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

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