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

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