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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  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.internal.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.OBJECT_ID_STRING_LENGTH;
  50. import static org.eclipse.jgit.lib.Constants.PACKED_REFS;
  51. import static org.eclipse.jgit.lib.Constants.R_HEADS;
  52. import static org.eclipse.jgit.lib.Constants.R_REFS;
  53. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  54. import static org.eclipse.jgit.lib.Ref.Storage.LOOSE;
  55. import static org.eclipse.jgit.lib.Ref.Storage.NEW;
  56. import static org.eclipse.jgit.lib.Ref.Storage.PACKED;
  57. import java.io.BufferedReader;
  58. import java.io.File;
  59. import java.io.FileInputStream;
  60. import java.io.FileNotFoundException;
  61. import java.io.IOException;
  62. import java.io.InputStreamReader;
  63. import java.security.DigestInputStream;
  64. import java.security.MessageDigest;
  65. import java.text.MessageFormat;
  66. import java.util.Arrays;
  67. import java.util.LinkedList;
  68. import java.util.List;
  69. import java.util.Map;
  70. import java.util.concurrent.atomic.AtomicInteger;
  71. import java.util.concurrent.atomic.AtomicReference;
  72. import org.eclipse.jgit.annotations.NonNull;
  73. import org.eclipse.jgit.errors.InvalidObjectIdException;
  74. import org.eclipse.jgit.errors.LockFailedException;
  75. import org.eclipse.jgit.errors.MissingObjectException;
  76. import org.eclipse.jgit.errors.ObjectWritingException;
  77. import org.eclipse.jgit.events.RefsChangedEvent;
  78. import org.eclipse.jgit.internal.JGitText;
  79. import org.eclipse.jgit.lib.Constants;
  80. import org.eclipse.jgit.lib.ObjectId;
  81. import org.eclipse.jgit.lib.ObjectIdRef;
  82. import org.eclipse.jgit.lib.Ref;
  83. import org.eclipse.jgit.lib.RefComparator;
  84. import org.eclipse.jgit.lib.RefDatabase;
  85. import org.eclipse.jgit.lib.RefUpdate;
  86. import org.eclipse.jgit.lib.RefWriter;
  87. import org.eclipse.jgit.lib.Repository;
  88. import org.eclipse.jgit.lib.SymbolicRef;
  89. import org.eclipse.jgit.revwalk.RevObject;
  90. import org.eclipse.jgit.revwalk.RevTag;
  91. import org.eclipse.jgit.revwalk.RevWalk;
  92. import org.eclipse.jgit.util.FS;
  93. import org.eclipse.jgit.util.FileUtils;
  94. import org.eclipse.jgit.util.IO;
  95. import org.eclipse.jgit.util.RawParseUtils;
  96. import org.eclipse.jgit.util.RefList;
  97. import org.eclipse.jgit.util.RefMap;
  98. import org.slf4j.Logger;
  99. import org.slf4j.LoggerFactory;
  100. /**
  101. * Traditional file system based {@link RefDatabase}.
  102. * <p>
  103. * This is the classical reference database representation for a Git repository.
  104. * References are stored in two formats: loose, and packed.
  105. * <p>
  106. * Loose references are stored as individual files within the {@code refs/}
  107. * directory. The file name matches the reference name and the file contents is
  108. * the current {@link ObjectId} in string form.
  109. * <p>
  110. * Packed references are stored in a single text file named {@code packed-refs}.
  111. * In the packed format, each reference is stored on its own line. This file
  112. * reduces the number of files needed for large reference spaces, reducing the
  113. * overall size of a Git repository on disk.
  114. */
  115. public class RefDirectory extends RefDatabase {
  116. private final static Logger LOG = LoggerFactory
  117. .getLogger(RefDirectory.class);
  118. /** Magic string denoting the start of a symbolic reference file. */
  119. public static final String SYMREF = "ref: "; //$NON-NLS-1$
  120. /** Magic string denoting the header of a packed-refs file. */
  121. public static final String PACKED_REFS_HEADER = "# pack-refs with:"; //$NON-NLS-1$
  122. /** If in the header, denotes the file has peeled data. */
  123. public static final String PACKED_REFS_PEELED = " peeled"; //$NON-NLS-1$
  124. /** The names of the additional refs supported by this class */
  125. private static final String[] additionalRefsNames = new String[] {
  126. Constants.MERGE_HEAD, Constants.FETCH_HEAD, Constants.ORIG_HEAD,
  127. Constants.CHERRY_PICK_HEAD };
  128. private final FileRepository parent;
  129. private final File gitDir;
  130. final File refsDir;
  131. private final ReflogWriter logWriter;
  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. 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. logWriter = new ReflogWriter(db);
  163. refsDir = fs.resolve(gitDir, R_REFS);
  164. packedRefsFile = fs.resolve(gitDir, PACKED_REFS);
  165. looseRefs.set(RefList.<LooseRef> emptyList());
  166. packedRefs.set(PackedRefList.NO_PACKED_REFS);
  167. }
  168. Repository getRepository() {
  169. return parent;
  170. }
  171. ReflogWriter getLogWriter() {
  172. return logWriter;
  173. }
  174. public void create() throws IOException {
  175. FileUtils.mkdir(refsDir);
  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. logWriter.create();
  179. }
  180. @Override
  181. public void close() {
  182. clearReferences();
  183. }
  184. private void clearReferences() {
  185. looseRefs.set(RefList.<LooseRef> emptyList());
  186. packedRefs.set(PackedRefList.NO_PACKED_REFS);
  187. }
  188. @Override
  189. public void refresh() {
  190. super.refresh();
  191. clearReferences();
  192. }
  193. @Override
  194. public boolean isNameConflicting(String name) throws IOException {
  195. RefList<Ref> packed = getPackedRefs();
  196. RefList<LooseRef> loose = getLooseRefs();
  197. // Cannot be nested within an existing reference.
  198. int lastSlash = name.lastIndexOf('/');
  199. while (0 < lastSlash) {
  200. String needle = name.substring(0, lastSlash);
  201. if (loose.contains(needle) || packed.contains(needle))
  202. return true;
  203. lastSlash = name.lastIndexOf('/', lastSlash - 1);
  204. }
  205. // Cannot be the container of an existing reference.
  206. String prefix = name + '/';
  207. int idx;
  208. idx = -(packed.find(prefix) + 1);
  209. if (idx < packed.size() && packed.get(idx).getName().startsWith(prefix))
  210. return true;
  211. idx = -(loose.find(prefix) + 1);
  212. if (idx < loose.size() && loose.get(idx).getName().startsWith(prefix))
  213. return true;
  214. return false;
  215. }
  216. private RefList<LooseRef> getLooseRefs() {
  217. final RefList<LooseRef> oldLoose = looseRefs.get();
  218. LooseScanner scan = new LooseScanner(oldLoose);
  219. scan.scan(ALL);
  220. RefList<LooseRef> loose;
  221. if (scan.newLoose != null) {
  222. loose = scan.newLoose.toRefList();
  223. if (looseRefs.compareAndSet(oldLoose, loose))
  224. modCnt.incrementAndGet();
  225. } else
  226. loose = oldLoose;
  227. return loose;
  228. }
  229. @Override
  230. public Ref exactRef(String name) throws IOException {
  231. RefList<Ref> packed = getPackedRefs();
  232. Ref ref;
  233. try {
  234. ref = readRef(name, packed);
  235. if (ref != null) {
  236. ref = resolve(ref, 0, null, null, packed);
  237. }
  238. } catch (IOException e) {
  239. if (name.contains("/") //$NON-NLS-1$
  240. || !(e.getCause() instanceof InvalidObjectIdException)) {
  241. throw e;
  242. }
  243. // While looking for a ref outside of refs/ (e.g., 'config'), we
  244. // found a non-ref file (e.g., a config file) instead. Treat this
  245. // as a ref-not-found condition.
  246. ref = null;
  247. }
  248. fireRefsChanged();
  249. return ref;
  250. }
  251. @Override
  252. public Ref getRef(final String needle) throws IOException {
  253. final RefList<Ref> packed = getPackedRefs();
  254. Ref ref = null;
  255. for (String prefix : SEARCH_PATH) {
  256. try {
  257. ref = readRef(prefix + needle, packed);
  258. if (ref != null) {
  259. ref = resolve(ref, 0, null, null, packed);
  260. }
  261. if (ref != null) {
  262. break;
  263. }
  264. } catch (IOException e) {
  265. if (!(!needle.contains("/") && "".equals(prefix) && e //$NON-NLS-1$ //$NON-NLS-2$
  266. .getCause() instanceof InvalidObjectIdException)) {
  267. throw e;
  268. }
  269. }
  270. }
  271. fireRefsChanged();
  272. return ref;
  273. }
  274. @Override
  275. public Map<String, Ref> getRefs(String prefix) throws IOException {
  276. final RefList<LooseRef> oldLoose = looseRefs.get();
  277. LooseScanner scan = new LooseScanner(oldLoose);
  278. scan.scan(prefix);
  279. final RefList<Ref> packed = getPackedRefs();
  280. RefList<LooseRef> loose;
  281. if (scan.newLoose != null) {
  282. scan.newLoose.sort();
  283. loose = scan.newLoose.toRefList();
  284. if (looseRefs.compareAndSet(oldLoose, loose))
  285. modCnt.incrementAndGet();
  286. } else
  287. loose = oldLoose;
  288. fireRefsChanged();
  289. RefList.Builder<Ref> symbolic = scan.symbolic;
  290. for (int idx = 0; idx < symbolic.size();) {
  291. final Ref symbolicRef = symbolic.get(idx);
  292. final Ref resolvedRef = resolve(symbolicRef, 0, prefix, loose, packed);
  293. if (resolvedRef != null && resolvedRef.getObjectId() != null) {
  294. symbolic.set(idx, resolvedRef);
  295. idx++;
  296. } else {
  297. // A broken symbolic reference, we have to drop it from the
  298. // collections the client is about to receive. Should be a
  299. // rare occurrence so pay a copy penalty.
  300. symbolic.remove(idx);
  301. final int toRemove = loose.find(symbolicRef.getName());
  302. if (0 <= toRemove)
  303. loose = loose.remove(toRemove);
  304. }
  305. }
  306. symbolic.sort();
  307. return new RefMap(prefix, packed, upcast(loose), symbolic.toRefList());
  308. }
  309. @Override
  310. public List<Ref> getAdditionalRefs() throws IOException {
  311. List<Ref> ret = new LinkedList<Ref>();
  312. for (String name : additionalRefsNames) {
  313. Ref r = getRef(name);
  314. if (r != null)
  315. ret.add(r);
  316. }
  317. return ret;
  318. }
  319. @SuppressWarnings("unchecked")
  320. private RefList<Ref> upcast(RefList<? extends Ref> loose) {
  321. return (RefList<Ref>) loose;
  322. }
  323. private class LooseScanner {
  324. private final RefList<LooseRef> curLoose;
  325. private int curIdx;
  326. final RefList.Builder<Ref> symbolic = new RefList.Builder<Ref>(4);
  327. RefList.Builder<LooseRef> newLoose;
  328. LooseScanner(final RefList<LooseRef> curLoose) {
  329. this.curLoose = curLoose;
  330. }
  331. void scan(String prefix) {
  332. if (ALL.equals(prefix)) {
  333. scanOne(HEAD);
  334. scanTree(R_REFS, refsDir);
  335. // If any entries remain, they are deleted, drop them.
  336. if (newLoose == null && curIdx < curLoose.size())
  337. newLoose = curLoose.copy(curIdx);
  338. } else if (prefix.startsWith(R_REFS) && prefix.endsWith("/")) { //$NON-NLS-1$
  339. curIdx = -(curLoose.find(prefix) + 1);
  340. File dir = new File(refsDir, prefix.substring(R_REFS.length()));
  341. scanTree(prefix, dir);
  342. // Skip over entries still within the prefix; these have
  343. // been removed from the directory.
  344. while (curIdx < curLoose.size()) {
  345. if (!curLoose.get(curIdx).getName().startsWith(prefix))
  346. break;
  347. if (newLoose == null)
  348. newLoose = curLoose.copy(curIdx);
  349. curIdx++;
  350. }
  351. // Keep any entries outside of the prefix space, we
  352. // do not know anything about their status.
  353. if (newLoose != null) {
  354. while (curIdx < curLoose.size())
  355. newLoose.add(curLoose.get(curIdx++));
  356. }
  357. }
  358. }
  359. private boolean scanTree(String prefix, File dir) {
  360. final String[] entries = dir.list(LockFile.FILTER);
  361. if (entries == null) // not a directory or an I/O error
  362. return false;
  363. if (0 < entries.length) {
  364. for (int i = 0; i < entries.length; ++i) {
  365. String e = entries[i];
  366. File f = new File(dir, e);
  367. if (f.isDirectory())
  368. entries[i] += '/';
  369. }
  370. Arrays.sort(entries);
  371. for (String name : entries) {
  372. if (name.charAt(name.length() - 1) == '/')
  373. scanTree(prefix + name, new File(dir, name));
  374. else
  375. scanOne(prefix + name);
  376. }
  377. }
  378. return true;
  379. }
  380. private void scanOne(String name) {
  381. LooseRef cur;
  382. if (curIdx < curLoose.size()) {
  383. do {
  384. cur = curLoose.get(curIdx);
  385. int cmp = RefComparator.compareTo(cur, name);
  386. if (cmp < 0) {
  387. // Reference is not loose anymore, its been deleted.
  388. // Skip the name in the new result list.
  389. if (newLoose == null)
  390. newLoose = curLoose.copy(curIdx);
  391. curIdx++;
  392. cur = null;
  393. continue;
  394. }
  395. if (cmp > 0) // Newly discovered loose reference.
  396. cur = null;
  397. break;
  398. } while (curIdx < curLoose.size());
  399. } else
  400. cur = null; // Newly discovered loose reference.
  401. LooseRef n;
  402. try {
  403. n = scanRef(cur, name);
  404. } catch (IOException notValid) {
  405. n = null;
  406. }
  407. if (n != null) {
  408. if (cur != n && newLoose == null)
  409. newLoose = curLoose.copy(curIdx);
  410. if (newLoose != null)
  411. newLoose.add(n);
  412. if (n.isSymbolic())
  413. symbolic.add(n);
  414. } else if (cur != null) {
  415. // Tragically, this file is no longer a loose reference.
  416. // Kill our cached entry of it.
  417. if (newLoose == null)
  418. newLoose = curLoose.copy(curIdx);
  419. }
  420. if (cur != null)
  421. curIdx++;
  422. }
  423. }
  424. @Override
  425. public Ref peel(final Ref ref) throws IOException {
  426. final Ref leaf = ref.getLeaf();
  427. if (leaf.isPeeled() || leaf.getObjectId() == null)
  428. return ref;
  429. ObjectIdRef newLeaf = doPeel(leaf);
  430. // Try to remember this peeling in the cache, so we don't have to do
  431. // it again in the future, but only if the reference is unchanged.
  432. if (leaf.getStorage().isLoose()) {
  433. RefList<LooseRef> curList = looseRefs.get();
  434. int idx = curList.find(leaf.getName());
  435. if (0 <= idx && curList.get(idx) == leaf) {
  436. LooseRef asPeeled = ((LooseRef) leaf).peel(newLeaf);
  437. RefList<LooseRef> newList = curList.set(idx, asPeeled);
  438. looseRefs.compareAndSet(curList, newList);
  439. }
  440. }
  441. return recreate(ref, newLeaf);
  442. }
  443. private ObjectIdRef doPeel(final Ref leaf) throws MissingObjectException,
  444. IOException {
  445. try (RevWalk rw = new RevWalk(getRepository())) {
  446. RevObject obj = rw.parseAny(leaf.getObjectId());
  447. if (obj instanceof RevTag) {
  448. return new ObjectIdRef.PeeledTag(leaf.getStorage(), leaf
  449. .getName(), leaf.getObjectId(), rw.peel(obj).copy());
  450. } else {
  451. return new ObjectIdRef.PeeledNonTag(leaf.getStorage(), leaf
  452. .getName(), leaf.getObjectId());
  453. }
  454. }
  455. }
  456. private static Ref recreate(final Ref old, final ObjectIdRef leaf) {
  457. if (old.isSymbolic()) {
  458. Ref dst = recreate(old.getTarget(), leaf);
  459. return new SymbolicRef(old.getName(), dst);
  460. }
  461. return leaf;
  462. }
  463. void storedSymbolicRef(RefDirectoryUpdate u, FileSnapshot snapshot,
  464. String target) {
  465. putLooseRef(newSymbolicRef(snapshot, u.getRef().getName(), target));
  466. fireRefsChanged();
  467. }
  468. public RefDirectoryUpdate newUpdate(String name, boolean detach)
  469. throws IOException {
  470. boolean detachingSymbolicRef = false;
  471. final RefList<Ref> packed = getPackedRefs();
  472. Ref ref = readRef(name, packed);
  473. if (ref != null)
  474. ref = resolve(ref, 0, null, null, packed);
  475. if (ref == null)
  476. ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  477. else {
  478. detachingSymbolicRef = detach && ref.isSymbolic();
  479. if (detachingSymbolicRef)
  480. ref = new ObjectIdRef.Unpeeled(LOOSE, name, ref.getObjectId());
  481. }
  482. RefDirectoryUpdate refDirUpdate = new RefDirectoryUpdate(this, ref);
  483. if (detachingSymbolicRef)
  484. refDirUpdate.setDetachingSymbolicRef();
  485. return refDirUpdate;
  486. }
  487. @Override
  488. public RefDirectoryRename newRename(String fromName, String toName)
  489. throws IOException {
  490. RefDirectoryUpdate from = newUpdate(fromName, false);
  491. RefDirectoryUpdate to = newUpdate(toName, false);
  492. return new RefDirectoryRename(from, to);
  493. }
  494. void stored(RefDirectoryUpdate update, FileSnapshot snapshot) {
  495. final ObjectId target = update.getNewObjectId().copy();
  496. final Ref leaf = update.getRef().getLeaf();
  497. putLooseRef(new LooseUnpeeled(snapshot, leaf.getName(), target));
  498. }
  499. private void putLooseRef(LooseRef ref) {
  500. RefList<LooseRef> cList, nList;
  501. do {
  502. cList = looseRefs.get();
  503. nList = cList.put(ref);
  504. } while (!looseRefs.compareAndSet(cList, nList));
  505. modCnt.incrementAndGet();
  506. fireRefsChanged();
  507. }
  508. void delete(RefDirectoryUpdate update) throws IOException {
  509. Ref dst = update.getRef().getLeaf();
  510. String name = dst.getName();
  511. // Write the packed-refs file using an atomic update. We might
  512. // wind up reading it twice, before and after the lock, to ensure
  513. // we don't miss an edit made externally.
  514. final PackedRefList packed = getPackedRefs();
  515. if (packed.contains(name)) {
  516. LockFile lck = new LockFile(packedRefsFile);
  517. if (!lck.lock())
  518. throw new LockFailedException(packedRefsFile);
  519. try {
  520. PackedRefList cur = readPackedRefs();
  521. int idx = cur.find(name);
  522. if (0 <= idx)
  523. commitPackedRefs(lck, cur.remove(idx), packed);
  524. } finally {
  525. lck.unlock();
  526. }
  527. }
  528. RefList<LooseRef> curLoose, newLoose;
  529. do {
  530. curLoose = looseRefs.get();
  531. int idx = curLoose.find(name);
  532. if (idx < 0)
  533. break;
  534. newLoose = curLoose.remove(idx);
  535. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  536. int levels = levelsIn(name) - 2;
  537. delete(logWriter.logFor(name), levels);
  538. if (dst.getStorage().isLoose()) {
  539. update.unlock();
  540. delete(fileFor(name), levels);
  541. }
  542. modCnt.incrementAndGet();
  543. fireRefsChanged();
  544. }
  545. /**
  546. * Adds a set of refs to the set of packed-refs. Only non-symbolic refs are
  547. * added. If a ref with the given name already existed in packed-refs it is
  548. * updated with the new value. Each loose ref which was added to the
  549. * packed-ref file is deleted. If a given ref can't be locked it will not be
  550. * added to the pack file.
  551. *
  552. * @param refs
  553. * the refs to be added. Must be fully qualified.
  554. * @throws IOException
  555. */
  556. public void pack(List<String> refs) throws IOException {
  557. if (refs.size() == 0)
  558. return;
  559. FS fs = parent.getFS();
  560. // Lock the packed refs file and read the content
  561. LockFile lck = new LockFile(packedRefsFile);
  562. if (!lck.lock())
  563. throw new IOException(MessageFormat.format(
  564. JGitText.get().cannotLock, packedRefsFile));
  565. try {
  566. final PackedRefList packed = getPackedRefs();
  567. RefList<Ref> cur = readPackedRefs();
  568. // Iterate over all refs to be packed
  569. for (String refName : refs) {
  570. Ref ref = readRef(refName, cur);
  571. if (ref.isSymbolic())
  572. continue; // can't pack symbolic refs
  573. // Add/Update it to packed-refs
  574. int idx = cur.find(refName);
  575. if (idx >= 0)
  576. cur = cur.set(idx, peeledPackedRef(ref));
  577. else
  578. cur = cur.add(idx, peeledPackedRef(ref));
  579. }
  580. // The new content for packed-refs is collected. Persist it.
  581. commitPackedRefs(lck, cur, packed);
  582. // Now delete the loose refs which are now packed
  583. for (String refName : refs) {
  584. // Lock the loose ref
  585. File refFile = fileFor(refName);
  586. if (!fs.exists(refFile))
  587. continue;
  588. LockFile rLck = new LockFile(refFile);
  589. if (!rLck.lock())
  590. continue;
  591. try {
  592. LooseRef currentLooseRef = scanRef(null, refName);
  593. if (currentLooseRef == null || currentLooseRef.isSymbolic())
  594. continue;
  595. Ref packedRef = cur.get(refName);
  596. ObjectId clr_oid = currentLooseRef.getObjectId();
  597. if (clr_oid != null
  598. && clr_oid.equals(packedRef.getObjectId())) {
  599. RefList<LooseRef> curLoose, newLoose;
  600. do {
  601. curLoose = looseRefs.get();
  602. int idx = curLoose.find(refName);
  603. if (idx < 0)
  604. break;
  605. newLoose = curLoose.remove(idx);
  606. } while (!looseRefs.compareAndSet(curLoose, newLoose));
  607. int levels = levelsIn(refName) - 2;
  608. delete(refFile, levels, rLck);
  609. }
  610. } finally {
  611. rLck.unlock();
  612. }
  613. }
  614. // Don't fire refsChanged. The refs have not change, only their
  615. // storage.
  616. } finally {
  617. lck.unlock();
  618. }
  619. }
  620. /**
  621. * Make sure a ref is peeled and has the Storage PACKED. If the given ref
  622. * has this attributes simply return it. Otherwise create a new peeled
  623. * {@link ObjectIdRef} where Storage is set to PACKED.
  624. *
  625. * @param f
  626. * @return a ref for Storage PACKED having the same name, id, peeledId as f
  627. * @throws MissingObjectException
  628. * @throws IOException
  629. */
  630. private Ref peeledPackedRef(Ref f)
  631. throws MissingObjectException, IOException {
  632. if (f.getStorage().isPacked() && f.isPeeled()) {
  633. return f;
  634. }
  635. if (!f.isPeeled()) {
  636. f = peel(f);
  637. }
  638. ObjectId peeledObjectId = f.getPeeledObjectId();
  639. if (peeledObjectId != null) {
  640. return new ObjectIdRef.PeeledTag(PACKED, f.getName(),
  641. f.getObjectId(), peeledObjectId);
  642. } else {
  643. return new ObjectIdRef.PeeledNonTag(PACKED, f.getName(),
  644. f.getObjectId());
  645. }
  646. }
  647. void log(final RefUpdate update, final String msg, final boolean deref)
  648. throws IOException {
  649. logWriter.log(update, msg, deref);
  650. }
  651. private Ref resolve(final Ref ref, int depth, String prefix,
  652. RefList<LooseRef> loose, RefList<Ref> packed) throws IOException {
  653. if (ref.isSymbolic()) {
  654. Ref dst = ref.getTarget();
  655. if (MAX_SYMBOLIC_REF_DEPTH <= depth)
  656. return null; // claim it doesn't exist
  657. // If the cached value can be assumed to be current due to a
  658. // recent scan of the loose directory, use it.
  659. if (loose != null && dst.getName().startsWith(prefix)) {
  660. int idx;
  661. if (0 <= (idx = loose.find(dst.getName())))
  662. dst = loose.get(idx);
  663. else if (0 <= (idx = packed.find(dst.getName())))
  664. dst = packed.get(idx);
  665. else
  666. return ref;
  667. } else {
  668. dst = readRef(dst.getName(), packed);
  669. if (dst == null)
  670. return ref;
  671. }
  672. dst = resolve(dst, depth + 1, prefix, loose, packed);
  673. if (dst == null)
  674. return null;
  675. return new SymbolicRef(ref.getName(), dst);
  676. }
  677. return ref;
  678. }
  679. private PackedRefList getPackedRefs() throws IOException {
  680. final PackedRefList curList = packedRefs.get();
  681. if (!curList.snapshot.isModified(packedRefsFile))
  682. return curList;
  683. final PackedRefList newList = readPackedRefs();
  684. if (packedRefs.compareAndSet(curList, newList)
  685. && !curList.id.equals(newList.id))
  686. modCnt.incrementAndGet();
  687. return newList;
  688. }
  689. private PackedRefList readPackedRefs() throws IOException {
  690. int maxStaleRetries = 5;
  691. int retries = 0;
  692. while (true) {
  693. final FileSnapshot snapshot = FileSnapshot.save(packedRefsFile);
  694. final BufferedReader br;
  695. final MessageDigest digest = Constants.newMessageDigest();
  696. try {
  697. br = new BufferedReader(new InputStreamReader(
  698. new DigestInputStream(new FileInputStream(packedRefsFile),
  699. digest), CHARSET));
  700. } catch (FileNotFoundException noPackedRefs) {
  701. if (packedRefsFile.exists()) {
  702. throw noPackedRefs;
  703. }
  704. // Ignore it and leave the new list empty.
  705. return PackedRefList.NO_PACKED_REFS;
  706. }
  707. try {
  708. return new PackedRefList(parsePackedRefs(br), snapshot,
  709. ObjectId.fromRaw(digest.digest()));
  710. } catch (IOException e) {
  711. if (FileUtils.isStaleFileHandle(e) && retries < maxStaleRetries) {
  712. if (LOG.isDebugEnabled()) {
  713. LOG.debug(MessageFormat.format(
  714. JGitText.get().packedRefsHandleIsStale,
  715. Integer.valueOf(retries)), e);
  716. }
  717. retries++;
  718. continue;
  719. }
  720. throw e;
  721. } finally {
  722. br.close();
  723. }
  724. }
  725. }
  726. private RefList<Ref> parsePackedRefs(final BufferedReader br)
  727. throws IOException {
  728. RefList.Builder<Ref> all = new RefList.Builder<Ref>();
  729. Ref last = null;
  730. boolean peeled = false;
  731. boolean needSort = false;
  732. String p;
  733. while ((p = br.readLine()) != null) {
  734. if (p.charAt(0) == '#') {
  735. if (p.startsWith(PACKED_REFS_HEADER)) {
  736. p = p.substring(PACKED_REFS_HEADER.length());
  737. peeled = p.contains(PACKED_REFS_PEELED);
  738. }
  739. continue;
  740. }
  741. if (p.charAt(0) == '^') {
  742. if (last == null)
  743. throw new IOException(JGitText.get().peeledLineBeforeRef);
  744. ObjectId id = ObjectId.fromString(p.substring(1));
  745. last = new ObjectIdRef.PeeledTag(PACKED, last.getName(), last
  746. .getObjectId(), id);
  747. all.set(all.size() - 1, last);
  748. continue;
  749. }
  750. int sp = p.indexOf(' ');
  751. ObjectId id = ObjectId.fromString(p.substring(0, sp));
  752. String name = copy(p, sp + 1, p.length());
  753. ObjectIdRef cur;
  754. if (peeled)
  755. cur = new ObjectIdRef.PeeledNonTag(PACKED, name, id);
  756. else
  757. cur = new ObjectIdRef.Unpeeled(PACKED, name, id);
  758. if (last != null && RefComparator.compareTo(last, cur) > 0)
  759. needSort = true;
  760. all.add(cur);
  761. last = cur;
  762. }
  763. if (needSort)
  764. all.sort();
  765. return all.toRefList();
  766. }
  767. private static String copy(final String src, final int off, final int end) {
  768. // Don't use substring since it could leave a reference to the much
  769. // larger existing string. Force construction of a full new object.
  770. return new StringBuilder(end - off).append(src, off, end).toString();
  771. }
  772. private void commitPackedRefs(final LockFile lck, final RefList<Ref> refs,
  773. final PackedRefList oldPackedList) throws IOException {
  774. new RefWriter(refs) {
  775. @Override
  776. protected void writeFile(String name, byte[] content)
  777. throws IOException {
  778. lck.setFSync(true);
  779. lck.setNeedSnapshot(true);
  780. try {
  781. lck.write(content);
  782. } catch (IOException ioe) {
  783. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name), ioe);
  784. }
  785. try {
  786. lck.waitForStatChange();
  787. } catch (InterruptedException e) {
  788. lck.unlock();
  789. throw new ObjectWritingException(MessageFormat.format(JGitText.get().interruptedWriting, name));
  790. }
  791. if (!lck.commit())
  792. throw new ObjectWritingException(MessageFormat.format(JGitText.get().unableToWrite, name));
  793. byte[] digest = Constants.newMessageDigest().digest(content);
  794. packedRefs.compareAndSet(oldPackedList, new PackedRefList(refs,
  795. lck.getCommitSnapshot(), ObjectId.fromRaw(digest)));
  796. }
  797. }.writePackedRefs();
  798. }
  799. private Ref readRef(String name, RefList<Ref> packed) throws IOException {
  800. final RefList<LooseRef> curList = looseRefs.get();
  801. final int idx = curList.find(name);
  802. if (0 <= idx) {
  803. final LooseRef o = curList.get(idx);
  804. final LooseRef n = scanRef(o, name);
  805. if (n == null) {
  806. if (looseRefs.compareAndSet(curList, curList.remove(idx)))
  807. modCnt.incrementAndGet();
  808. return packed.get(name);
  809. }
  810. if (o == n)
  811. return n;
  812. if (looseRefs.compareAndSet(curList, curList.set(idx, n)))
  813. modCnt.incrementAndGet();
  814. return n;
  815. }
  816. final LooseRef n = scanRef(null, name);
  817. if (n == null)
  818. return packed.get(name);
  819. // check whether the found new ref is the an additional ref. These refs
  820. // should not go into looseRefs
  821. for (int i = 0; i < additionalRefsNames.length; i++)
  822. if (name.equals(additionalRefsNames[i]))
  823. return n;
  824. if (looseRefs.compareAndSet(curList, curList.add(idx, n)))
  825. modCnt.incrementAndGet();
  826. return n;
  827. }
  828. LooseRef scanRef(LooseRef ref, String name) throws IOException {
  829. final File path = fileFor(name);
  830. FileSnapshot currentSnapshot = null;
  831. if (ref != null) {
  832. currentSnapshot = ref.getSnapShot();
  833. if (!currentSnapshot.isModified(path))
  834. return ref;
  835. name = ref.getName();
  836. }
  837. final int limit = 4096;
  838. final byte[] buf;
  839. FileSnapshot otherSnapshot = FileSnapshot.save(path);
  840. try {
  841. buf = IO.readSome(path, limit);
  842. } catch (FileNotFoundException noFile) {
  843. if (path.exists() && path.isFile()) {
  844. throw noFile;
  845. }
  846. return null; // doesn't exist or no file; not a reference.
  847. }
  848. int n = buf.length;
  849. if (n == 0)
  850. return null; // empty file; not a reference.
  851. if (isSymRef(buf, n)) {
  852. if (n == limit)
  853. return null; // possibly truncated ref
  854. // trim trailing whitespace
  855. while (0 < n && Character.isWhitespace(buf[n - 1]))
  856. n--;
  857. if (n < 6) {
  858. String content = RawParseUtils.decode(buf, 0, n);
  859. throw new IOException(MessageFormat.format(JGitText.get().notARef, name, content));
  860. }
  861. final String target = RawParseUtils.decode(buf, 5, n);
  862. if (ref != null && ref.isSymbolic()
  863. && ref.getTarget().getName().equals(target)) {
  864. assert(currentSnapshot != null);
  865. currentSnapshot.setClean(otherSnapshot);
  866. return ref;
  867. }
  868. return newSymbolicRef(otherSnapshot, name, target);
  869. }
  870. if (n < OBJECT_ID_STRING_LENGTH)
  871. return null; // impossibly short object identifier; not a reference.
  872. final ObjectId id;
  873. try {
  874. id = ObjectId.fromString(buf, 0);
  875. if (ref != null && !ref.isSymbolic()
  876. && id.equals(ref.getTarget().getObjectId())) {
  877. assert(currentSnapshot != null);
  878. currentSnapshot.setClean(otherSnapshot);
  879. return ref;
  880. }
  881. } catch (IllegalArgumentException notRef) {
  882. while (0 < n && Character.isWhitespace(buf[n - 1]))
  883. n--;
  884. String content = RawParseUtils.decode(buf, 0, n);
  885. IOException ioException = new IOException(MessageFormat.format(JGitText.get().notARef,
  886. name, content));
  887. ioException.initCause(notRef);
  888. throw ioException;
  889. }
  890. return new LooseUnpeeled(otherSnapshot, name, id);
  891. }
  892. private static boolean isSymRef(final byte[] buf, int n) {
  893. if (n < 6)
  894. return false;
  895. return /**/buf[0] == 'r' //
  896. && buf[1] == 'e' //
  897. && buf[2] == 'f' //
  898. && buf[3] == ':' //
  899. && buf[4] == ' ';
  900. }
  901. /** If the parent should fire listeners, fires them. */
  902. private void fireRefsChanged() {
  903. final int last = lastNotifiedModCnt.get();
  904. final int curr = modCnt.get();
  905. if (last != curr && lastNotifiedModCnt.compareAndSet(last, curr) && last != 0)
  906. parent.fireEvent(new RefsChangedEvent());
  907. }
  908. /**
  909. * Create a reference update to write a temporary reference.
  910. *
  911. * @return an update for a new temporary reference.
  912. * @throws IOException
  913. * a temporary name cannot be allocated.
  914. */
  915. RefDirectoryUpdate newTemporaryUpdate() throws IOException {
  916. File tmp = File.createTempFile("renamed_", "_ref", refsDir); //$NON-NLS-1$ //$NON-NLS-2$
  917. String name = Constants.R_REFS + tmp.getName();
  918. Ref ref = new ObjectIdRef.Unpeeled(NEW, name, null);
  919. return new RefDirectoryUpdate(this, ref);
  920. }
  921. /**
  922. * Locate the file on disk for a single reference name.
  923. *
  924. * @param name
  925. * name of the ref, relative to the Git repository top level
  926. * directory (so typically starts with refs/).
  927. * @return the loose file location.
  928. */
  929. File fileFor(String name) {
  930. if (name.startsWith(R_REFS)) {
  931. name = name.substring(R_REFS.length());
  932. return new File(refsDir, name);
  933. }
  934. return new File(gitDir, name);
  935. }
  936. static int levelsIn(final String name) {
  937. int count = 0;
  938. for (int p = name.indexOf('/'); p >= 0; p = name.indexOf('/', p + 1))
  939. count++;
  940. return count;
  941. }
  942. static void delete(final File file, final int depth) throws IOException {
  943. delete(file, depth, null);
  944. }
  945. private static void delete(final File file, final int depth, LockFile rLck)
  946. throws IOException {
  947. if (!file.delete() && file.isFile()) {
  948. throw new IOException(MessageFormat.format(
  949. JGitText.get().fileCannotBeDeleted, file));
  950. }
  951. if (rLck != null) {
  952. rLck.unlock(); // otherwise cannot delete dir below
  953. }
  954. File dir = file.getParentFile();
  955. for (int i = 0; i < depth; ++i) {
  956. if (!dir.delete()) {
  957. break; // ignore problem here
  958. }
  959. dir = dir.getParentFile();
  960. }
  961. }
  962. private static class PackedRefList extends RefList<Ref> {
  963. static final PackedRefList NO_PACKED_REFS = new PackedRefList(
  964. RefList.emptyList(), FileSnapshot.MISSING_FILE,
  965. ObjectId.zeroId());
  966. final FileSnapshot snapshot;
  967. final ObjectId id;
  968. PackedRefList(RefList<Ref> src, FileSnapshot s, ObjectId i) {
  969. super(src);
  970. snapshot = s;
  971. id = i;
  972. }
  973. }
  974. private static LooseSymbolicRef newSymbolicRef(FileSnapshot snapshot,
  975. String name, String target) {
  976. Ref dst = new ObjectIdRef.Unpeeled(NEW, target, null);
  977. return new LooseSymbolicRef(snapshot, name, dst);
  978. }
  979. private static interface LooseRef extends Ref {
  980. FileSnapshot getSnapShot();
  981. LooseRef peel(ObjectIdRef newLeaf);
  982. }
  983. private final static class LoosePeeledTag extends ObjectIdRef.PeeledTag
  984. implements LooseRef {
  985. private final FileSnapshot snapShot;
  986. LoosePeeledTag(FileSnapshot snapshot, @NonNull String refName,
  987. @NonNull ObjectId id, @NonNull ObjectId p) {
  988. super(LOOSE, refName, id, p);
  989. this.snapShot = snapshot;
  990. }
  991. public FileSnapshot getSnapShot() {
  992. return snapShot;
  993. }
  994. public LooseRef peel(ObjectIdRef newLeaf) {
  995. return this;
  996. }
  997. }
  998. private final static class LooseNonTag extends ObjectIdRef.PeeledNonTag
  999. implements LooseRef {
  1000. private final FileSnapshot snapShot;
  1001. LooseNonTag(FileSnapshot snapshot, @NonNull String refName,
  1002. @NonNull ObjectId id) {
  1003. super(LOOSE, refName, id);
  1004. this.snapShot = snapshot;
  1005. }
  1006. public FileSnapshot getSnapShot() {
  1007. return snapShot;
  1008. }
  1009. public LooseRef peel(ObjectIdRef newLeaf) {
  1010. return this;
  1011. }
  1012. }
  1013. private final static class LooseUnpeeled extends ObjectIdRef.Unpeeled
  1014. implements LooseRef {
  1015. private FileSnapshot snapShot;
  1016. LooseUnpeeled(FileSnapshot snapShot, @NonNull String refName,
  1017. @NonNull ObjectId id) {
  1018. super(LOOSE, refName, id);
  1019. this.snapShot = snapShot;
  1020. }
  1021. public FileSnapshot getSnapShot() {
  1022. return snapShot;
  1023. }
  1024. @NonNull
  1025. @Override
  1026. public ObjectId getObjectId() {
  1027. ObjectId id = super.getObjectId();
  1028. assert id != null; // checked in constructor
  1029. return id;
  1030. }
  1031. public LooseRef peel(ObjectIdRef newLeaf) {
  1032. ObjectId peeledObjectId = newLeaf.getPeeledObjectId();
  1033. ObjectId objectId = getObjectId();
  1034. if (peeledObjectId != null) {
  1035. return new LoosePeeledTag(snapShot, getName(),
  1036. objectId, peeledObjectId);
  1037. } else {
  1038. return new LooseNonTag(snapShot, getName(),
  1039. objectId);
  1040. }
  1041. }
  1042. }
  1043. private final static class LooseSymbolicRef extends SymbolicRef implements
  1044. LooseRef {
  1045. private final FileSnapshot snapShot;
  1046. LooseSymbolicRef(FileSnapshot snapshot, @NonNull String refName,
  1047. @NonNull Ref target) {
  1048. super(refName, target);
  1049. this.snapShot = snapshot;
  1050. }
  1051. public FileSnapshot getSnapShot() {
  1052. return snapShot;
  1053. }
  1054. public LooseRef peel(ObjectIdRef newLeaf) {
  1055. // We should never try to peel the symbolic references.
  1056. throw new UnsupportedOperationException();
  1057. }
  1058. }
  1059. }