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

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