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

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