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

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