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

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