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

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