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.

RefTree.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. /*
  2. * Copyright (C) 2016, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.reftree;
  44. import static org.eclipse.jgit.lib.Constants.HEAD;
  45. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  46. import static org.eclipse.jgit.lib.Constants.R_REFS;
  47. import static org.eclipse.jgit.lib.Constants.encode;
  48. import static org.eclipse.jgit.lib.FileMode.GITLINK;
  49. import static org.eclipse.jgit.lib.FileMode.SYMLINK;
  50. import static org.eclipse.jgit.lib.FileMode.TYPE_GITLINK;
  51. import static org.eclipse.jgit.lib.FileMode.TYPE_SYMLINK;
  52. import static org.eclipse.jgit.lib.Ref.Storage.NEW;
  53. import static org.eclipse.jgit.lib.Ref.Storage.PACKED;
  54. import static org.eclipse.jgit.lib.RefDatabase.MAX_SYMBOLIC_REF_DEPTH;
  55. import static org.eclipse.jgit.transport.ReceiveCommand.Result.LOCK_FAILURE;
  56. import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_OTHER_REASON;
  57. import java.io.IOException;
  58. import java.util.Collection;
  59. import java.util.HashMap;
  60. import java.util.Map;
  61. import org.eclipse.jgit.annotations.Nullable;
  62. import org.eclipse.jgit.dircache.DirCache;
  63. import org.eclipse.jgit.dircache.DirCacheBuilder;
  64. import org.eclipse.jgit.dircache.DirCacheEditor;
  65. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  66. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  67. import org.eclipse.jgit.dircache.DirCacheEntry;
  68. import org.eclipse.jgit.errors.CorruptObjectException;
  69. import org.eclipse.jgit.errors.DirCacheNameConflictException;
  70. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  71. import org.eclipse.jgit.errors.MissingObjectException;
  72. import org.eclipse.jgit.internal.JGitText;
  73. import org.eclipse.jgit.lib.FileMode;
  74. import org.eclipse.jgit.lib.ObjectId;
  75. import org.eclipse.jgit.lib.ObjectIdRef;
  76. import org.eclipse.jgit.lib.ObjectInserter;
  77. import org.eclipse.jgit.lib.ObjectReader;
  78. import org.eclipse.jgit.lib.Ref;
  79. import org.eclipse.jgit.lib.Repository;
  80. import org.eclipse.jgit.lib.SymbolicRef;
  81. import org.eclipse.jgit.revwalk.RevTree;
  82. import org.eclipse.jgit.util.RawParseUtils;
  83. /**
  84. * Tree of references in the reference graph.
  85. * <p>
  86. * The root corresponds to the {@code "refs/"} subdirectory, for example the
  87. * default reference {@code "refs/heads/master"} is stored at path
  88. * {@code "heads/master"} in a {@code RefTree}.
  89. * <p>
  90. * Normal references are stored as {@link FileMode#GITLINK} tree entries. The
  91. * ObjectId in the tree entry is the ObjectId the reference refers to.
  92. * <p>
  93. * Symbolic references are stored as {@link FileMode#SYMLINK} entries, with the
  94. * blob storing the name of the target reference.
  95. * <p>
  96. * Annotated tags also store the peeled object using a {@code GITLINK} entry
  97. * with the suffix <code>" ^"</code> (space carrot), for example
  98. * {@code "tags/v1.0"} stores the annotated tag object, while
  99. * <code>"tags/v1.0 ^"</code> stores the commit the tag annotates.
  100. * <p>
  101. * {@code HEAD} is a special case and stored as {@code "..HEAD"}.
  102. */
  103. public class RefTree {
  104. /** Suffix applied to GITLINK to indicate its the peeled value of a tag. */
  105. public static final String PEELED_SUFFIX = " ^"; //$NON-NLS-1$
  106. static final String ROOT_DOTDOT = ".."; //$NON-NLS-1$
  107. /**
  108. * Create an empty reference tree.
  109. *
  110. * @return a new empty reference tree.
  111. */
  112. public static RefTree newEmptyTree() {
  113. return new RefTree(DirCache.newInCore());
  114. }
  115. /**
  116. * Load a reference tree.
  117. *
  118. * @param reader
  119. * reader to scan the reference tree with.
  120. * @param tree
  121. * the tree to read.
  122. * @return the ref tree read from the commit.
  123. * @throws IOException
  124. * the repository cannot be accessed through the reader.
  125. * @throws CorruptObjectException
  126. * a tree object is corrupt and cannot be read.
  127. * @throws IncorrectObjectTypeException
  128. * a tree object wasn't actually a tree.
  129. * @throws MissingObjectException
  130. * a reference tree object doesn't exist.
  131. */
  132. public static RefTree read(ObjectReader reader, RevTree tree)
  133. throws MissingObjectException, IncorrectObjectTypeException,
  134. CorruptObjectException, IOException {
  135. return new RefTree(DirCache.read(reader, tree));
  136. }
  137. private DirCache contents;
  138. private Map<ObjectId, String> pendingBlobs;
  139. private RefTree(DirCache dc) {
  140. this.contents = dc;
  141. }
  142. /**
  143. * Read one reference.
  144. * <p>
  145. * References are always returned peeled ({@link Ref#isPeeled()} is true).
  146. * If the reference points to an annotated tag, the returned reference will
  147. * be peeled and contain {@link Ref#getPeeledObjectId()}.
  148. * <p>
  149. * If the reference is a symbolic reference and the chain depth is less than
  150. * {@link org.eclipse.jgit.lib.RefDatabase#MAX_SYMBOLIC_REF_DEPTH} the
  151. * returned reference is resolved. If the chain depth is longer, the
  152. * symbolic reference is returned without resolving.
  153. *
  154. * @param reader
  155. * to access objects necessary to read the requested reference.
  156. * @param name
  157. * name of the reference to read.
  158. * @return the reference; null if it does not exist.
  159. * @throws IOException
  160. * cannot read a symbolic reference target.
  161. */
  162. @Nullable
  163. public Ref exactRef(ObjectReader reader, String name) throws IOException {
  164. Ref r = readRef(reader, name);
  165. if (r == null) {
  166. return null;
  167. } else if (r.isSymbolic()) {
  168. return resolve(reader, r, 0);
  169. }
  170. DirCacheEntry p = contents.getEntry(peeledPath(name));
  171. if (p != null && p.getRawMode() == TYPE_GITLINK) {
  172. return new ObjectIdRef.PeeledTag(PACKED, r.getName(),
  173. r.getObjectId(), p.getObjectId());
  174. }
  175. return r;
  176. }
  177. private Ref readRef(ObjectReader reader, String name) throws IOException {
  178. DirCacheEntry e = contents.getEntry(refPath(name));
  179. return e != null ? toRef(reader, e, name) : null;
  180. }
  181. private Ref toRef(ObjectReader reader, DirCacheEntry e, String name)
  182. throws IOException {
  183. int mode = e.getRawMode();
  184. if (mode == TYPE_GITLINK) {
  185. ObjectId id = e.getObjectId();
  186. return new ObjectIdRef.PeeledNonTag(PACKED, name, id);
  187. }
  188. if (mode == TYPE_SYMLINK) {
  189. ObjectId id = e.getObjectId();
  190. String n = pendingBlobs != null ? pendingBlobs.get(id) : null;
  191. if (n == null) {
  192. byte[] bin = reader.open(id, OBJ_BLOB).getCachedBytes();
  193. n = RawParseUtils.decode(bin);
  194. }
  195. Ref dst = new ObjectIdRef.Unpeeled(NEW, n, null);
  196. return new SymbolicRef(name, dst);
  197. }
  198. return null; // garbage file or something; not a reference.
  199. }
  200. private Ref resolve(ObjectReader reader, Ref ref, int depth)
  201. throws IOException {
  202. if (ref.isSymbolic() && depth < MAX_SYMBOLIC_REF_DEPTH) {
  203. Ref r = readRef(reader, ref.getTarget().getName());
  204. if (r == null) {
  205. return ref;
  206. }
  207. Ref dst = resolve(reader, r, depth + 1);
  208. return new SymbolicRef(ref.getName(), dst);
  209. }
  210. return ref;
  211. }
  212. /**
  213. * Attempt a batch of commands against this RefTree.
  214. * <p>
  215. * The batch is applied atomically, either all commands apply at once, or
  216. * they all reject and the RefTree is left unmodified.
  217. * <p>
  218. * On success (when this method returns {@code true}) the command results
  219. * are left as-is (probably {@code NOT_ATTEMPTED}). Result fields are set
  220. * only when this method returns {@code false} to indicate failure.
  221. *
  222. * @param cmdList
  223. * to apply. All commands should still have result NOT_ATTEMPTED.
  224. * @return true if the commands applied; false if they were rejected.
  225. */
  226. public boolean apply(Collection<Command> cmdList) {
  227. try {
  228. DirCacheEditor ed = contents.editor();
  229. for (Command cmd : cmdList) {
  230. if (!isValidRef(cmd)) {
  231. cmd.setResult(REJECTED_OTHER_REASON,
  232. JGitText.get().funnyRefname);
  233. Command.abort(cmdList, null);
  234. return false;
  235. }
  236. apply(ed, cmd);
  237. }
  238. ed.finish();
  239. return true;
  240. } catch (DirCacheNameConflictException e) {
  241. String r1 = refName(e.getPath1());
  242. String r2 = refName(e.getPath2());
  243. for (Command cmd : cmdList) {
  244. if (r1.equals(cmd.getRefName())
  245. || r2.equals(cmd.getRefName())) {
  246. cmd.setResult(LOCK_FAILURE);
  247. break;
  248. }
  249. }
  250. Command.abort(cmdList, null);
  251. return false;
  252. } catch (LockFailureException e) {
  253. Command.abort(cmdList, null);
  254. return false;
  255. }
  256. }
  257. private static boolean isValidRef(Command cmd) {
  258. String n = cmd.getRefName();
  259. return HEAD.equals(n) || Repository.isValidRefName(n);
  260. }
  261. private void apply(DirCacheEditor ed, final Command cmd) {
  262. String path = refPath(cmd.getRefName());
  263. Ref oldRef = cmd.getOldRef();
  264. final Ref newRef = cmd.getNewRef();
  265. if (newRef == null) {
  266. checkRef(contents.getEntry(path), cmd);
  267. ed.add(new DeletePath(path));
  268. cleanupPeeledRef(ed, oldRef);
  269. return;
  270. }
  271. if (newRef.isSymbolic()) {
  272. final String dst = newRef.getTarget().getName();
  273. ed.add(new PathEdit(path) {
  274. @Override
  275. public void apply(DirCacheEntry ent) {
  276. checkRef(ent, cmd);
  277. ObjectId id = Command.symref(dst);
  278. ent.setFileMode(SYMLINK);
  279. ent.setObjectId(id);
  280. if (pendingBlobs == null) {
  281. pendingBlobs = new HashMap<>(4);
  282. }
  283. pendingBlobs.put(id, dst);
  284. }
  285. }.setReplace(false));
  286. cleanupPeeledRef(ed, oldRef);
  287. return;
  288. }
  289. ed.add(new PathEdit(path) {
  290. @Override
  291. public void apply(DirCacheEntry ent) {
  292. checkRef(ent, cmd);
  293. ent.setFileMode(GITLINK);
  294. ent.setObjectId(newRef.getObjectId());
  295. }
  296. }.setReplace(false));
  297. if (newRef.getPeeledObjectId() != null) {
  298. ed.add(new PathEdit(peeledPath(newRef.getName())) {
  299. @Override
  300. public void apply(DirCacheEntry ent) {
  301. ent.setFileMode(GITLINK);
  302. ent.setObjectId(newRef.getPeeledObjectId());
  303. }
  304. }.setReplace(false));
  305. } else {
  306. cleanupPeeledRef(ed, oldRef);
  307. }
  308. }
  309. private static void checkRef(@Nullable DirCacheEntry ent, Command cmd) {
  310. if (!cmd.checkRef(ent)) {
  311. cmd.setResult(LOCK_FAILURE);
  312. throw new LockFailureException();
  313. }
  314. }
  315. private static void cleanupPeeledRef(DirCacheEditor ed, Ref ref) {
  316. if (ref != null && !ref.isSymbolic()
  317. && (!ref.isPeeled() || ref.getPeeledObjectId() != null)) {
  318. ed.add(new DeletePath(peeledPath(ref.getName())));
  319. }
  320. }
  321. /**
  322. * Convert a path name in a RefTree to the reference name known by Git.
  323. *
  324. * @param path
  325. * name read from the RefTree structure, for example
  326. * {@code "heads/master"}.
  327. * @return reference name for the path, {@code "refs/heads/master"}.
  328. */
  329. public static String refName(String path) {
  330. if (path.startsWith(ROOT_DOTDOT)) {
  331. return path.substring(2);
  332. }
  333. return R_REFS + path;
  334. }
  335. static String refPath(String name) {
  336. if (name.startsWith(R_REFS)) {
  337. return name.substring(R_REFS.length());
  338. }
  339. return ROOT_DOTDOT + name;
  340. }
  341. private static String peeledPath(String name) {
  342. return refPath(name) + PEELED_SUFFIX;
  343. }
  344. /**
  345. * Write this reference tree.
  346. *
  347. * @param inserter
  348. * inserter to use when writing trees to the object database.
  349. * Caller is responsible for flushing the inserter before trying
  350. * to read the objects, or exposing them through a reference.
  351. * @return the top level tree.
  352. * @throws IOException
  353. * a tree could not be written.
  354. */
  355. public ObjectId writeTree(ObjectInserter inserter) throws IOException {
  356. if (pendingBlobs != null) {
  357. for (String s : pendingBlobs.values()) {
  358. inserter.insert(OBJ_BLOB, encode(s));
  359. }
  360. pendingBlobs = null;
  361. }
  362. return contents.writeTree(inserter);
  363. }
  364. /** @return a deep copy of this RefTree. */
  365. public RefTree copy() {
  366. RefTree r = new RefTree(DirCache.newInCore());
  367. DirCacheBuilder b = r.contents.builder();
  368. for (int i = 0; i < contents.getEntryCount(); i++) {
  369. b.add(new DirCacheEntry(contents.getEntry(i)));
  370. }
  371. b.finish();
  372. if (pendingBlobs != null) {
  373. r.pendingBlobs = new HashMap<>(pendingBlobs);
  374. }
  375. return r;
  376. }
  377. private static class LockFailureException extends RuntimeException {
  378. private static final long serialVersionUID = 1L;
  379. }
  380. }