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

RefDirectory.java 31KB

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