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

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