Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RefDirectory.java 34KB

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