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 44KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  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 Ref getRef(String needle) throws IOException {
  348. try {
  349. RefList<Ref> packed = getPackedRefs();
  350. for (String prefix : SEARCH_PATH) {
  351. Ref ref = readAndResolve(prefix + needle, packed);
  352. if (ref != null) {
  353. return ref;
  354. }
  355. }
  356. return null;
  357. } finally {
  358. fireRefsChanged();
  359. }
  360. }
  361. /** {@inheritDoc} */
  362. @Override
  363. public Map<String, Ref> getRefs(String prefix) throws IOException {
  364. final RefList<LooseRef> oldLoose = looseRefs.get();
  365. LooseScanner scan = new LooseScanner(oldLoose);
  366. scan.scan(prefix);
  367. final RefList<Ref> packed = getPackedRefs();
  368. RefList<LooseRef> loose;
  369. if (scan.newLoose != null) {
  370. scan.newLoose.sort();
  371. loose = scan.newLoose.toRefList();
  372. if (looseRefs.compareAndSet(oldLoose, loose))
  373. modCnt.incrementAndGet();
  374. } else
  375. loose = oldLoose;
  376. fireRefsChanged();
  377. RefList.Builder<Ref> symbolic = scan.symbolic;
  378. for (int idx = 0; idx < symbolic.size();) {
  379. final Ref symbolicRef = symbolic.get(idx);
  380. final Ref resolvedRef = resolve(symbolicRef, 0, prefix, loose, packed);
  381. if (resolvedRef != null && resolvedRef.getObjectId() != null) {
  382. symbolic.set(idx, resolvedRef);
  383. idx++;
  384. } else {
  385. // A broken symbolic reference, we have to drop it from the
  386. // collections the client is about to receive. Should be a
  387. // rare occurrence so pay a copy penalty.
  388. symbolic.remove(idx);
  389. final int toRemove = loose.find(symbolicRef.getName());
  390. if (0 <= toRemove)
  391. loose = loose.remove(toRemove);
  392. }
  393. }
  394. symbolic.sort();
  395. return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList());
  396. }
  397. /** {@inheritDoc} */
  398. @Override
  399. public List<Ref> getAdditionalRefs() throws IOException {
  400. List<Ref> ret = new LinkedList<>();
  401. for (String name : additionalRefsNames) {
  402. Ref r = exactRef(name);
  403. if (r != null)
  404. ret.add(r);
  405. }
  406. return ret;
  407. }
  408. @SuppressWarnings("unchecked")
  409. private RefList<Ref> upcast(RefList<? extends Ref> loose) {
  410. return (RefList<Ref>) loose;
  411. }
  412. private class LooseScanner {
  413. private final RefList<LooseRef> curLoose;
  414. private int curIdx;
  415. final RefList.Builder<Ref> symbolic = new RefList.Builder<>(4);
  416. RefList.Builder<LooseRef> newLoose;
  417. LooseScanner(RefList<LooseRef> curLoose) {
  418. this.curLoose = curLoose;
  419. }
  420. void scan(String prefix) {
  421. if (ALL.equals(prefix)) {
  422. scanOne(HEAD);
  423. scanTree(R_REFS, refsDir);
  424. // If any entries remain, they are deleted, drop them.
  425. if (newLoose == null && curIdx < curLoose.size())
  426. newLoose = curLoose.copy(curIdx);
  427. } else if (prefix.startsWith(R_REFS) && prefix.endsWith("/")) { //$NON-NLS-1$
  428. curIdx = -(curLoose.find(prefix) + 1);
  429. File dir = new File(refsDir, prefix.substring(R_REFS.length()));
  430. scanTree(prefix, dir);
  431. // Skip over entries still within the prefix; these have
  432. // been removed from the directory.
  433. while (curIdx < curLoose.size()) {
  434. if (!curLoose.get(curIdx).getName().startsWith(prefix))
  435. break;
  436. if (newLoose == null)
  437. newLoose = curLoose.copy(curIdx);
  438. curIdx++;
  439. }
  440. // Keep any entries outside of the prefix space, we
  441. // do not know anything about their status.
  442. if (newLoose != null) {
  443. while (curIdx < curLoose.size())
  444. newLoose.add(curLoose.get(curIdx++));
  445. }
  446. }
  447. }
  448. private boolean scanTree(String prefix, File dir) {
  449. final String[] entries = dir.list(LockFile.FILTER);
  450. if (entries == null) // not a directory or an I/O error
  451. return false;
  452. if (0 < entries.length) {
  453. for (int i = 0; i < entries.length; ++i) {
  454. String e = entries[i];
  455. File f = new File(dir, e);
  456. if (f.isDirectory())
  457. entries[i] += '/';
  458. }
  459. Arrays.sort(entries);
  460. for (String name : entries) {
  461. if (name.charAt(name.length() - 1) == '/')
  462. scanTree(prefix + name, new File(dir, name));
  463. else
  464. scanOne(prefix + name);
  465. }
  466. }
  467. return true;
  468. }
  469. private void scanOne(String name) {
  470. LooseRef cur;
  471. if (curIdx < curLoose.size()) {
  472. do {
  473. cur = curLoose.get(curIdx);
  474. int cmp = RefComparator.compareTo(cur, name);
  475. if (cmp < 0) {
  476. // Reference is not loose anymore, its been deleted.
  477. // Skip the name in the new result list.
  478. if (newLoose == null)
  479. newLoose = curLoose.copy(curIdx);
  480. curIdx++;
  481. cur = null;
  482. continue;
  483. }
  484. if (cmp > 0) // Newly discovered loose reference.
  485. cur = null;
  486. break;
  487. } while (curIdx < curLoose.size());
  488. } else
  489. cur = null; // Newly discovered loose reference.
  490. LooseRef n;
  491. try {
  492. n = scanRef(cur, name);
  493. } catch (IOException notValid) {
  494. n = null;
  495. }
  496. if (n != null) {
  497. if (cur != n && newLoose == null)
  498. newLoose = curLoose.copy(curIdx);
  499. if (newLoose != null)
  500. newLoose.add(n);
  501. if (n.isSymbolic())
  502. symbolic.add(n);
  503. } else if (cur != null) {
  504. // Tragically, this file is no longer a loose reference.
  505. // Kill our cached entry of it.
  506. if (newLoose == null)
  507. newLoose = curLoose.copy(curIdx);
  508. }
  509. if (cur != null)
  510. curIdx++;
  511. }
  512. }
  513. /** {@inheritDoc} */
  514. @Override
  515. public Ref peel(Ref ref) throws IOException {
  516. final Ref leaf = ref.getLeaf();
  517. if (leaf.isPeeled() || leaf.getObjectId() == null)
  518. return ref;
  519. ObjectIdRef newLeaf = doPeel(leaf);
  520. // Try to remember this peeling in the cache, so we don't have to do
  521. // it again in the future, but only if the reference is unchanged.
  522. if (leaf.getStorage().isLoose()) {
  523. RefList<LooseRef> curList = looseRefs.get();
  524. int idx = curList.find(leaf.getName());
  525. if (0 <= idx && curList.get(idx) == leaf) {
  526. LooseRef asPeeled = ((LooseRef) leaf).peel(newLeaf);
  527. RefList<LooseRef> newList = curList.set(idx, asPeeled);
  528. looseRefs.compareAndSet(curList, newList);
  529. }
  530. }
  531. return recreate(ref, newLeaf);
  532. }
  533. private ObjectIdRef doPeel(Ref leaf) throws MissingObjectException,
  534. IOException {
  535. try (RevWalk rw = new RevWalk(getRepository())) {
  536. RevObject obj = rw.parseAny(leaf.getObjectId());
  537. if (obj instanceof RevTag) {
  538. return new ObjectIdRef.PeeledTag(leaf.getStorage(), leaf
  539. .getName(), leaf.getObjectId(), rw.peel(obj).copy());
  540. } else {
  541. return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf
  542. .getName(), leaf.getObjectId());
  543. }
  544. }
  545. }
  546. private static Ref recreate(Ref old, ObjectIdRef leaf) {
  547. if (old.isSymbolic()) {
  548. Ref dst = recreate(old.getTarget(), leaf);
  549. return new SymbolicRef(old.getName(), dst);
  550. }
  551. return leaf;
  552. }
  553. void storedSymbolicRef(RefDirectoryUpdate u, FileSnapshot snapshot,
  554. String target) {
  555. putLooseRef(newSymbolicRef(snapshot, u.getRef().getName(), target));
  556. fireRefsChanged();
  557. }
  558. /** {@inheritDoc} */
  559. @Override
  560. public RefDirectoryUpdate newUpdate(String name, boolean detach)
  561. throws IOException {
  562. boolean detachingSymbolicRef = false;
  563. final RefList<Ref> packed = getPackedRefs();
  564. Ref ref = readRef(name, packed);
  565. if (ref != null)
  566. ref = resolve(ref, 0, null, null, packed);
  567. if (ref == null)
  568. ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  569. else {
  570. detachingSymbolicRef = detach && ref.isSymbolic();
  571. }
  572. RefDirectoryUpdate refDirUpdate = new RefDirectoryUpdate(this, ref);
  573. if (detachingSymbolicRef)
  574. refDirUpdate.setDetachingSymbolicRef();
  575. return refDirUpdate;
  576. }
  577. /** {@inheritDoc} */
  578. @Override
  579. public RefDirectoryRename newRename(String fromName, String toName)
  580. throws IOException {
  581. RefDirectoryUpdate from = newUpdate(fromName, false);
  582. RefDirectoryUpdate to = newUpdate(toName, false);
  583. return new RefDirectoryRename(from, to);
  584. }
  585. /** {@inheritDoc} */
  586. @Override
  587. public PackedBatchRefUpdate newBatchUpdate() {
  588. return new PackedBatchRefUpdate(this);
  589. }
  590. /** {@inheritDoc} */
  591. @Override
  592. public boolean performsAtomicTransactions() {
  593. return true;
  594. }
  595. void stored(RefDirectoryUpdate update, FileSnapshot snapshot) {
  596. final ObjectId target = update.getNewObjectId().copy();
  597. final Ref leaf = update.getRef().getLeaf();
  598. putLooseRef(new LooseUnpeeled(snapshot, leaf.getName(), target));
  599. }
  600. private void putLooseRef(LooseRef ref) {
  601. RefList<LooseRef> cList, nList;
  602. do {
  603. cList = looseRefs.get();
  604. nList = cList.put(ref);
  605. } while (!looseRefs.compareAndSet(cList, nList));
  606. modCnt.incrementAndGet();
  607. fireRefsChanged();
  608. }
  609. void delete(RefDirectoryUpdate update) throws IOException {
  610. Ref dst = update.getRef();
  611. if (!update.isDetachingSymbolicRef()) {
  612. dst = dst.getLeaf();
  613. }
  614. String name = dst.getName();
  615. // Write the packed-refs file using an atomic update. We might
  616. // wind up reading it twice, before and after the lock, to ensure
  617. // we don't miss an edit made externally.
  618. final PackedRefList packed = getPackedRefs();
  619. if (packed.contains(name)) {
  620. inProcessPackedRefsLock.lock();
  621. try {
  622. LockFile lck = lockPackedRefsOrThrow();
  623. try {
  624. PackedRefList cur = readPackedRefs();
  625. int idx = cur.find(name);
  626. if (0 <= idx) {
  627. commitPackedRefs(lck, cur.remove(idx), packed, true);
  628. }
  629. } finally {
  630. lck.unlock();
  631. }
  632. } finally {
  633. inProcessPackedRefsLock.unlock();
  634. }
  635. }
  636. RefList<LooseRef> curLoose, newLoose;
  637. do {
  638. curLoose = looseRefs.get();
  639. int idx = curLoose.find(name);
  640. if (idx < 0)
  641. break;
  642. newLoose = curLoose.remove(idx);
  643. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  644. int levels = levelsIn(name) - 2;
  645. delete(logFor(name), levels);
  646. if (dst.getStorage().isLoose()) {
  647. update.unlock();
  648. delete(fileFor(name), levels);
  649. }
  650. modCnt.incrementAndGet();
  651. fireRefsChanged();
  652. }
  653. /**
  654. * Adds a set of refs to the set of packed-refs. Only non-symbolic refs are
  655. * added. If a ref with the given name already existed in packed-refs it is
  656. * updated with the new value. Each loose ref which was added to the
  657. * packed-ref file is deleted. If a given ref can't be locked it will not be
  658. * added to the pack file.
  659. *
  660. * @param refs
  661. * the refs to be added. Must be fully qualified.
  662. * @throws java.io.IOException
  663. */
  664. public void pack(List<String> refs) throws IOException {
  665. pack(refs, Collections.emptyMap());
  666. }
  667. PackedRefList pack(Map<String, LockFile> heldLocks) throws IOException {
  668. return pack(heldLocks.keySet(), heldLocks);
  669. }
  670. private PackedRefList pack(Collection<String> refs,
  671. Map<String, LockFile> heldLocks) throws IOException {
  672. for (LockFile ol : heldLocks.values()) {
  673. ol.requireLock();
  674. }
  675. if (refs.size() == 0) {
  676. return null;
  677. }
  678. FS fs = parent.getFS();
  679. // Lock the packed refs file and read the content
  680. inProcessPackedRefsLock.lock();
  681. try {
  682. LockFile lck = lockPackedRefsOrThrow();
  683. try {
  684. final PackedRefList packed = getPackedRefs();
  685. RefList<Ref> cur = readPackedRefs();
  686. // Iterate over all refs to be packed
  687. boolean dirty = false;
  688. for (String refName : refs) {
  689. Ref oldRef = readRef(refName, cur);
  690. if (oldRef == null) {
  691. continue; // A non-existent ref is already correctly packed.
  692. }
  693. if (oldRef.isSymbolic()) {
  694. continue; // can't pack symbolic refs
  695. }
  696. // Add/Update it to packed-refs
  697. Ref newRef = peeledPackedRef(oldRef);
  698. if (newRef == oldRef) {
  699. // No-op; peeledPackedRef returns the input ref only if it's already
  700. // packed, and readRef returns a packed ref only if there is no
  701. // loose ref.
  702. continue;
  703. }
  704. dirty = true;
  705. int idx = cur.find(refName);
  706. if (idx >= 0) {
  707. cur = cur.set(idx, newRef);
  708. } else {
  709. cur = cur.add(idx, newRef);
  710. }
  711. }
  712. if (!dirty) {
  713. // All requested refs were already packed accurately
  714. return packed;
  715. }
  716. // The new content for packed-refs is collected. Persist it.
  717. PackedRefList result = commitPackedRefs(lck, cur, packed,
  718. false);
  719. // Now delete the loose refs which are now packed
  720. for (String refName : refs) {
  721. // Lock the loose ref
  722. File refFile = fileFor(refName);
  723. if (!fs.exists(refFile)) {
  724. continue;
  725. }
  726. LockFile rLck = heldLocks.get(refName);
  727. boolean shouldUnlock;
  728. if (rLck == null) {
  729. rLck = new LockFile(refFile);
  730. if (!rLck.lock()) {
  731. continue;
  732. }
  733. shouldUnlock = true;
  734. } else {
  735. shouldUnlock = false;
  736. }
  737. try {
  738. LooseRef currentLooseRef = scanRef(null, refName);
  739. if (currentLooseRef == null || currentLooseRef.isSymbolic()) {
  740. continue;
  741. }
  742. Ref packedRef = cur.get(refName);
  743. ObjectId clr_oid = currentLooseRef.getObjectId();
  744. if (clr_oid != null
  745. && clr_oid.equals(packedRef.getObjectId())) {
  746. RefList<LooseRef> curLoose, newLoose;
  747. do {
  748. curLoose = looseRefs.get();
  749. int idx = curLoose.find(refName);
  750. if (idx < 0) {
  751. break;
  752. }
  753. newLoose = curLoose.remove(idx);
  754. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  755. int levels = levelsIn(refName) - 2;
  756. delete(refFile, levels, rLck);
  757. }
  758. } finally {
  759. if (shouldUnlock) {
  760. rLck.unlock();
  761. }
  762. }
  763. }
  764. // Don't fire refsChanged. The refs have not change, only their
  765. // storage.
  766. return result;
  767. } finally {
  768. lck.unlock();
  769. }
  770. } finally {
  771. inProcessPackedRefsLock.unlock();
  772. }
  773. }
  774. @Nullable
  775. LockFile lockPackedRefs() throws IOException {
  776. LockFile lck = new LockFile(packedRefsFile);
  777. for (int ms : getRetrySleepMs()) {
  778. sleep(ms);
  779. if (lck.lock()) {
  780. return lck;
  781. }
  782. }
  783. return null;
  784. }
  785. private LockFile lockPackedRefsOrThrow() throws IOException {
  786. LockFile lck = lockPackedRefs();
  787. if (lck == null) {
  788. throw new LockFailedException(packedRefsFile);
  789. }
  790. return lck;
  791. }
  792. /**
  793. * Make sure a ref is peeled and has the Storage PACKED. If the given ref
  794. * has this attributes simply return it. Otherwise create a new peeled
  795. * {@link ObjectIdRef} where Storage is set to PACKED.
  796. *
  797. * @param f
  798. * @return a ref for Storage PACKED having the same name, id, peeledId as f
  799. * @throws MissingObjectException
  800. * @throws IOException
  801. */
  802. private Ref peeledPackedRef(Ref f)
  803. throws MissingObjectException, IOException {
  804. if (f.getStorage().isPacked() && f.isPeeled()) {
  805. return f;
  806. }
  807. if (!f.isPeeled()) {
  808. f = peel(f);
  809. }
  810. ObjectId peeledObjectId = f.getPeeledObjectId();
  811. if (peeledObjectId != null) {
  812. return new ObjectIdRef.PeeledTag(PACKED, f.getName(),
  813. f.getObjectId(), peeledObjectId);
  814. } else {
  815. return new ObjectIdRef.PeeledNonTag(PACKED, f.getName(),
  816. f.getObjectId());
  817. }
  818. }
  819. void log(boolean force, RefUpdate update, String msg, boolean deref)
  820. throws IOException {
  821. newLogWriter(force).log(update, msg, deref);
  822. }
  823. private Ref resolve(final Ref ref, int depth, String prefix,
  824. RefList<LooseRef> loose, RefList<Ref> packed) throws IOException {
  825. if (ref.isSymbolic()) {
  826. Ref dst = ref.getTarget();
  827. if (MAX_SYMBOLIC_REF_DEPTH <= depth)
  828. return null; // claim it doesn't exist
  829. // If the cached value can be assumed to be current due to a
  830. // recent scan of the loose directory, use it.
  831. if (loose != null && dst.getName().startsWith(prefix)) {
  832. int idx;
  833. if (0 <= (idx = loose.find(dst.getName())))
  834. dst = loose.get(idx);
  835. else if (0 <= (idx = packed.find(dst.getName())))
  836. dst = packed.get(idx);
  837. else
  838. return ref;
  839. } else {
  840. dst = readRef(dst.getName(), packed);
  841. if (dst == null)
  842. return ref;
  843. }
  844. dst = resolve(dst, depth + 1, prefix, loose, packed);
  845. if (dst == null)
  846. return null;
  847. return new SymbolicRef(ref.getName(), dst);
  848. }
  849. return ref;
  850. }
  851. PackedRefList getPackedRefs() throws IOException {
  852. boolean trustFolderStat = getRepository().getConfig().getBoolean(
  853. ConfigConstants.CONFIG_CORE_SECTION,
  854. ConfigConstants.CONFIG_KEY_TRUSTFOLDERSTAT, true);
  855. final PackedRefList curList = packedRefs.get();
  856. if (trustFolderStat && !curList.snapshot.isModified(packedRefsFile)) {
  857. return curList;
  858. }
  859. final PackedRefList newList = readPackedRefs();
  860. if (packedRefs.compareAndSet(curList, newList)
  861. && !curList.id.equals(newList.id)) {
  862. modCnt.incrementAndGet();
  863. }
  864. return newList;
  865. }
  866. private PackedRefList readPackedRefs() throws IOException {
  867. int maxStaleRetries = 5;
  868. int retries = 0;
  869. while (true) {
  870. final FileSnapshot snapshot = FileSnapshot.save(packedRefsFile);
  871. final MessageDigest digest = Constants.newMessageDigest();
  872. try (BufferedReader br = new BufferedReader(new InputStreamReader(
  873. new DigestInputStream(new FileInputStream(packedRefsFile),
  874. digest),
  875. UTF_8))) {
  876. try {
  877. return new PackedRefList(parsePackedRefs(br), snapshot,
  878. ObjectId.fromRaw(digest.digest()));
  879. } catch (IOException e) {
  880. if (FileUtils.isStaleFileHandleInCausalChain(e)
  881. && retries < maxStaleRetries) {
  882. if (LOG.isDebugEnabled()) {
  883. LOG.debug(MessageFormat.format(
  884. JGitText.get().packedRefsHandleIsStale,
  885. Integer.valueOf(retries)), e);
  886. }
  887. retries++;
  888. continue;
  889. }
  890. throw e;
  891. }
  892. } catch (FileNotFoundException noPackedRefs) {
  893. if (packedRefsFile.exists()) {
  894. throw noPackedRefs;
  895. }
  896. // Ignore it and leave the new list empty.
  897. return NO_PACKED_REFS;
  898. }
  899. }
  900. }
  901. private RefList<Ref> parsePackedRefs(BufferedReader br)
  902. throws IOException {
  903. RefList.Builder<Ref> all = new RefList.Builder<>();
  904. Ref last = null;
  905. boolean peeled = false;
  906. boolean needSort = false;
  907. String p;
  908. while ((p = br.readLine()) != null) {
  909. if (p.charAt(0) == '#') {
  910. if (p.startsWith(PACKED_REFS_HEADER)) {
  911. p = p.substring(PACKED_REFS_HEADER.length());
  912. peeled = p.contains(PACKED_REFS_PEELED);
  913. }
  914. continue;
  915. }
  916. if (p.charAt(0) == '^') {
  917. if (last == null)
  918. throw new IOException(JGitText.get().peeledLineBeforeRef);
  919. ObjectId id = ObjectId.fromString(p.substring(1));
  920. last = new ObjectIdRef.PeeledTag(PACKED, last.getName(), last
  921. .getObjectId(), id);
  922. all.set(all.size() - 1, last);
  923. continue;
  924. }
  925. int sp = p.indexOf(' ');
  926. if (sp < 0) {
  927. throw new IOException(MessageFormat.format(
  928. JGitText.get().packedRefsCorruptionDetected,
  929. packedRefsFile.getAbsolutePath()));
  930. }
  931. ObjectId id = ObjectId.fromString(p.substring(0, sp));
  932. String name = copy(p, sp + 1, p.length());
  933. ObjectIdRef cur;
  934. if (peeled)
  935. cur = new ObjectIdRef.PeeledNonTag(PACKED, name, id);
  936. else
  937. cur = new ObjectIdRef.Unpeeled(PACKED, name, id);
  938. if (last != null && RefComparator.compareTo(last, cur) > 0)
  939. needSort = true;
  940. all.add(cur);
  941. last = cur;
  942. }
  943. if (needSort)
  944. all.sort();
  945. return all.toRefList();
  946. }
  947. private static String copy(String src, int off, int end) {
  948. // Don't use substring since it could leave a reference to the much
  949. // larger existing string. Force construction of a full new object.
  950. return new StringBuilder(end - off).append(src, off, end).toString();
  951. }
  952. PackedRefList commitPackedRefs(final LockFile lck, final RefList<Ref> refs,
  953. final PackedRefList oldPackedList, boolean changed)
  954. throws IOException {
  955. // Can't just return packedRefs.get() from this method; it might have been
  956. // updated again after writePackedRefs() returns.
  957. AtomicReference<PackedRefList> result = new AtomicReference<>();
  958. new RefWriter(refs) {
  959. @Override
  960. protected void writeFile(String name, byte[] content)
  961. throws IOException {
  962. lck.setFSync(true);
  963. lck.setNeedSnapshot(true);
  964. try {
  965. lck.write(content);
  966. } catch (IOException ioe) {
  967. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name), ioe);
  968. }
  969. try {
  970. lck.waitForStatChange();
  971. } catch (InterruptedException e) {
  972. lck.unlock();
  973. throw new ObjectWritingException(MessageFormat.format(JGitText.get().interruptedWriting, name));
  974. }
  975. if (!lck.commit())
  976. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name));
  977. byte[] digest = Constants.newMessageDigest().digest(content);
  978. PackedRefList newPackedList = new PackedRefList(
  979. refs, lck.getCommitSnapshot(), ObjectId.fromRaw(digest));
  980. // This thread holds the file lock, so no other thread or process should
  981. // be able to modify the packed-refs file on disk. If the list changed,
  982. // it means something is very wrong, so throw an exception.
  983. //
  984. // However, we can't use a naive compareAndSet to check whether the
  985. // update was successful, because another thread might _read_ the
  986. // packed refs file that was written out by this thread while holding
  987. // the lock, and update the packedRefs reference to point to that. So
  988. // compare the actual contents instead.
  989. PackedRefList afterUpdate = packedRefs.updateAndGet(
  990. p -> p.id.equals(oldPackedList.id) ? newPackedList : p);
  991. if (!afterUpdate.id.equals(newPackedList.id)) {
  992. throw new ObjectWritingException(
  993. MessageFormat.format(JGitText.get().unableToWrite, name));
  994. }
  995. if (changed) {
  996. modCnt.incrementAndGet();
  997. }
  998. result.set(newPackedList);
  999. }
  1000. }.writePackedRefs();
  1001. return result.get();
  1002. }
  1003. private Ref readRef(String name, RefList<Ref> packed) throws IOException {
  1004. final RefList<LooseRef> curList = looseRefs.get();
  1005. final int idx = curList.find(name);
  1006. if (0 <= idx) {
  1007. final LooseRef o = curList.get(idx);
  1008. final LooseRef n = scanRef(o, name);
  1009. if (n == null) {
  1010. if (looseRefs.compareAndSet(curList, curList.remove(idx)))
  1011. modCnt.incrementAndGet();
  1012. return packed.get(name);
  1013. }
  1014. if (o == n)
  1015. return n;
  1016. if (looseRefs.compareAndSet(curList, curList.set(idx, n)))
  1017. modCnt.incrementAndGet();
  1018. return n;
  1019. }
  1020. final LooseRef n = scanRef(null, name);
  1021. if (n == null)
  1022. return packed.get(name);
  1023. // check whether the found new ref is the an additional ref. These refs
  1024. // should not go into looseRefs
  1025. for (int i = 0; i < additionalRefsNames.length; i++)
  1026. if (name.equals(additionalRefsNames[i]))
  1027. return n;
  1028. if (looseRefs.compareAndSet(curList, curList.add(idx, n)))
  1029. modCnt.incrementAndGet();
  1030. return n;
  1031. }
  1032. LooseRef scanRef(LooseRef ref, String name) throws IOException {
  1033. final File path = fileFor(name);
  1034. FileSnapshot currentSnapshot = null;
  1035. if (ref != null) {
  1036. currentSnapshot = ref.getSnapShot();
  1037. if (!currentSnapshot.isModified(path))
  1038. return ref;
  1039. name = ref.getName();
  1040. }
  1041. final int limit = 4096;
  1042. final byte[] buf;
  1043. FileSnapshot otherSnapshot = FileSnapshot.save(path);
  1044. try {
  1045. buf = IO.readSome(path, limit);
  1046. } catch (FileNotFoundException noFile) {
  1047. if (path.exists() && path.isFile()) {
  1048. throw noFile;
  1049. }
  1050. return null; // doesn't exist or no file; not a reference.
  1051. }
  1052. int n = buf.length;
  1053. if (n == 0)
  1054. return null; // empty file; not a reference.
  1055. if (isSymRef(buf, n)) {
  1056. if (n == limit)
  1057. return null; // possibly truncated ref
  1058. // trim trailing whitespace
  1059. while (0 < n && Character.isWhitespace(buf[n - 1]))
  1060. n--;
  1061. if (n < 6) {
  1062. String content = RawParseUtils.decode(buf, 0, n);
  1063. throw new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
  1064. }
  1065. final String target = RawParseUtils.decode(buf, 5, n);
  1066. if (ref != null && ref.isSymbolic()
  1067. && ref.getTarget().getName().equals(target)) {
  1068. assert(currentSnapshot != null);
  1069. currentSnapshot.setClean(otherSnapshot);
  1070. return ref;
  1071. }
  1072. return newSymbolicRef(otherSnapshot, name, target);
  1073. }
  1074. if (n < OBJECT_ID_STRING_LENGTH)
  1075. return null; // impossibly short object identifier; not a reference.
  1076. final ObjectId id;
  1077. try {
  1078. id = ObjectId.fromString(buf, 0);
  1079. if (ref != null && !ref.isSymbolic()
  1080. && id.equals(ref.getTarget().getObjectId())) {
  1081. assert(currentSnapshot != null);
  1082. currentSnapshot.setClean(otherSnapshot);
  1083. return ref;
  1084. }
  1085. } catch (IllegalArgumentException notRef) {
  1086. while (0 < n && Character.isWhitespace(buf[n - 1]))
  1087. n--;
  1088. String content = RawParseUtils.decode(buf, 0, n);
  1089. throw new IOException(MessageFormat.format(JGitText.get().notARef,
  1090. name, content), notRef);
  1091. }
  1092. return new LooseUnpeeled(otherSnapshot, name, id);
  1093. }
  1094. private static boolean isSymRef(byte[] buf, int n) {
  1095. if (n < 6)
  1096. return false;
  1097. return /**/buf[0] == 'r' //
  1098. && buf[1] == 'e' //
  1099. && buf[2] == 'f' //
  1100. && buf[3] == ':' //
  1101. && buf[4] == ' ';
  1102. }
  1103. /**
  1104. * Detect if we are in a clone command execution
  1105. *
  1106. * @return {@code true} if we are currently cloning a repository
  1107. * @throws IOException
  1108. */
  1109. boolean isInClone() throws IOException {
  1110. return hasDanglingHead() && !packedRefsFile.exists() && !hasLooseRef();
  1111. }
  1112. private boolean hasDanglingHead() throws IOException {
  1113. Ref head = exactRef(Constants.HEAD);
  1114. if (head != null) {
  1115. ObjectId id = head.getObjectId();
  1116. return id == null || id.equals(ObjectId.zeroId());
  1117. }
  1118. return false;
  1119. }
  1120. private boolean hasLooseRef() throws IOException {
  1121. try (Stream<Path> stream = Files.walk(refsDir.toPath())) {
  1122. return stream.anyMatch(Files::isRegularFile);
  1123. }
  1124. }
  1125. /** If the parent should fire listeners, fires them. */
  1126. void fireRefsChanged() {
  1127. final int last = lastNotifiedModCnt.get();
  1128. final int curr = modCnt.get();
  1129. if (last != curr && lastNotifiedModCnt.compareAndSet(last, curr) && last != 0)
  1130. parent.fireEvent(new RefsChangedEvent());
  1131. }
  1132. /**
  1133. * Create a reference update to write a temporary reference.
  1134. *
  1135. * @return an update for a new temporary reference.
  1136. * @throws IOException
  1137. * a temporary name cannot be allocated.
  1138. */
  1139. RefDirectoryUpdate newTemporaryUpdate() throws IOException {
  1140. File tmp = File.createTempFile("renamed_", "_ref", refsDir); //$NON-NLS-1$ //$NON-NLS-2$
  1141. String name = Constants.R_REFS + tmp.getName();
  1142. Ref ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  1143. return new RefDirectoryUpdate(this, ref);
  1144. }
  1145. /**
  1146. * Locate the file on disk for a single reference name.
  1147. *
  1148. * @param name
  1149. * name of the ref, relative to the Git repository top level
  1150. * directory (so typically starts with refs/).
  1151. * @return the loose file location.
  1152. */
  1153. File fileFor(String name) {
  1154. if (name.startsWith(R_REFS)) {
  1155. name = name.substring(R_REFS.length());
  1156. return new File(refsDir, name);
  1157. }
  1158. return new File(gitDir, name);
  1159. }
  1160. static int levelsIn(String name) {
  1161. int count = 0;
  1162. for (int p = name.indexOf('/'); p >= 0; p = name.indexOf('/', p + 1))
  1163. count++;
  1164. return count;
  1165. }
  1166. static void delete(File file, int depth) throws IOException {
  1167. delete(file, depth, null);
  1168. }
  1169. private static void delete(File file, int depth, LockFile rLck)
  1170. throws IOException {
  1171. if (!file.delete() && file.isFile()) {
  1172. throw new IOException(MessageFormat.format(
  1173. JGitText.get().fileCannotBeDeleted, file));
  1174. }
  1175. if (rLck != null) {
  1176. rLck.unlock(); // otherwise cannot delete dir below
  1177. }
  1178. File dir = file.getParentFile();
  1179. for (int i = 0; i < depth; ++i) {
  1180. try {
  1181. Files.deleteIfExists(dir.toPath());
  1182. } catch (DirectoryNotEmptyException e) {
  1183. // Don't log; normal case when there are other refs with the
  1184. // same prefix
  1185. break;
  1186. } catch (IOException e) {
  1187. LOG.warn(MessageFormat.format(JGitText.get().unableToRemovePath,
  1188. dir), e);
  1189. break;
  1190. }
  1191. dir = dir.getParentFile();
  1192. }
  1193. }
  1194. /**
  1195. * Get times to sleep while retrying a possibly contentious operation.
  1196. * <p>
  1197. * For retrying an operation that might have high contention, such as locking
  1198. * the {@code packed-refs} file, the caller may implement a retry loop using
  1199. * the returned values:
  1200. *
  1201. * <pre>
  1202. * for (int toSleepMs : getRetrySleepMs()) {
  1203. * sleep(toSleepMs);
  1204. * if (isSuccessful(doSomething())) {
  1205. * return success;
  1206. * }
  1207. * }
  1208. * return failure;
  1209. * </pre>
  1210. *
  1211. * The first value in the returned iterable is 0, and the caller should treat
  1212. * a fully-consumed iterator as a timeout.
  1213. *
  1214. * @return iterable of times, in milliseconds, that the caller should sleep
  1215. * before attempting an operation.
  1216. */
  1217. Iterable<Integer> getRetrySleepMs() {
  1218. return retrySleepMs;
  1219. }
  1220. void setRetrySleepMs(List<Integer> retrySleepMs) {
  1221. if (retrySleepMs == null || retrySleepMs.isEmpty()
  1222. || retrySleepMs.get(0).intValue() != 0) {
  1223. throw new IllegalArgumentException();
  1224. }
  1225. this.retrySleepMs = retrySleepMs;
  1226. }
  1227. /**
  1228. * Sleep with {@link Thread#sleep(long)}, converting {@link
  1229. * InterruptedException} to {@link InterruptedIOException}.
  1230. *
  1231. * @param ms
  1232. * time to sleep, in milliseconds; zero or negative is a no-op.
  1233. * @throws InterruptedIOException
  1234. * if sleeping was interrupted.
  1235. */
  1236. static void sleep(long ms) throws InterruptedIOException {
  1237. if (ms <= 0) {
  1238. return;
  1239. }
  1240. try {
  1241. Thread.sleep(ms);
  1242. } catch (InterruptedException e) {
  1243. InterruptedIOException ie = new InterruptedIOException();
  1244. ie.initCause(e);
  1245. throw ie;
  1246. }
  1247. }
  1248. static class PackedRefList extends RefList<Ref> {
  1249. private final FileSnapshot snapshot;
  1250. private final ObjectId id;
  1251. private PackedRefList(RefList<Ref> src, FileSnapshot s, ObjectId i) {
  1252. super(src);
  1253. snapshot = s;
  1254. id = i;
  1255. }
  1256. }
  1257. private static final PackedRefList NO_PACKED_REFS = new PackedRefList(
  1258. RefList.emptyList(), FileSnapshot.MISSING_FILE,
  1259. ObjectId.zeroId());
  1260. private static LooseSymbolicRef newSymbolicRef(FileSnapshot snapshot,
  1261. String name, String target) {
  1262. Ref dst = new ObjectIdRef.Unpeeled(NEW, target, null);
  1263. return new LooseSymbolicRef(snapshot, name, dst);
  1264. }
  1265. private static interface LooseRef extends Ref {
  1266. FileSnapshot getSnapShot();
  1267. LooseRef peel(ObjectIdRef newLeaf);
  1268. }
  1269. private final static class LoosePeeledTag extends ObjectIdRef.PeeledTag
  1270. implements LooseRef {
  1271. private final FileSnapshot snapShot;
  1272. LoosePeeledTag(FileSnapshot snapshot, @NonNull String refName,
  1273. @NonNull ObjectId id, @NonNull ObjectId p) {
  1274. super(LOOSE, refName, id, p);
  1275. this.snapShot = snapshot;
  1276. }
  1277. @Override
  1278. public FileSnapshot getSnapShot() {
  1279. return snapShot;
  1280. }
  1281. @Override
  1282. public LooseRef peel(ObjectIdRef newLeaf) {
  1283. return this;
  1284. }
  1285. }
  1286. private final static class LooseNonTag extends ObjectIdRef.PeeledNonTag
  1287. implements LooseRef {
  1288. private final FileSnapshot snapShot;
  1289. LooseNonTag(FileSnapshot snapshot, @NonNull String refName,
  1290. @NonNull ObjectId id) {
  1291. super(LOOSE, refName, id);
  1292. this.snapShot = snapshot;
  1293. }
  1294. @Override
  1295. public FileSnapshot getSnapShot() {
  1296. return snapShot;
  1297. }
  1298. @Override
  1299. public LooseRef peel(ObjectIdRef newLeaf) {
  1300. return this;
  1301. }
  1302. }
  1303. private final static class LooseUnpeeled extends ObjectIdRef.Unpeeled
  1304. implements LooseRef {
  1305. private FileSnapshot snapShot;
  1306. LooseUnpeeled(FileSnapshot snapShot, @NonNull String refName,
  1307. @NonNull ObjectId id) {
  1308. super(LOOSE, refName, id);
  1309. this.snapShot = snapShot;
  1310. }
  1311. @Override
  1312. public FileSnapshot getSnapShot() {
  1313. return snapShot;
  1314. }
  1315. @NonNull
  1316. @Override
  1317. public ObjectId getObjectId() {
  1318. ObjectId id = super.getObjectId();
  1319. assert id != null; // checked in constructor
  1320. return id;
  1321. }
  1322. @Override
  1323. public LooseRef peel(ObjectIdRef newLeaf) {
  1324. ObjectId peeledObjectId = newLeaf.getPeeledObjectId();
  1325. ObjectId objectId = getObjectId();
  1326. if (peeledObjectId != null) {
  1327. return new LoosePeeledTag(snapShot, getName(),
  1328. objectId, peeledObjectId);
  1329. } else {
  1330. return new LooseNonTag(snapShot, getName(),
  1331. objectId);
  1332. }
  1333. }
  1334. }
  1335. private final static class LooseSymbolicRef extends SymbolicRef implements
  1336. LooseRef {
  1337. private final FileSnapshot snapShot;
  1338. LooseSymbolicRef(FileSnapshot snapshot, @NonNull String refName,
  1339. @NonNull Ref target) {
  1340. super(refName, target);
  1341. this.snapShot = snapshot;
  1342. }
  1343. @Override
  1344. public FileSnapshot getSnapShot() {
  1345. return snapShot;
  1346. }
  1347. @Override
  1348. public LooseRef peel(ObjectIdRef newLeaf) {
  1349. // We should never try to peel the symbolic references.
  1350. throw new UnsupportedOperationException();
  1351. }
  1352. }
  1353. }