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

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