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

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