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

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