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

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