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

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