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 42KB

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