You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RefDirectory.java 43KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. /*
  2. * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
  3. * Copyright (C) 2009-2010, Google Inc.
  4. * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
  5. * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org>
  6. * and other copyright owners as documented in the project's IP log.
  7. *
  8. * This program and the accompanying materials are made available
  9. * under the terms of the Eclipse Distribution License v1.0 which
  10. * accompanies this distribution, is reproduced below, and is
  11. * available at http://www.eclipse.org/org/documents/edl-v10.php
  12. *
  13. * All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or
  16. * without modification, are permitted provided that the following
  17. * conditions are met:
  18. *
  19. * - Redistributions of source code must retain the above copyright
  20. * notice, this list of conditions and the following disclaimer.
  21. *
  22. * - Redistributions in binary form must reproduce the above
  23. * copyright notice, this list of conditions and the following
  24. * disclaimer in the documentation and/or other materials provided
  25. * with the distribution.
  26. *
  27. * - Neither the name of the Eclipse Foundation, Inc. nor the
  28. * names of its contributors may be used to endorse or promote
  29. * products derived from this software without specific prior
  30. * written permission.
  31. *
  32. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  33. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  34. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  35. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  36. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  37. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  38. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  39. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  40. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  41. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  42. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  43. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  44. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. package org.eclipse.jgit.internal.storage.file;
  47. import static org.eclipse.jgit.lib.Constants.CHARSET;
  48. import static org.eclipse.jgit.lib.Constants.HEAD;
  49. import static org.eclipse.jgit.lib.Constants.LOGS;
  50. import static org.eclipse.jgit.lib.Constants.OBJECT_ID_STRING_LENGTH;
  51. import static org.eclipse.jgit.lib.Constants.PACKED_REFS;
  52. import static org.eclipse.jgit.lib.Constants.R_HEADS;
  53. import static org.eclipse.jgit.lib.Constants.R_REFS;
  54. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  55. import static org.eclipse.jgit.lib.Ref.Storage.LOOSE;
  56. import static org.eclipse.jgit.lib.Ref.Storage.NEW;
  57. import static org.eclipse.jgit.lib.Ref.Storage.PACKED;
  58. import java.io.BufferedReader;
  59. import java.io.File;
  60. import java.io.FileInputStream;
  61. import java.io.FileNotFoundException;
  62. import java.io.IOException;
  63. import java.io.InputStreamReader;
  64. import java.io.InterruptedIOException;
  65. import java.nio.file.DirectoryNotEmptyException;
  66. import java.nio.file.Files;
  67. import java.security.DigestInputStream;
  68. import java.security.MessageDigest;
  69. import java.text.MessageFormat;
  70. import java.util.Arrays;
  71. import java.util.Collection;
  72. import java.util.Collections;
  73. import java.util.LinkedList;
  74. import java.util.List;
  75. import java.util.Map;
  76. import java.util.concurrent.atomic.AtomicInteger;
  77. import java.util.concurrent.atomic.AtomicReference;
  78. import java.util.concurrent.locks.ReentrantLock;
  79. import org.eclipse.jgit.annotations.NonNull;
  80. import org.eclipse.jgit.annotations.Nullable;
  81. import org.eclipse.jgit.errors.InvalidObjectIdException;
  82. import org.eclipse.jgit.errors.LockFailedException;
  83. import org.eclipse.jgit.errors.MissingObjectException;
  84. import org.eclipse.jgit.errors.ObjectWritingException;
  85. import org.eclipse.jgit.events.RefsChangedEvent;
  86. import org.eclipse.jgit.internal.JGitText;
  87. import org.eclipse.jgit.lib.ConfigConstants;
  88. import org.eclipse.jgit.lib.Constants;
  89. import org.eclipse.jgit.lib.ObjectId;
  90. import org.eclipse.jgit.lib.ObjectIdRef;
  91. import org.eclipse.jgit.lib.Ref;
  92. import org.eclipse.jgit.lib.RefComparator;
  93. import org.eclipse.jgit.lib.RefDatabase;
  94. import org.eclipse.jgit.lib.RefUpdate;
  95. import org.eclipse.jgit.lib.RefWriter;
  96. import org.eclipse.jgit.lib.Repository;
  97. import org.eclipse.jgit.lib.SymbolicRef;
  98. import org.eclipse.jgit.revwalk.RevObject;
  99. import org.eclipse.jgit.revwalk.RevTag;
  100. import org.eclipse.jgit.revwalk.RevWalk;
  101. import org.eclipse.jgit.util.FS;
  102. import org.eclipse.jgit.util.FileUtils;
  103. import org.eclipse.jgit.util.IO;
  104. import org.eclipse.jgit.util.RawParseUtils;
  105. import org.eclipse.jgit.util.RefList;
  106. import org.eclipse.jgit.util.RefMap;
  107. import org.slf4j.Logger;
  108. import org.slf4j.LoggerFactory;
  109. /**
  110. * Traditional file system based {@link org.eclipse.jgit.lib.RefDatabase}.
  111. * <p>
  112. * This is the classical reference database representation for a Git repository.
  113. * References are stored in two formats: loose, and packed.
  114. * <p>
  115. * Loose references are stored as individual files within the {@code refs/}
  116. * directory. The file name matches the reference name and the file contents is
  117. * the current {@link org.eclipse.jgit.lib.ObjectId} in string form.
  118. * <p>
  119. * Packed references are stored in a single text file named {@code packed-refs}.
  120. * In the packed format, each reference is stored on its own line. This file
  121. * reduces the number of files needed for large reference spaces, reducing the
  122. * overall size of a Git repository on disk.
  123. */
  124. public class RefDirectory extends RefDatabase {
  125. private final static Logger LOG = LoggerFactory
  126. .getLogger(RefDirectory.class);
  127. /** Magic string denoting the start of a symbolic reference file. */
  128. public static final String SYMREF = "ref: "; //$NON-NLS-1$
  129. /** Magic string denoting the header of a packed-refs file. */
  130. public static final String PACKED_REFS_HEADER = "# pack-refs with:"; //$NON-NLS-1$
  131. /** If in the header, denotes the file has peeled data. */
  132. public static final String PACKED_REFS_PEELED = " peeled"; //$NON-NLS-1$
  133. /** The names of the additional refs supported by this class */
  134. private static final String[] additionalRefsNames = new String[] {
  135. Constants.MERGE_HEAD, Constants.FETCH_HEAD, Constants.ORIG_HEAD,
  136. Constants.CHERRY_PICK_HEAD };
  137. @SuppressWarnings("boxing")
  138. private static final List<Integer> RETRY_SLEEP_MS =
  139. Collections.unmodifiableList(Arrays.asList(0, 100, 200, 400, 800, 1600));
  140. private final FileRepository parent;
  141. private final File gitDir;
  142. final File refsDir;
  143. final File packedRefsFile;
  144. final File logsDir;
  145. final File logsRefsDir;
  146. /**
  147. * Immutable sorted list of loose references.
  148. * <p>
  149. * Symbolic references in this collection are stored unresolved, that is
  150. * their target appears to be a new reference with no ObjectId. These are
  151. * converted into resolved references during a get operation, ensuring the
  152. * live value is always returned.
  153. */
  154. private final AtomicReference<RefList<LooseRef>> looseRefs = new AtomicReference<>();
  155. /** Immutable sorted list of packed references. */
  156. final AtomicReference<PackedRefList> packedRefs = new AtomicReference<>();
  157. /**
  158. * Lock for coordinating operations within a single process that may contend
  159. * on the {@code packed-refs} file.
  160. * <p>
  161. * All operations that write {@code packed-refs} must still acquire a
  162. * {@link LockFile} on {@link #packedRefsFile}, even after they have acquired
  163. * this lock, since there may be multiple {@link RefDirectory} instances or
  164. * other processes operating on the same repo on disk.
  165. * <p>
  166. * This lock exists so multiple threads in the same process can wait in a fair
  167. * queue without trying, failing, and retrying to acquire the on-disk lock. If
  168. * {@code RepositoryCache} is used, this lock instance will be used by all
  169. * threads.
  170. */
  171. final ReentrantLock inProcessPackedRefsLock = new ReentrantLock(true);
  172. /**
  173. * Number of modifications made to this database.
  174. * <p>
  175. * This counter is incremented when a change is made, or detected from the
  176. * filesystem during a read operation.
  177. */
  178. private final AtomicInteger modCnt = new AtomicInteger();
  179. /**
  180. * Last {@link #modCnt} that we sent to listeners.
  181. * <p>
  182. * This value is compared to {@link #modCnt}, and a notification is sent to
  183. * the listeners only when it differs.
  184. */
  185. private final AtomicInteger lastNotifiedModCnt = new AtomicInteger();
  186. private List<Integer> retrySleepMs = RETRY_SLEEP_MS;
  187. RefDirectory(final FileRepository db) {
  188. final FS fs = db.getFS();
  189. parent = db;
  190. gitDir = db.getDirectory();
  191. refsDir = fs.resolve(gitDir, R_REFS);
  192. logsDir = fs.resolve(gitDir, LOGS);
  193. logsRefsDir = fs.resolve(gitDir, LOGS + '/' + R_REFS);
  194. packedRefsFile = fs.resolve(gitDir, PACKED_REFS);
  195. looseRefs.set(RefList.<LooseRef> emptyList());
  196. packedRefs.set(NO_PACKED_REFS);
  197. }
  198. Repository getRepository() {
  199. return parent;
  200. }
  201. ReflogWriter newLogWriter(boolean force) {
  202. return new ReflogWriter(this, force);
  203. }
  204. /**
  205. * Locate the log file on disk for a single reference name.
  206. *
  207. * @param name
  208. * name of the ref, relative to the Git repository top level
  209. * directory (so typically starts with refs/).
  210. * @return the log file location.
  211. */
  212. public File logFor(String name) {
  213. if (name.startsWith(R_REFS)) {
  214. name = name.substring(R_REFS.length());
  215. return new File(logsRefsDir, name);
  216. }
  217. return new File(logsDir, name);
  218. }
  219. /** {@inheritDoc} */
  220. @Override
  221. public void create() throws IOException {
  222. FileUtils.mkdir(refsDir);
  223. FileUtils.mkdir(new File(refsDir, R_HEADS.substring(R_REFS.length())));
  224. FileUtils.mkdir(new File(refsDir, R_TAGS.substring(R_REFS.length())));
  225. newLogWriter(false).create();
  226. }
  227. /** {@inheritDoc} */
  228. @Override
  229. public void close() {
  230. clearReferences();
  231. }
  232. private void clearReferences() {
  233. looseRefs.set(RefList.<LooseRef> emptyList());
  234. packedRefs.set(NO_PACKED_REFS);
  235. }
  236. /** {@inheritDoc} */
  237. @Override
  238. public void refresh() {
  239. super.refresh();
  240. clearReferences();
  241. }
  242. /** {@inheritDoc} */
  243. @Override
  244. public boolean isNameConflicting(String name) throws IOException {
  245. RefList<Ref> packed = getPackedRefs();
  246. RefList<LooseRef> loose = getLooseRefs();
  247. // Cannot be nested within an existing reference.
  248. int lastSlash = name.lastIndexOf('/');
  249. while (0 < lastSlash) {
  250. String needle = name.substring(0, lastSlash);
  251. if (loose.contains(needle) || packed.contains(needle))
  252. return true;
  253. lastSlash = name.lastIndexOf('/', lastSlash - 1);
  254. }
  255. // Cannot be the container of an existing reference.
  256. String prefix = name + '/';
  257. int idx;
  258. idx = -(packed.find(prefix) + 1);
  259. if (idx < packed.size() && packed.get(idx).getName().startsWith(prefix))
  260. return true;
  261. idx = -(loose.find(prefix) + 1);
  262. if (idx < loose.size() && loose.get(idx).getName().startsWith(prefix))
  263. return true;
  264. return false;
  265. }
  266. private RefList<LooseRef> getLooseRefs() {
  267. final RefList<LooseRef> oldLoose = looseRefs.get();
  268. LooseScanner scan = new LooseScanner(oldLoose);
  269. scan.scan(ALL);
  270. RefList<LooseRef> loose;
  271. if (scan.newLoose != null) {
  272. loose = scan.newLoose.toRefList();
  273. if (looseRefs.compareAndSet(oldLoose, loose))
  274. modCnt.incrementAndGet();
  275. } else
  276. loose = oldLoose;
  277. return loose;
  278. }
  279. /** {@inheritDoc} */
  280. @Override
  281. public Ref exactRef(String name) throws IOException {
  282. RefList<Ref> packed = getPackedRefs();
  283. Ref ref;
  284. try {
  285. ref = readRef(name, packed);
  286. if (ref != null) {
  287. ref = resolve(ref, 0, null, null, packed);
  288. }
  289. } catch (IOException e) {
  290. if (name.contains("/") //$NON-NLS-1$
  291. || !(e.getCause() instanceof InvalidObjectIdException)) {
  292. throw e;
  293. }
  294. // While looking for a ref outside of refs/ (e.g., 'config'), we
  295. // found a non-ref file (e.g., a config file) instead. Treat this
  296. // as a ref-not-found condition.
  297. ref = null;
  298. }
  299. fireRefsChanged();
  300. return ref;
  301. }
  302. /** {@inheritDoc} */
  303. @Override
  304. public Ref getRef(final String needle) throws IOException {
  305. final RefList<Ref> packed = getPackedRefs();
  306. Ref ref = null;
  307. for (String prefix : SEARCH_PATH) {
  308. try {
  309. ref = readRef(prefix + needle, packed);
  310. if (ref != null) {
  311. ref = resolve(ref, 0, null, null, packed);
  312. }
  313. if (ref != null) {
  314. break;
  315. }
  316. } catch (IOException e) {
  317. if (!(!needle.contains("/") && "".equals(prefix) && e //$NON-NLS-1$ //$NON-NLS-2$
  318. .getCause() instanceof InvalidObjectIdException)) {
  319. throw e;
  320. }
  321. }
  322. }
  323. fireRefsChanged();
  324. return ref;
  325. }
  326. /** {@inheritDoc} */
  327. @Override
  328. public Map<String, Ref> getRefs(String prefix) throws IOException {
  329. final RefList<LooseRef> oldLoose = looseRefs.get();
  330. LooseScanner scan = new LooseScanner(oldLoose);
  331. scan.scan(prefix);
  332. final RefList<Ref> packed = getPackedRefs();
  333. RefList<LooseRef> loose;
  334. if (scan.newLoose != null) {
  335. scan.newLoose.sort();
  336. loose = scan.newLoose.toRefList();
  337. if (looseRefs.compareAndSet(oldLoose, loose))
  338. modCnt.incrementAndGet();
  339. } else
  340. loose = oldLoose;
  341. fireRefsChanged();
  342. RefList.Builder<Ref> symbolic = scan.symbolic;
  343. for (int idx = 0; idx < symbolic.size();) {
  344. final Ref symbolicRef = symbolic.get(idx);
  345. final Ref resolvedRef = resolve(symbolicRef, 0, prefix, loose, packed);
  346. if (resolvedRef != null && resolvedRef.getObjectId() != null) {
  347. symbolic.set(idx, resolvedRef);
  348. idx++;
  349. } else {
  350. // A broken symbolic reference, we have to drop it from the
  351. // collections the client is about to receive. Should be a
  352. // rare occurrence so pay a copy penalty.
  353. symbolic.remove(idx);
  354. final int toRemove = loose.find(symbolicRef.getName());
  355. if (0 <= toRemove)
  356. loose = loose.remove(toRemove);
  357. }
  358. }
  359. symbolic.sort();
  360. return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList());
  361. }
  362. /** {@inheritDoc} */
  363. @Override
  364. public List<Ref> getAdditionalRefs() throws IOException {
  365. List<Ref> ret = new LinkedList<>();
  366. for (String name : additionalRefsNames) {
  367. Ref r = getRef(name);
  368. if (r != null)
  369. ret.add(r);
  370. }
  371. return ret;
  372. }
  373. @SuppressWarnings("unchecked")
  374. private RefList<Ref> upcast(RefList<? extends Ref> loose) {
  375. return (RefList<Ref>) loose;
  376. }
  377. private class LooseScanner {
  378. private final RefList<LooseRef> curLoose;
  379. private int curIdx;
  380. final RefList.Builder<Ref> symbolic = new RefList.Builder<>(4);
  381. RefList.Builder<LooseRef> newLoose;
  382. LooseScanner(final RefList<LooseRef> curLoose) {
  383. this.curLoose = curLoose;
  384. }
  385. void scan(String prefix) {
  386. if (ALL.equals(prefix)) {
  387. scanOne(HEAD);
  388. scanTree(R_REFS, refsDir);
  389. // If any entries remain, they are deleted, drop them.
  390. if (newLoose == null && curIdx < curLoose.size())
  391. newLoose = curLoose.copy(curIdx);
  392. } else if (prefix.startsWith(R_REFS) && prefix.endsWith("/")) { //$NON-NLS-1$
  393. curIdx = -(curLoose.find(prefix) + 1);
  394. File dir = new File(refsDir, prefix.substring(R_REFS.length()));
  395. scanTree(prefix, dir);
  396. // Skip over entries still within the prefix; these have
  397. // been removed from the directory.
  398. while (curIdx < curLoose.size()) {
  399. if (!curLoose.get(curIdx).getName().startsWith(prefix))
  400. break;
  401. if (newLoose == null)
  402. newLoose = curLoose.copy(curIdx);
  403. curIdx++;
  404. }
  405. // Keep any entries outside of the prefix space, we
  406. // do not know anything about their status.
  407. if (newLoose != null) {
  408. while (curIdx < curLoose.size())
  409. newLoose.add(curLoose.get(curIdx++));
  410. }
  411. }
  412. }
  413. private boolean scanTree(String prefix, File dir) {
  414. final String[] entries = dir.list(LockFile.FILTER);
  415. if (entries == null) // not a directory or an I/O error
  416. return false;
  417. if (0 < entries.length) {
  418. for (int i = 0; i < entries.length; ++i) {
  419. String e = entries[i];
  420. File f = new File(dir, e);
  421. if (f.isDirectory())
  422. entries[i] += '/';
  423. }
  424. Arrays.sort(entries);
  425. for (String name : entries) {
  426. if (name.charAt(name.length() - 1) == '/')
  427. scanTree(prefix + name, new File(dir, name));
  428. else
  429. scanOne(prefix + name);
  430. }
  431. }
  432. return true;
  433. }
  434. private void scanOne(String name) {
  435. LooseRef cur;
  436. if (curIdx < curLoose.size()) {
  437. do {
  438. cur = curLoose.get(curIdx);
  439. int cmp = RefComparator.compareTo(cur, name);
  440. if (cmp < 0) {
  441. // Reference is not loose anymore, its been deleted.
  442. // Skip the name in the new result list.
  443. if (newLoose == null)
  444. newLoose = curLoose.copy(curIdx);
  445. curIdx++;
  446. cur = null;
  447. continue;
  448. }
  449. if (cmp > 0) // Newly discovered loose reference.
  450. cur = null;
  451. break;
  452. } while (curIdx < curLoose.size());
  453. } else
  454. cur = null; // Newly discovered loose reference.
  455. LooseRef n;
  456. try {
  457. n = scanRef(cur, name);
  458. } catch (IOException notValid) {
  459. n = null;
  460. }
  461. if (n != null) {
  462. if (cur != n && newLoose == null)
  463. newLoose = curLoose.copy(curIdx);
  464. if (newLoose != null)
  465. newLoose.add(n);
  466. if (n.isSymbolic())
  467. symbolic.add(n);
  468. } else if (cur != null) {
  469. // Tragically, this file is no longer a loose reference.
  470. // Kill our cached entry of it.
  471. if (newLoose == null)
  472. newLoose = curLoose.copy(curIdx);
  473. }
  474. if (cur != null)
  475. curIdx++;
  476. }
  477. }
  478. /** {@inheritDoc} */
  479. @Override
  480. public Ref peel(final Ref ref) throws IOException {
  481. final Ref leaf = ref.getLeaf();
  482. if (leaf.isPeeled() || leaf.getObjectId() == null)
  483. return ref;
  484. ObjectIdRef newLeaf = doPeel(leaf);
  485. // Try to remember this peeling in the cache, so we don't have to do
  486. // it again in the future, but only if the reference is unchanged.
  487. if (leaf.getStorage().isLoose()) {
  488. RefList<LooseRef> curList = looseRefs.get();
  489. int idx = curList.find(leaf.getName());
  490. if (0 <= idx && curList.get(idx) == leaf) {
  491. LooseRef asPeeled = ((LooseRef) leaf).peel(newLeaf);
  492. RefList<LooseRef> newList = curList.set(idx, asPeeled);
  493. looseRefs.compareAndSet(curList, newList);
  494. }
  495. }
  496. return recreate(ref, newLeaf);
  497. }
  498. private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException,
  499. IOException {
  500. try (RevWalk rw = new RevWalk(getRepository())) {
  501. RevObject obj = rw.parseAny(leaf.getObjectId());
  502. if (obj instanceof RevTag) {
  503. return new ObjectIdRef.PeeledTag(leaf.getStorage(), leaf
  504. .getName(), leaf.getObjectId(), rw.peel(obj).copy());
  505. } else {
  506. return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf
  507. .getName(), leaf.getObjectId());
  508. }
  509. }
  510. }
  511. private static Ref recreate(final Ref old, final ObjectIdRef leaf) {
  512. if (old.isSymbolic()) {
  513. Ref dst = recreate(old.getTarget(), leaf);
  514. return new SymbolicRef(old.getName(), dst);
  515. }
  516. return leaf;
  517. }
  518. void storedSymbolicRef(RefDirectoryUpdate u, FileSnapshot snapshot,
  519. String target) {
  520. putLooseRef(newSymbolicRef(snapshot, u.getRef().getName(), target));
  521. fireRefsChanged();
  522. }
  523. /** {@inheritDoc} */
  524. @Override
  525. public RefDirectoryUpdate newUpdate(String name, boolean detach)
  526. throws IOException {
  527. boolean detachingSymbolicRef = false;
  528. final RefList<Ref> packed = getPackedRefs();
  529. Ref ref = readRef(name, packed);
  530. if (ref != null)
  531. ref = resolve(ref, 0, null, null, packed);
  532. if (ref == null)
  533. ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  534. else {
  535. detachingSymbolicRef = detach && ref.isSymbolic();
  536. }
  537. RefDirectoryUpdate refDirUpdate = new RefDirectoryUpdate(this, ref);
  538. if (detachingSymbolicRef)
  539. refDirUpdate.setDetachingSymbolicRef();
  540. return refDirUpdate;
  541. }
  542. /** {@inheritDoc} */
  543. @Override
  544. public RefDirectoryRename newRename(String fromName, String toName)
  545. throws IOException {
  546. RefDirectoryUpdate from = newUpdate(fromName, false);
  547. RefDirectoryUpdate to = newUpdate(toName, false);
  548. return new RefDirectoryRename(from, to);
  549. }
  550. /** {@inheritDoc} */
  551. @Override
  552. public PackedBatchRefUpdate newBatchUpdate() {
  553. return new PackedBatchRefUpdate(this);
  554. }
  555. /** {@inheritDoc} */
  556. @Override
  557. public boolean performsAtomicTransactions() {
  558. return true;
  559. }
  560. void stored(RefDirectoryUpdate update, FileSnapshot snapshot) {
  561. final ObjectId target = update.getNewObjectId().copy();
  562. final Ref leaf = update.getRef().getLeaf();
  563. putLooseRef(new LooseUnpeeled(snapshot, leaf.getName(), target));
  564. }
  565. private void putLooseRef(LooseRef ref) {
  566. RefList<LooseRef> cList, nList;
  567. do {
  568. cList = looseRefs.get();
  569. nList = cList.put(ref);
  570. } while (!looseRefs.compareAndSet(cList, nList));
  571. modCnt.incrementAndGet();
  572. fireRefsChanged();
  573. }
  574. void delete(RefDirectoryUpdate update) throws IOException {
  575. Ref dst = update.getRef();
  576. if (!update.isDetachingSymbolicRef()) {
  577. dst = dst.getLeaf();
  578. }
  579. String name = dst.getName();
  580. // Write the packed-refs file using an atomic update. We might
  581. // wind up reading it twice, before and after the lock, to ensure
  582. // we don't miss an edit made externally.
  583. final PackedRefList packed = getPackedRefs();
  584. if (packed.contains(name)) {
  585. inProcessPackedRefsLock.lock();
  586. try {
  587. LockFile lck = lockPackedRefsOrThrow();
  588. try {
  589. PackedRefList cur = readPackedRefs();
  590. int idx = cur.find(name);
  591. if (0 <= idx) {
  592. commitPackedRefs(lck, cur.remove(idx), packed, true);
  593. }
  594. } finally {
  595. lck.unlock();
  596. }
  597. } finally {
  598. inProcessPackedRefsLock.unlock();
  599. }
  600. }
  601. RefList<LooseRef> curLoose, newLoose;
  602. do {
  603. curLoose = looseRefs.get();
  604. int idx = curLoose.find(name);
  605. if (idx < 0)
  606. break;
  607. newLoose = curLoose.remove(idx);
  608. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  609. int levels = levelsIn(name) - 2;
  610. delete(logFor(name), levels);
  611. if (dst.getStorage().isLoose()) {
  612. update.unlock();
  613. delete(fileFor(name), levels);
  614. }
  615. modCnt.incrementAndGet();
  616. fireRefsChanged();
  617. }
  618. /**
  619. * Adds a set of refs to the set of packed-refs. Only non-symbolic refs are
  620. * added. If a ref with the given name already existed in packed-refs it is
  621. * updated with the new value. Each loose ref which was added to the
  622. * packed-ref file is deleted. If a given ref can't be locked it will not be
  623. * added to the pack file.
  624. *
  625. * @param refs
  626. * the refs to be added. Must be fully qualified.
  627. * @throws java.io.IOException
  628. */
  629. public void pack(List<String> refs) throws IOException {
  630. pack(refs, Collections.emptyMap());
  631. }
  632. PackedRefList pack(Map<String, LockFile> heldLocks) throws IOException {
  633. return pack(heldLocks.keySet(), heldLocks);
  634. }
  635. private PackedRefList pack(Collection<String> refs,
  636. Map<String, LockFile> heldLocks) throws IOException {
  637. for (LockFile ol : heldLocks.values()) {
  638. ol.requireLock();
  639. }
  640. if (refs.size() == 0) {
  641. return null;
  642. }
  643. FS fs = parent.getFS();
  644. // Lock the packed refs file and read the content
  645. inProcessPackedRefsLock.lock();
  646. try {
  647. LockFile lck = lockPackedRefsOrThrow();
  648. try {
  649. final PackedRefList packed = getPackedRefs();
  650. RefList<Ref> cur = readPackedRefs();
  651. // Iterate over all refs to be packed
  652. boolean dirty = false;
  653. for (String refName : refs) {
  654. Ref oldRef = readRef(refName, cur);
  655. if (oldRef == null) {
  656. continue; // A non-existent ref is already correctly packed.
  657. }
  658. if (oldRef.isSymbolic()) {
  659. continue; // can't pack symbolic refs
  660. }
  661. // Add/Update it to packed-refs
  662. Ref newRef = peeledPackedRef(oldRef);
  663. if (newRef == oldRef) {
  664. // No-op; peeledPackedRef returns the input ref only if it's already
  665. // packed, and readRef returns a packed ref only if there is no
  666. // loose ref.
  667. continue;
  668. }
  669. dirty = true;
  670. int idx = cur.find(refName);
  671. if (idx >= 0) {
  672. cur = cur.set(idx, newRef);
  673. } else {
  674. cur = cur.add(idx, newRef);
  675. }
  676. }
  677. if (!dirty) {
  678. // All requested refs were already packed accurately
  679. return packed;
  680. }
  681. // The new content for packed-refs is collected. Persist it.
  682. PackedRefList result = commitPackedRefs(lck, cur, packed,
  683. false);
  684. // Now delete the loose refs which are now packed
  685. for (String refName : refs) {
  686. // Lock the loose ref
  687. File refFile = fileFor(refName);
  688. if (!fs.exists(refFile)) {
  689. continue;
  690. }
  691. LockFile rLck = heldLocks.get(refName);
  692. boolean shouldUnlock;
  693. if (rLck == null) {
  694. rLck = new LockFile(refFile);
  695. if (!rLck.lock()) {
  696. continue;
  697. }
  698. shouldUnlock = true;
  699. } else {
  700. shouldUnlock = false;
  701. }
  702. try {
  703. LooseRef currentLooseRef = scanRef(null, refName);
  704. if (currentLooseRef == null || currentLooseRef.isSymbolic()) {
  705. continue;
  706. }
  707. Ref packedRef = cur.get(refName);
  708. ObjectId clr_oid = currentLooseRef.getObjectId();
  709. if (clr_oid != null
  710. && clr_oid.equals(packedRef.getObjectId())) {
  711. RefList<LooseRef> curLoose, newLoose;
  712. do {
  713. curLoose = looseRefs.get();
  714. int idx = curLoose.find(refName);
  715. if (idx < 0) {
  716. break;
  717. }
  718. newLoose = curLoose.remove(idx);
  719. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  720. int levels = levelsIn(refName) - 2;
  721. delete(refFile, levels, rLck);
  722. }
  723. } finally {
  724. if (shouldUnlock) {
  725. rLck.unlock();
  726. }
  727. }
  728. }
  729. // Don't fire refsChanged. The refs have not change, only their
  730. // storage.
  731. return result;
  732. } finally {
  733. lck.unlock();
  734. }
  735. } finally {
  736. inProcessPackedRefsLock.unlock();
  737. }
  738. }
  739. @Nullable
  740. LockFile lockPackedRefs() throws IOException {
  741. LockFile lck = new LockFile(packedRefsFile);
  742. for (int ms : getRetrySleepMs()) {
  743. sleep(ms);
  744. if (lck.lock()) {
  745. return lck;
  746. }
  747. }
  748. return null;
  749. }
  750. private LockFile lockPackedRefsOrThrow() throws IOException {
  751. LockFile lck = lockPackedRefs();
  752. if (lck == null) {
  753. throw new LockFailedException(packedRefsFile);
  754. }
  755. return lck;
  756. }
  757. /**
  758. * Make sure a ref is peeled and has the Storage PACKED. If the given ref
  759. * has this attributes simply return it. Otherwise create a new peeled
  760. * {@link ObjectIdRef} where Storage is set to PACKED.
  761. *
  762. * @param f
  763. * @return a ref for Storage PACKED having the same name, id, peeledId as f
  764. * @throws MissingObjectException
  765. * @throws IOException
  766. */
  767. private Ref peeledPackedRef(Ref f)
  768. throws MissingObjectException, IOException {
  769. if (f.getStorage().isPacked() && f.isPeeled()) {
  770. return f;
  771. }
  772. if (!f.isPeeled()) {
  773. f = peel(f);
  774. }
  775. ObjectId peeledObjectId = f.getPeeledObjectId();
  776. if (peeledObjectId != null) {
  777. return new ObjectIdRef.PeeledTag(PACKED, f.getName(),
  778. f.getObjectId(), peeledObjectId);
  779. } else {
  780. return new ObjectIdRef.PeeledNonTag(PACKED, f.getName(),
  781. f.getObjectId());
  782. }
  783. }
  784. void log(boolean force, RefUpdate update, String msg, boolean deref)
  785. throws IOException {
  786. newLogWriter(force).log(update, msg, deref);
  787. }
  788. private Ref resolve(final Ref ref, int depth, String prefix,
  789. RefList<LooseRef> loose, RefList<Ref> packed) throws IOException {
  790. if (ref.isSymbolic()) {
  791. Ref dst = ref.getTarget();
  792. if (MAX_SYMBOLIC_REF_DEPTH <= depth)
  793. return null; // claim it doesn't exist
  794. // If the cached value can be assumed to be current due to a
  795. // recent scan of the loose directory, use it.
  796. if (loose != null && dst.getName().startsWith(prefix)) {
  797. int idx;
  798. if (0 <= (idx = loose.find(dst.getName())))
  799. dst = loose.get(idx);
  800. else if (0 <= (idx = packed.find(dst.getName())))
  801. dst = packed.get(idx);
  802. else
  803. return ref;
  804. } else {
  805. dst = readRef(dst.getName(), packed);
  806. if (dst == null)
  807. return ref;
  808. }
  809. dst = resolve(dst, depth + 1, prefix, loose, packed);
  810. if (dst == null)
  811. return null;
  812. return new SymbolicRef(ref.getName(), dst);
  813. }
  814. return ref;
  815. }
  816. PackedRefList getPackedRefs() throws IOException {
  817. boolean trustFolderStat = getRepository().getConfig().getBoolean(
  818. ConfigConstants.CONFIG_CORE_SECTION,
  819. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  820. final PackedRefList curList = packedRefs.get();
  821. if (trustFolderStat && !curList.snapshot.isModified(packedRefsFile)) {
  822. return curList;
  823. }
  824. final PackedRefList newList = readPackedRefs();
  825. if (packedRefs.compareAndSet(curList, newList)
  826. && !curList.id.equals(newList.id)) {
  827. modCnt.incrementAndGet();
  828. }
  829. return newList;
  830. }
  831. private PackedRefList readPackedRefs() throws IOException {
  832. int maxStaleRetries = 5;
  833. int retries = 0;
  834. while (true) {
  835. final FileSnapshot snapshot = FileSnapshot.save(packedRefsFile);
  836. final BufferedReader br;
  837. final MessageDigest digest = Constants.newMessageDigest();
  838. try {
  839. br = new BufferedReader(new InputStreamReader(
  840. new DigestInputStream(new FileInputStream(packedRefsFile),
  841. digest), CHARSET));
  842. } catch (FileNotFoundException noPackedRefs) {
  843. if (packedRefsFile.exists()) {
  844. throw noPackedRefs;
  845. }
  846. // Ignore it and leave the new list empty.
  847. return NO_PACKED_REFS;
  848. }
  849. try {
  850. return new PackedRefList(parsePackedRefs(br), snapshot,
  851. ObjectId.fromRaw(digest.digest()));
  852. } catch (IOException e) {
  853. if (FileUtils.isStaleFileHandleInCausalChain(e)
  854. && retries < maxStaleRetries) {
  855. if (LOG.isDebugEnabled()) {
  856. LOG.debug(MessageFormat.format(
  857. JGitText.get().packedRefsHandleIsStale,
  858. Integer.valueOf(retries)), e);
  859. }
  860. retries++;
  861. continue;
  862. }
  863. throw e;
  864. } finally {
  865. br.close();
  866. }
  867. }
  868. }
  869. private RefList<Ref> parsePackedRefs(final BufferedReader br)
  870. throws IOException {
  871. RefList.Builder<Ref> all = new RefList.Builder<>();
  872. Ref last = null;
  873. boolean peeled = false;
  874. boolean needSort = false;
  875. String p;
  876. while ((p = br.readLine()) != null) {
  877. if (p.charAt(0) == '#') {
  878. if (p.startsWith(PACKED_REFS_HEADER)) {
  879. p = p.substring(PACKED_REFS_HEADER.length());
  880. peeled = p.contains(PACKED_REFS_PEELED);
  881. }
  882. continue;
  883. }
  884. if (p.charAt(0) == '^') {
  885. if (last == null)
  886. throw new IOException(JGitText.get().peeledLineBeforeRef);
  887. ObjectId id = ObjectId.fromString(p.substring(1));
  888. last = new ObjectIdRef.PeeledTag(PACKED, last.getName(), last
  889. .getObjectId(), id);
  890. all.set(all.size() - 1, last);
  891. continue;
  892. }
  893. int sp = p.indexOf(' ');
  894. if (sp < 0) {
  895. throw new IOException(MessageFormat.format(
  896. JGitText.get().packedRefsCorruptionDetected,
  897. packedRefsFile.getAbsolutePath()));
  898. }
  899. ObjectId id = ObjectId.fromString(p.substring(0, sp));
  900. String name = copy(p, sp + 1, p.length());
  901. ObjectIdRef cur;
  902. if (peeled)
  903. cur = new ObjectIdRef.PeeledNonTag(PACKED, name, id);
  904. else
  905. cur = new ObjectIdRef.Unpeeled(PACKED, name, id);
  906. if (last != null && RefComparator.compareTo(last, cur) > 0)
  907. needSort = true;
  908. all.add(cur);
  909. last = cur;
  910. }
  911. if (needSort)
  912. all.sort();
  913. return all.toRefList();
  914. }
  915. private static String copy(final String src, final int off, final int end) {
  916. // Don't use substring since it could leave a reference to the much
  917. // larger existing string. Force construction of a full new object.
  918. return new StringBuilder(end - off).append(src, off, end).toString();
  919. }
  920. PackedRefList commitPackedRefs(final LockFile lck, final RefList<Ref> refs,
  921. final PackedRefList oldPackedList, boolean changed)
  922. throws IOException {
  923. // Can't just return packedRefs.get() from this method; it might have been
  924. // updated again after writePackedRefs() returns.
  925. AtomicReference<PackedRefList> result = new AtomicReference<>();
  926. new RefWriter(refs) {
  927. @Override
  928. protected void writeFile(String name, byte[] content)
  929. throws IOException {
  930. lck.setFSync(true);
  931. lck.setNeedSnapshot(true);
  932. try {
  933. lck.write(content);
  934. } catch (IOException ioe) {
  935. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name), ioe);
  936. }
  937. try {
  938. lck.waitForStatChange();
  939. } catch (InterruptedException e) {
  940. lck.unlock();
  941. throw new ObjectWritingException(MessageFormat.format(JGitText.get().interruptedWriting, name));
  942. }
  943. if (!lck.commit())
  944. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name));
  945. byte[] digest = Constants.newMessageDigest().digest(content);
  946. PackedRefList newPackedList = new PackedRefList(
  947. refs, lck.getCommitSnapshot(), ObjectId.fromRaw(digest));
  948. // This thread holds the file lock, so no other thread or process should
  949. // be able to modify the packed-refs file on disk. If the list changed,
  950. // it means something is very wrong, so throw an exception.
  951. //
  952. // However, we can't use a naive compareAndSet to check whether the
  953. // update was successful, because another thread might _read_ the
  954. // packed refs file that was written out by this thread while holding
  955. // the lock, and update the packedRefs reference to point to that. So
  956. // compare the actual contents instead.
  957. PackedRefList afterUpdate = packedRefs.updateAndGet(
  958. p -> p.id.equals(oldPackedList.id) ? newPackedList : p);
  959. if (!afterUpdate.id.equals(newPackedList.id)) {
  960. throw new ObjectWritingException(
  961. MessageFormat.format(JGitText.get().unableToWrite, name));
  962. }
  963. if (changed) {
  964. modCnt.incrementAndGet();
  965. }
  966. result.set(newPackedList);
  967. }
  968. }.writePackedRefs();
  969. return result.get();
  970. }
  971. private Ref readRef(String name, RefList<Ref> packed) throws IOException {
  972. final RefList<LooseRef> curList = looseRefs.get();
  973. final int idx = curList.find(name);
  974. if (0 <= idx) {
  975. final LooseRef o = curList.get(idx);
  976. final LooseRef n = scanRef(o, name);
  977. if (n == null) {
  978. if (looseRefs.compareAndSet(curList, curList.remove(idx)))
  979. modCnt.incrementAndGet();
  980. return packed.get(name);
  981. }
  982. if (o == n)
  983. return n;
  984. if (looseRefs.compareAndSet(curList, curList.set(idx, n)))
  985. modCnt.incrementAndGet();
  986. return n;
  987. }
  988. final LooseRef n = scanRef(null, name);
  989. if (n == null)
  990. return packed.get(name);
  991. // check whether the found new ref is the an additional ref. These refs
  992. // should not go into looseRefs
  993. for (int i = 0; i < additionalRefsNames.length; i++)
  994. if (name.equals(additionalRefsNames[i]))
  995. return n;
  996. if (looseRefs.compareAndSet(curList, curList.add(idx, n)))
  997. modCnt.incrementAndGet();
  998. return n;
  999. }
  1000. LooseRef scanRef(LooseRef ref, String name) throws IOException {
  1001. final File path = fileFor(name);
  1002. FileSnapshot currentSnapshot = null;
  1003. if (ref != null) {
  1004. currentSnapshot = ref.getSnapShot();
  1005. if (!currentSnapshot.isModified(path))
  1006. return ref;
  1007. name = ref.getName();
  1008. }
  1009. final int limit = 4096;
  1010. final byte[] buf;
  1011. FileSnapshot otherSnapshot = FileSnapshot.save(path);
  1012. try {
  1013. buf = IO.readSome(path, limit);
  1014. } catch (FileNotFoundException noFile) {
  1015. if (path.exists() && path.isFile()) {
  1016. throw noFile;
  1017. }
  1018. return null; // doesn't exist or no file; not a reference.
  1019. }
  1020. int n = buf.length;
  1021. if (n == 0)
  1022. return null; // empty file; not a reference.
  1023. if (isSymRef(buf, n)) {
  1024. if (n == limit)
  1025. return null; // possibly truncated ref
  1026. // trim trailing whitespace
  1027. while (0 < n && Character.isWhitespace(buf[n - 1]))
  1028. n--;
  1029. if (n < 6) {
  1030. String content = RawParseUtils.decode(buf, 0, n);
  1031. throw new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
  1032. }
  1033. final String target = RawParseUtils.decode(buf, 5, n);
  1034. if (ref != null && ref.isSymbolic()
  1035. && ref.getTarget().getName().equals(target)) {
  1036. assert(currentSnapshot != null);
  1037. currentSnapshot.setClean(otherSnapshot);
  1038. return ref;
  1039. }
  1040. return newSymbolicRef(otherSnapshot, name, target);
  1041. }
  1042. if (n < OBJECT_ID_STRING_LENGTH)
  1043. return null; // impossibly short object identifier; not a reference.
  1044. final ObjectId id;
  1045. try {
  1046. id = ObjectId.fromString(buf, 0);
  1047. if (ref != null && !ref.isSymbolic()
  1048. && id.equals(ref.getTarget().getObjectId())) {
  1049. assert(currentSnapshot != null);
  1050. currentSnapshot.setClean(otherSnapshot);
  1051. return ref;
  1052. }
  1053. } catch (IllegalArgumentException notRef) {
  1054. while (0 < n && Character.isWhitespace(buf[n - 1]))
  1055. n--;
  1056. String content = RawParseUtils.decode(buf, 0, n);
  1057. throw new IOException(MessageFormat.format(JGitText.get().notARef,
  1058. name, content), notRef);
  1059. }
  1060. return new LooseUnpeeled(otherSnapshot, name, id);
  1061. }
  1062. private static boolean isSymRef(final byte[] buf, int n) {
  1063. if (n < 6)
  1064. return false;
  1065. return /**/buf[0] == 'r' //
  1066. && buf[1] == 'e' //
  1067. && buf[2] == 'f' //
  1068. && buf[3] == ':' //
  1069. && buf[4] == ' ';
  1070. }
  1071. /**
  1072. * Detect if we are in a clone command execution
  1073. *
  1074. * @return {@code true} if we are currently cloning a repository
  1075. * @throws IOException
  1076. */
  1077. boolean isInClone() throws IOException {
  1078. return hasDanglingHead() && !packedRefsFile.exists() && !hasLooseRef();
  1079. }
  1080. private boolean hasDanglingHead() throws IOException {
  1081. Ref head = exactRef(Constants.HEAD);
  1082. if (head != null) {
  1083. ObjectId id = head.getObjectId();
  1084. return id == null || id.equals(ObjectId.zeroId());
  1085. }
  1086. return false;
  1087. }
  1088. private boolean hasLooseRef() throws IOException {
  1089. return Files.walk(refsDir.toPath()).anyMatch(Files::isRegularFile);
  1090. }
  1091. /** If the parent should fire listeners, fires them. */
  1092. void fireRefsChanged() {
  1093. final int last = lastNotifiedModCnt.get();
  1094. final int curr = modCnt.get();
  1095. if (last != curr && lastNotifiedModCnt.compareAndSet(last, curr) && last != 0)
  1096. parent.fireEvent(new RefsChangedEvent());
  1097. }
  1098. /**
  1099. * Create a reference update to write a temporary reference.
  1100. *
  1101. * @return an update for a new temporary reference.
  1102. * @throws IOException
  1103. * a temporary name cannot be allocated.
  1104. */
  1105. RefDirectoryUpdate newTemporaryUpdate() throws IOException {
  1106. File tmp = File.createTempFile("renamed_", "_ref", refsDir); //$NON-NLS-1$ //$NON-NLS-2$
  1107. String name = Constants.R_REFS + tmp.getName();
  1108. Ref ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  1109. return new RefDirectoryUpdate(this, ref);
  1110. }
  1111. /**
  1112. * Locate the file on disk for a single reference name.
  1113. *
  1114. * @param name
  1115. * name of the ref, relative to the Git repository top level
  1116. * directory (so typically starts with refs/).
  1117. * @return the loose file location.
  1118. */
  1119. File fileFor(String name) {
  1120. if (name.startsWith(R_REFS)) {
  1121. name = name.substring(R_REFS.length());
  1122. return new File(refsDir, name);
  1123. }
  1124. return new File(gitDir, name);
  1125. }
  1126. static int levelsIn(final String name) {
  1127. int count = 0;
  1128. for (int p = name.indexOf('/'); p >= 0; p = name.indexOf('/', p + 1))
  1129. count++;
  1130. return count;
  1131. }
  1132. static void delete(final File file, final int depth) throws IOException {
  1133. delete(file, depth, null);
  1134. }
  1135. private static void delete(final File file, final int depth, LockFile rLck)
  1136. throws IOException {
  1137. if (!file.delete() && file.isFile()) {
  1138. throw new IOException(MessageFormat.format(
  1139. JGitText.get().fileCannotBeDeleted, file));
  1140. }
  1141. if (rLck != null) {
  1142. rLck.unlock(); // otherwise cannot delete dir below
  1143. }
  1144. File dir = file.getParentFile();
  1145. for (int i = 0; i < depth; ++i) {
  1146. try {
  1147. Files.delete(dir.toPath());
  1148. } catch (DirectoryNotEmptyException e) {
  1149. // Don't log; normal case when there are other refs with the
  1150. // same prefix
  1151. break;
  1152. } catch (IOException e) {
  1153. LOG.warn("Unable to remove path {}", dir, e);
  1154. break;
  1155. }
  1156. dir = dir.getParentFile();
  1157. }
  1158. }
  1159. /**
  1160. * Get times to sleep while retrying a possibly contentious operation.
  1161. * <p>
  1162. * For retrying an operation that might have high contention, such as locking
  1163. * the {@code packed-refs} file, the caller may implement a retry loop using
  1164. * the returned values:
  1165. *
  1166. * <pre>
  1167. * for (int toSleepMs : getRetrySleepMs()) {
  1168. * sleep(toSleepMs);
  1169. * if (isSuccessful(doSomething())) {
  1170. * return success;
  1171. * }
  1172. * }
  1173. * return failure;
  1174. * </pre>
  1175. *
  1176. * The first value in the returned iterable is 0, and the caller should treat
  1177. * a fully-consumed iterator as a timeout.
  1178. *
  1179. * @return iterable of times, in milliseconds, that the caller should sleep
  1180. * before attempting an operation.
  1181. */
  1182. Iterable<Integer> getRetrySleepMs() {
  1183. return retrySleepMs;
  1184. }
  1185. void setRetrySleepMs(List<Integer> retrySleepMs) {
  1186. if (retrySleepMs == null || retrySleepMs.isEmpty()
  1187. || retrySleepMs.get(0).intValue() != 0) {
  1188. throw new IllegalArgumentException();
  1189. }
  1190. this.retrySleepMs = retrySleepMs;
  1191. }
  1192. /**
  1193. * Sleep with {@link Thread#sleep(long)}, converting {@link
  1194. * InterruptedException} to {@link InterruptedIOException}.
  1195. *
  1196. * @param ms
  1197. * time to sleep, in milliseconds; zero or negative is a no-op.
  1198. * @throws InterruptedIOException
  1199. * if sleeping was interrupted.
  1200. */
  1201. static void sleep(long ms) throws InterruptedIOException {
  1202. if (ms <= 0) {
  1203. return;
  1204. }
  1205. try {
  1206. Thread.sleep(ms);
  1207. } catch (InterruptedException e) {
  1208. InterruptedIOException ie = new InterruptedIOException();
  1209. ie.initCause(e);
  1210. throw ie;
  1211. }
  1212. }
  1213. static class PackedRefList extends RefList<Ref> {
  1214. private final FileSnapshot snapshot;
  1215. private final ObjectId id;
  1216. private PackedRefList(RefList<Ref> src, FileSnapshot s, ObjectId i) {
  1217. super(src);
  1218. snapshot = s;
  1219. id = i;
  1220. }
  1221. }
  1222. private static final PackedRefList NO_PACKED_REFS = new PackedRefList(
  1223. RefList.emptyList(), FileSnapshot.MISSING_FILE,
  1224. ObjectId.zeroId());
  1225. private static LooseSymbolicRef newSymbolicRef(FileSnapshot snapshot,
  1226. String name, String target) {
  1227. Ref dst = new ObjectIdRef.Unpeeled(NEW, target, null);
  1228. return new LooseSymbolicRef(snapshot, name, dst);
  1229. }
  1230. private static interface LooseRef extends Ref {
  1231. FileSnapshot getSnapShot();
  1232. LooseRef peel(ObjectIdRef newLeaf);
  1233. }
  1234. private final static class LoosePeeledTag extends ObjectIdRef.PeeledTag
  1235. implements LooseRef {
  1236. private final FileSnapshot snapShot;
  1237. LoosePeeledTag(FileSnapshot snapshot, @NonNull String refName,
  1238. @NonNull ObjectId id, @NonNull ObjectId p) {
  1239. super(LOOSE, refName, id, p);
  1240. this.snapShot = snapshot;
  1241. }
  1242. @Override
  1243. public FileSnapshot getSnapShot() {
  1244. return snapShot;
  1245. }
  1246. @Override
  1247. public LooseRef peel(ObjectIdRef newLeaf) {
  1248. return this;
  1249. }
  1250. }
  1251. private final static class LooseNonTag extends ObjectIdRef.PeeledNonTag
  1252. implements LooseRef {
  1253. private final FileSnapshot snapShot;
  1254. LooseNonTag(FileSnapshot snapshot, @NonNull String refName,
  1255. @NonNull ObjectId id) {
  1256. super(LOOSE, refName, id);
  1257. this.snapShot = snapshot;
  1258. }
  1259. @Override
  1260. public FileSnapshot getSnapShot() {
  1261. return snapShot;
  1262. }
  1263. @Override
  1264. public LooseRef peel(ObjectIdRef newLeaf) {
  1265. return this;
  1266. }
  1267. }
  1268. private final static class LooseUnpeeled extends ObjectIdRef.Unpeeled
  1269. implements LooseRef {
  1270. private FileSnapshot snapShot;
  1271. LooseUnpeeled(FileSnapshot snapShot, @NonNull String refName,
  1272. @NonNull ObjectId id) {
  1273. super(LOOSE, refName, id);
  1274. this.snapShot = snapShot;
  1275. }
  1276. @Override
  1277. public FileSnapshot getSnapShot() {
  1278. return snapShot;
  1279. }
  1280. @NonNull
  1281. @Override
  1282. public ObjectId getObjectId() {
  1283. ObjectId id = super.getObjectId();
  1284. assert id != null; // checked in constructor
  1285. return id;
  1286. }
  1287. @Override
  1288. public LooseRef peel(ObjectIdRef newLeaf) {
  1289. ObjectId peeledObjectId = newLeaf.getPeeledObjectId();
  1290. ObjectId objectId = getObjectId();
  1291. if (peeledObjectId != null) {
  1292. return new LoosePeeledTag(snapShot, getName(),
  1293. objectId, peeledObjectId);
  1294. } else {
  1295. return new LooseNonTag(snapShot, getName(),
  1296. objectId);
  1297. }
  1298. }
  1299. }
  1300. private final static class LooseSymbolicRef extends SymbolicRef implements
  1301. LooseRef {
  1302. private final FileSnapshot snapShot;
  1303. LooseSymbolicRef(FileSnapshot snapshot, @NonNull String refName,
  1304. @NonNull Ref target) {
  1305. super(refName, target);
  1306. this.snapShot = snapshot;
  1307. }
  1308. @Override
  1309. public FileSnapshot getSnapShot() {
  1310. return snapShot;
  1311. }
  1312. @Override
  1313. public LooseRef peel(ObjectIdRef newLeaf) {
  1314. // We should never try to peel the symbolic references.
  1315. throw new UnsupportedOperationException();
  1316. }
  1317. }
  1318. }