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

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