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

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