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

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