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

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