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