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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  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 static final 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. }
  503. return new ObjectIdRef.PeeledNonTag(leaf.getStorage(),
  504. leaf.getName(), leaf.getObjectId());
  505. }
  506. }
  507. private static Ref recreate(Ref old, ObjectIdRef leaf) {
  508. if (old.isSymbolic()) {
  509. Ref dst = recreate(old.getTarget(), leaf);
  510. return new SymbolicRef(old.getName(), dst);
  511. }
  512. return leaf;
  513. }
  514. void storedSymbolicRef(RefDirectoryUpdate u, FileSnapshot snapshot,
  515. String target) {
  516. putLooseRef(newSymbolicRef(snapshot, u.getRef().getName(), target));
  517. fireRefsChanged();
  518. }
  519. /** {@inheritDoc} */
  520. @Override
  521. public RefDirectoryUpdate newUpdate(String name, boolean detach)
  522. throws IOException {
  523. boolean detachingSymbolicRef = false;
  524. final RefList<Ref> packed = getPackedRefs();
  525. Ref ref = readRef(name, packed);
  526. if (ref != null)
  527. ref = resolve(ref, 0, null, null, packed);
  528. if (ref == null)
  529. ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  530. else {
  531. detachingSymbolicRef = detach && ref.isSymbolic();
  532. }
  533. RefDirectoryUpdate refDirUpdate = new RefDirectoryUpdate(this, ref);
  534. if (detachingSymbolicRef)
  535. refDirUpdate.setDetachingSymbolicRef();
  536. return refDirUpdate;
  537. }
  538. /** {@inheritDoc} */
  539. @Override
  540. public RefDirectoryRename newRename(String fromName, String toName)
  541. throws IOException {
  542. RefDirectoryUpdate from = newUpdate(fromName, false);
  543. RefDirectoryUpdate to = newUpdate(toName, false);
  544. return new RefDirectoryRename(from, to);
  545. }
  546. /** {@inheritDoc} */
  547. @Override
  548. public PackedBatchRefUpdate newBatchUpdate() {
  549. return new PackedBatchRefUpdate(this);
  550. }
  551. /** {@inheritDoc} */
  552. @Override
  553. public boolean performsAtomicTransactions() {
  554. return true;
  555. }
  556. void stored(RefDirectoryUpdate update, FileSnapshot snapshot) {
  557. final ObjectId target = update.getNewObjectId().copy();
  558. final Ref leaf = update.getRef().getLeaf();
  559. putLooseRef(new LooseUnpeeled(snapshot, leaf.getName(), target));
  560. }
  561. private void putLooseRef(LooseRef ref) {
  562. RefList<LooseRef> cList, nList;
  563. do {
  564. cList = looseRefs.get();
  565. nList = cList.put(ref);
  566. } while (!looseRefs.compareAndSet(cList, nList));
  567. modCnt.incrementAndGet();
  568. fireRefsChanged();
  569. }
  570. void delete(RefDirectoryUpdate update) throws IOException {
  571. Ref dst = update.getRef();
  572. if (!update.isDetachingSymbolicRef()) {
  573. dst = dst.getLeaf();
  574. }
  575. String name = dst.getName();
  576. // Write the packed-refs file using an atomic update. We might
  577. // wind up reading it twice, before and after the lock, to ensure
  578. // we don't miss an edit made externally.
  579. final PackedRefList packed = getPackedRefs();
  580. if (packed.contains(name)) {
  581. inProcessPackedRefsLock.lock();
  582. try {
  583. LockFile lck = lockPackedRefsOrThrow();
  584. try {
  585. PackedRefList cur = readPackedRefs();
  586. int idx = cur.find(name);
  587. if (0 <= idx) {
  588. commitPackedRefs(lck, cur.remove(idx), packed, true);
  589. }
  590. } finally {
  591. lck.unlock();
  592. }
  593. } finally {
  594. inProcessPackedRefsLock.unlock();
  595. }
  596. }
  597. RefList<LooseRef> curLoose, newLoose;
  598. do {
  599. curLoose = looseRefs.get();
  600. int idx = curLoose.find(name);
  601. if (idx < 0)
  602. break;
  603. newLoose = curLoose.remove(idx);
  604. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  605. int levels = levelsIn(name) - 2;
  606. delete(logFor(name), levels);
  607. if (dst.getStorage().isLoose()) {
  608. update.unlock();
  609. delete(fileFor(name), levels);
  610. }
  611. modCnt.incrementAndGet();
  612. fireRefsChanged();
  613. }
  614. /**
  615. * Adds a set of refs to the set of packed-refs. Only non-symbolic refs are
  616. * added. If a ref with the given name already existed in packed-refs it is
  617. * updated with the new value. Each loose ref which was added to the
  618. * packed-ref file is deleted. If a given ref can't be locked it will not be
  619. * added to the pack file.
  620. *
  621. * @param refs
  622. * the refs to be added. Must be fully qualified.
  623. * @throws java.io.IOException
  624. */
  625. public void pack(List<String> refs) throws IOException {
  626. pack(refs, Collections.emptyMap());
  627. }
  628. PackedRefList pack(Map<String, LockFile> heldLocks) throws IOException {
  629. return pack(heldLocks.keySet(), heldLocks);
  630. }
  631. private PackedRefList pack(Collection<String> refs,
  632. Map<String, LockFile> heldLocks) throws IOException {
  633. for (LockFile ol : heldLocks.values()) {
  634. ol.requireLock();
  635. }
  636. if (refs.isEmpty()) {
  637. return null;
  638. }
  639. FS fs = parent.getFS();
  640. // Lock the packed refs file and read the content
  641. inProcessPackedRefsLock.lock();
  642. try {
  643. LockFile lck = lockPackedRefsOrThrow();
  644. try {
  645. final PackedRefList packed = getPackedRefs();
  646. RefList<Ref> cur = readPackedRefs();
  647. // Iterate over all refs to be packed
  648. boolean dirty = false;
  649. for (String refName : refs) {
  650. Ref oldRef = readRef(refName, cur);
  651. if (oldRef == null) {
  652. continue; // A non-existent ref is already correctly packed.
  653. }
  654. if (oldRef.isSymbolic()) {
  655. continue; // can't pack symbolic refs
  656. }
  657. // Add/Update it to packed-refs
  658. Ref newRef = peeledPackedRef(oldRef);
  659. if (newRef == oldRef) {
  660. // No-op; peeledPackedRef returns the input ref only if it's already
  661. // packed, and readRef returns a packed ref only if there is no
  662. // loose ref.
  663. continue;
  664. }
  665. dirty = true;
  666. int idx = cur.find(refName);
  667. if (idx >= 0) {
  668. cur = cur.set(idx, newRef);
  669. } else {
  670. cur = cur.add(idx, newRef);
  671. }
  672. }
  673. if (!dirty) {
  674. // All requested refs were already packed accurately
  675. return packed;
  676. }
  677. // The new content for packed-refs is collected. Persist it.
  678. PackedRefList result = commitPackedRefs(lck, cur, packed,
  679. false);
  680. // Now delete the loose refs which are now packed
  681. for (String refName : refs) {
  682. // Lock the loose ref
  683. File refFile = fileFor(refName);
  684. if (!fs.exists(refFile)) {
  685. continue;
  686. }
  687. LockFile rLck = heldLocks.get(refName);
  688. boolean shouldUnlock;
  689. if (rLck == null) {
  690. rLck = new LockFile(refFile);
  691. if (!rLck.lock()) {
  692. continue;
  693. }
  694. shouldUnlock = true;
  695. } else {
  696. shouldUnlock = false;
  697. }
  698. try {
  699. LooseRef currentLooseRef = scanRef(null, refName);
  700. if (currentLooseRef == null || currentLooseRef.isSymbolic()) {
  701. continue;
  702. }
  703. Ref packedRef = cur.get(refName);
  704. ObjectId clr_oid = currentLooseRef.getObjectId();
  705. if (clr_oid != null
  706. && clr_oid.equals(packedRef.getObjectId())) {
  707. RefList<LooseRef> curLoose, newLoose;
  708. do {
  709. curLoose = looseRefs.get();
  710. int idx = curLoose.find(refName);
  711. if (idx < 0) {
  712. break;
  713. }
  714. newLoose = curLoose.remove(idx);
  715. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  716. int levels = levelsIn(refName) - 2;
  717. delete(refFile, levels, rLck);
  718. }
  719. } finally {
  720. if (shouldUnlock) {
  721. rLck.unlock();
  722. }
  723. }
  724. }
  725. // Don't fire refsChanged. The refs have not change, only their
  726. // storage.
  727. return result;
  728. } finally {
  729. lck.unlock();
  730. }
  731. } finally {
  732. inProcessPackedRefsLock.unlock();
  733. }
  734. }
  735. @Nullable
  736. LockFile lockPackedRefs() throws IOException {
  737. LockFile lck = new LockFile(packedRefsFile);
  738. for (int ms : getRetrySleepMs()) {
  739. sleep(ms);
  740. if (lck.lock()) {
  741. return lck;
  742. }
  743. }
  744. return null;
  745. }
  746. private LockFile lockPackedRefsOrThrow() throws IOException {
  747. LockFile lck = lockPackedRefs();
  748. if (lck == null) {
  749. throw new LockFailedException(packedRefsFile);
  750. }
  751. return lck;
  752. }
  753. /**
  754. * Make sure a ref is peeled and has the Storage PACKED. If the given ref
  755. * has this attributes simply return it. Otherwise create a new peeled
  756. * {@link ObjectIdRef} where Storage is set to PACKED.
  757. *
  758. * @param f
  759. * @return a ref for Storage PACKED having the same name, id, peeledId as f
  760. * @throws MissingObjectException
  761. * @throws IOException
  762. */
  763. private Ref peeledPackedRef(Ref f)
  764. throws MissingObjectException, IOException {
  765. if (f.getStorage().isPacked() && f.isPeeled()) {
  766. return f;
  767. }
  768. if (!f.isPeeled()) {
  769. f = peel(f);
  770. }
  771. ObjectId peeledObjectId = f.getPeeledObjectId();
  772. if (peeledObjectId != null) {
  773. return new ObjectIdRef.PeeledTag(PACKED, f.getName(),
  774. f.getObjectId(), peeledObjectId);
  775. }
  776. return new ObjectIdRef.PeeledNonTag(PACKED, f.getName(),
  777. f.getObjectId());
  778. }
  779. void log(boolean force, RefUpdate update, String msg, boolean deref)
  780. throws IOException {
  781. newLogWriter(force).log(update, msg, deref);
  782. }
  783. private Ref resolve(final Ref ref, int depth, String prefix,
  784. RefList<LooseRef> loose, RefList<Ref> packed) throws IOException {
  785. if (ref.isSymbolic()) {
  786. Ref dst = ref.getTarget();
  787. if (MAX_SYMBOLIC_REF_DEPTH <= depth)
  788. return null; // claim it doesn't exist
  789. // If the cached value can be assumed to be current due to a
  790. // recent scan of the loose directory, use it.
  791. if (loose != null && dst.getName().startsWith(prefix)) {
  792. int idx;
  793. if (0 <= (idx = loose.find(dst.getName())))
  794. dst = loose.get(idx);
  795. else if (0 <= (idx = packed.find(dst.getName())))
  796. dst = packed.get(idx);
  797. else
  798. return ref;
  799. } else {
  800. dst = readRef(dst.getName(), packed);
  801. if (dst == null)
  802. return ref;
  803. }
  804. dst = resolve(dst, depth + 1, prefix, loose, packed);
  805. if (dst == null)
  806. return null;
  807. return new SymbolicRef(ref.getName(), dst);
  808. }
  809. return ref;
  810. }
  811. PackedRefList getPackedRefs() throws IOException {
  812. boolean trustFolderStat = getRepository().getConfig().getBoolean(
  813. ConfigConstants.CONFIG_CORE_SECTION,
  814. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  815. final PackedRefList curList = packedRefs.get();
  816. if (trustFolderStat && !curList.snapshot.isModified(packedRefsFile)) {
  817. return curList;
  818. }
  819. final PackedRefList newList = readPackedRefs();
  820. if (packedRefs.compareAndSet(curList, newList)
  821. && !curList.id.equals(newList.id)) {
  822. modCnt.incrementAndGet();
  823. }
  824. return newList;
  825. }
  826. private PackedRefList readPackedRefs() throws IOException {
  827. int maxStaleRetries = 5;
  828. int retries = 0;
  829. while (true) {
  830. final FileSnapshot snapshot = FileSnapshot.save(packedRefsFile);
  831. final MessageDigest digest = Constants.newMessageDigest();
  832. try (BufferedReader br = new BufferedReader(new InputStreamReader(
  833. new DigestInputStream(new FileInputStream(packedRefsFile),
  834. digest),
  835. UTF_8))) {
  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. }
  852. } catch (FileNotFoundException noPackedRefs) {
  853. if (packedRefsFile.exists()) {
  854. throw noPackedRefs;
  855. }
  856. // Ignore it and leave the new list empty.
  857. return NO_PACKED_REFS;
  858. }
  859. }
  860. }
  861. private RefList<Ref> parsePackedRefs(BufferedReader br)
  862. throws IOException {
  863. RefList.Builder<Ref> all = new RefList.Builder<>();
  864. Ref last = null;
  865. boolean peeled = false;
  866. boolean needSort = false;
  867. String p;
  868. while ((p = br.readLine()) != null) {
  869. if (p.charAt(0) == '#') {
  870. if (p.startsWith(PACKED_REFS_HEADER)) {
  871. p = p.substring(PACKED_REFS_HEADER.length());
  872. peeled = p.contains(PACKED_REFS_PEELED);
  873. }
  874. continue;
  875. }
  876. if (p.charAt(0) == '^') {
  877. if (last == null)
  878. throw new IOException(JGitText.get().peeledLineBeforeRef);
  879. ObjectId id = ObjectId.fromString(p.substring(1));
  880. last = new ObjectIdRef.PeeledTag(PACKED, last.getName(), last
  881. .getObjectId(), id);
  882. all.set(all.size() - 1, last);
  883. continue;
  884. }
  885. int sp = p.indexOf(' ');
  886. if (sp < 0) {
  887. throw new IOException(MessageFormat.format(
  888. JGitText.get().packedRefsCorruptionDetected,
  889. packedRefsFile.getAbsolutePath()));
  890. }
  891. ObjectId id = ObjectId.fromString(p.substring(0, sp));
  892. String name = copy(p, sp + 1, p.length());
  893. ObjectIdRef cur;
  894. if (peeled)
  895. cur = new ObjectIdRef.PeeledNonTag(PACKED, name, id);
  896. else
  897. cur = new ObjectIdRef.Unpeeled(PACKED, name, id);
  898. if (last != null && RefComparator.compareTo(last, cur) > 0)
  899. needSort = true;
  900. all.add(cur);
  901. last = cur;
  902. }
  903. if (needSort)
  904. all.sort();
  905. return all.toRefList();
  906. }
  907. private static String copy(String src, int off, int end) {
  908. // Don't use substring since it could leave a reference to the much
  909. // larger existing string. Force construction of a full new object.
  910. return new StringBuilder(end - off).append(src, off, end).toString();
  911. }
  912. PackedRefList commitPackedRefs(final LockFile lck, final RefList<Ref> refs,
  913. final PackedRefList oldPackedList, boolean changed)
  914. throws IOException {
  915. // Can't just return packedRefs.get() from this method; it might have been
  916. // updated again after writePackedRefs() returns.
  917. AtomicReference<PackedRefList> result = new AtomicReference<>();
  918. new RefWriter(refs) {
  919. @Override
  920. protected void writeFile(String name, byte[] content)
  921. throws IOException {
  922. lck.setFSync(true);
  923. lck.setNeedSnapshot(true);
  924. try {
  925. lck.write(content);
  926. } catch (IOException ioe) {
  927. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name), ioe);
  928. }
  929. try {
  930. lck.waitForStatChange();
  931. } catch (InterruptedException e) {
  932. lck.unlock();
  933. throw new ObjectWritingException(MessageFormat.format(JGitText.get().interruptedWriting, name));
  934. }
  935. if (!lck.commit())
  936. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name));
  937. byte[] digest = Constants.newMessageDigest().digest(content);
  938. PackedRefList newPackedList = new PackedRefList(
  939. refs, lck.getCommitSnapshot(), ObjectId.fromRaw(digest));
  940. // This thread holds the file lock, so no other thread or process should
  941. // be able to modify the packed-refs file on disk. If the list changed,
  942. // it means something is very wrong, so throw an exception.
  943. //
  944. // However, we can't use a naive compareAndSet to check whether the
  945. // update was successful, because another thread might _read_ the
  946. // packed refs file that was written out by this thread while holding
  947. // the lock, and update the packedRefs reference to point to that. So
  948. // compare the actual contents instead.
  949. PackedRefList afterUpdate = packedRefs.updateAndGet(
  950. p -> p.id.equals(oldPackedList.id) ? newPackedList : p);
  951. if (!afterUpdate.id.equals(newPackedList.id)) {
  952. throw new ObjectWritingException(
  953. MessageFormat.format(JGitText.get().unableToWrite, name));
  954. }
  955. if (changed) {
  956. modCnt.incrementAndGet();
  957. }
  958. result.set(newPackedList);
  959. }
  960. }.writePackedRefs();
  961. return result.get();
  962. }
  963. private Ref readRef(String name, RefList<Ref> packed) throws IOException {
  964. final RefList<LooseRef> curList = looseRefs.get();
  965. final int idx = curList.find(name);
  966. if (0 <= idx) {
  967. final LooseRef o = curList.get(idx);
  968. final LooseRef n = scanRef(o, name);
  969. if (n == null) {
  970. if (looseRefs.compareAndSet(curList, curList.remove(idx)))
  971. modCnt.incrementAndGet();
  972. return packed.get(name);
  973. }
  974. if (o == n)
  975. return n;
  976. if (looseRefs.compareAndSet(curList, curList.set(idx, n)))
  977. modCnt.incrementAndGet();
  978. return n;
  979. }
  980. final LooseRef n = scanRef(null, name);
  981. if (n == null)
  982. return packed.get(name);
  983. // check whether the found new ref is the an additional ref. These refs
  984. // should not go into looseRefs
  985. for (String additionalRefsName : additionalRefsNames) {
  986. if (name.equals(additionalRefsName)) {
  987. return n;
  988. }
  989. }
  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 static final 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 static final 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 static final 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. }
  1292. return new LooseNonTag(snapShot, getName(), objectId);
  1293. }
  1294. }
  1295. private static final class LooseSymbolicRef extends SymbolicRef implements
  1296. LooseRef {
  1297. private final FileSnapshot snapShot;
  1298. LooseSymbolicRef(FileSnapshot snapshot, @NonNull String refName,
  1299. @NonNull Ref target) {
  1300. super(refName, target);
  1301. this.snapShot = snapshot;
  1302. }
  1303. @Override
  1304. public FileSnapshot getSnapShot() {
  1305. return snapShot;
  1306. }
  1307. @Override
  1308. public LooseRef peel(ObjectIdRef newLeaf) {
  1309. // We should never try to peel the symbolic references.
  1310. throw new UnsupportedOperationException();
  1311. }
  1312. }
  1313. }