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

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