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

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