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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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.OBJ_BLOB;
  45. import static org.eclipse.jgit.lib.Constants.R_REFS;
  46. import static org.eclipse.jgit.lib.Constants.encode;
  47. import static org.eclipse.jgit.lib.FileMode.GITLINK;
  48. import static org.eclipse.jgit.lib.FileMode.SYMLINK;
  49. import static org.eclipse.jgit.lib.FileMode.TYPE_GITLINK;
  50. import static org.eclipse.jgit.lib.FileMode.TYPE_SYMLINK;
  51. import static org.eclipse.jgit.lib.Ref.Storage.NEW;
  52. import static org.eclipse.jgit.lib.Ref.Storage.PACKED;
  53. import static org.eclipse.jgit.lib.RefDatabase.MAX_SYMBOLIC_REF_DEPTH;
  54. import static org.eclipse.jgit.transport.ReceiveCommand.Result.LOCK_FAILURE;
  55. import static org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED;
  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.SymbolicRef;
  80. import org.eclipse.jgit.revwalk.RevTree;
  81. import org.eclipse.jgit.util.RawParseUtils;
  82. /**
  83. * Tree of references in the reference graph.
  84. * <p>
  85. * The root corresponds to the {@code "refs/"} subdirectory, for example the
  86. * default reference {@code "refs/heads/master"} is stored at path
  87. * {@code "heads/master"} in a {@code RefTree}.
  88. * <p>
  89. * Normal references are stored as {@link FileMode#GITLINK} tree entries. The
  90. * ObjectId in the tree entry is the ObjectId the reference refers to.
  91. * <p>
  92. * Symbolic references are stored as {@link FileMode#SYMLINK} entries, with the
  93. * blob storing the name of the target reference.
  94. * <p>
  95. * Annotated tags also store the peeled object using a {@code GITLINK} entry
  96. * with the suffix <code>"^{}"</code>, for example {@code "tags/v1.0"} stores
  97. * the annotated tag object, while <code>"tags/v1.0^{}"</code> stores the commit
  98. * the tag annotates.
  99. * <p>
  100. * {@code HEAD} is a special case and stored as {@code "..HEAD"}.
  101. */
  102. public class RefTree {
  103. /** Suffix applied to GITLINK to indicate its the peeled value of a tag. */
  104. public static final String PEELED_SUFFIX = "^{}"; //$NON-NLS-1$
  105. static final String ROOT_DOTDOT = ".."; //$NON-NLS-1$
  106. /**
  107. * Create an empty reference tree.
  108. *
  109. * @return a new empty reference tree.
  110. */
  111. public static RefTree newEmptyTree() {
  112. return new RefTree(DirCache.newInCore());
  113. }
  114. /**
  115. * Load a reference tree.
  116. *
  117. * @param reader
  118. * reader to scan the reference tree with.
  119. * @param tree
  120. * the tree to read.
  121. * @return the ref tree read from the commit.
  122. * @throws IOException
  123. * the repository cannot be accessed through the reader.
  124. * @throws CorruptObjectException
  125. * a tree object is corrupt and cannot be read.
  126. * @throws IncorrectObjectTypeException
  127. * a tree object wasn't actually a tree.
  128. * @throws MissingObjectException
  129. * a reference tree object doesn't exist.
  130. */
  131. public static RefTree read(ObjectReader reader, RevTree tree)
  132. throws MissingObjectException, IncorrectObjectTypeException,
  133. CorruptObjectException, IOException {
  134. return new RefTree(DirCache.read(reader, tree));
  135. }
  136. private DirCache contents;
  137. private Map<ObjectId, String> pendingBlobs;
  138. private RefTree(DirCache dc) {
  139. this.contents = dc;
  140. }
  141. /**
  142. * Read one reference.
  143. * <p>
  144. * References are always returned peeled ({@link Ref#isPeeled()} is true).
  145. * If the reference points to an annotated tag, the returned reference will
  146. * be peeled and contain {@link Ref#getPeeledObjectId()}.
  147. * <p>
  148. * If the reference is a symbolic reference and the chain depth is less than
  149. * {@link org.eclipse.jgit.lib.RefDatabase#MAX_SYMBOLIC_REF_DEPTH} the
  150. * returned reference is resolved. If the chain depth is longer, the
  151. * symbolic reference is returned without resolving.
  152. *
  153. * @param reader
  154. * to access objects necessary to read the requested reference.
  155. * @param name
  156. * name of the reference to read.
  157. * @return the reference; null if it does not exist.
  158. * @throws IOException
  159. * cannot read a symbolic reference target.
  160. */
  161. @Nullable
  162. public Ref exactRef(ObjectReader reader, String name) throws IOException {
  163. Ref r = readRef(reader, name);
  164. if (r == null) {
  165. return null;
  166. } else if (r.isSymbolic()) {
  167. return resolve(reader, r, 0);
  168. }
  169. DirCacheEntry p = contents.getEntry(peeledPath(name));
  170. if (p != null && p.getRawMode() == TYPE_GITLINK) {
  171. return new ObjectIdRef.PeeledTag(PACKED, r.getName(),
  172. r.getObjectId(), p.getObjectId());
  173. }
  174. return r;
  175. }
  176. private Ref readRef(ObjectReader reader, String name) throws IOException {
  177. DirCacheEntry e = contents.getEntry(refPath(name));
  178. return e != null ? toRef(reader, e, name) : null;
  179. }
  180. private Ref toRef(ObjectReader reader, DirCacheEntry e, String name)
  181. throws IOException {
  182. int mode = e.getRawMode();
  183. if (mode == TYPE_GITLINK) {
  184. ObjectId id = e.getObjectId();
  185. return new ObjectIdRef.PeeledNonTag(PACKED, name, id);
  186. }
  187. if (mode == TYPE_SYMLINK) {
  188. ObjectId id = e.getObjectId();
  189. String n = pendingBlobs != null ? pendingBlobs.get(id) : null;
  190. if (n == null) {
  191. byte[] bin = reader.open(id, OBJ_BLOB).getCachedBytes();
  192. n = RawParseUtils.decode(bin);
  193. }
  194. Ref dst = new ObjectIdRef.Unpeeled(NEW, n, null);
  195. return new SymbolicRef(name, dst);
  196. }
  197. return null; // garbage file or something; not a reference.
  198. }
  199. private Ref resolve(ObjectReader reader, Ref ref, int depth)
  200. throws IOException {
  201. if (ref.isSymbolic() && depth < MAX_SYMBOLIC_REF_DEPTH) {
  202. Ref r = readRef(reader, ref.getTarget().getName());
  203. if (r == null) {
  204. return ref;
  205. }
  206. Ref dst = resolve(reader, r, depth + 1);
  207. return new SymbolicRef(ref.getName(), dst);
  208. }
  209. return ref;
  210. }
  211. /**
  212. * Attempt a batch of commands against this RefTree.
  213. * <p>
  214. * The batch is applied atomically, either all commands apply at once, or
  215. * they all reject and the RefTree is left unmodified.
  216. * <p>
  217. * On success (when this method returns {@code true}) the command results
  218. * are left as-is (probably {@code NOT_ATTEMPTED}). Result fields are set
  219. * only when this method returns {@code false} to indicate failure.
  220. *
  221. * @param cmdList
  222. * to apply. All commands should still have result NOT_ATTEMPTED.
  223. * @return true if the commands applied; false if they were rejected.
  224. */
  225. public boolean apply(Collection<Command> cmdList) {
  226. try {
  227. DirCacheEditor ed = contents.editor();
  228. for (Command cmd : cmdList) {
  229. apply(ed, cmd);
  230. }
  231. ed.finish();
  232. return true;
  233. } catch (DirCacheNameConflictException e) {
  234. String r1 = refName(e.getPath1());
  235. String r2 = refName(e.getPath2());
  236. for (Command cmd : cmdList) {
  237. if (r1.equals(cmd.getRefName())
  238. || r2.equals(cmd.getRefName())) {
  239. cmd.setResult(LOCK_FAILURE);
  240. break;
  241. }
  242. }
  243. return abort(cmdList);
  244. } catch (LockFailureException e) {
  245. return abort(cmdList);
  246. }
  247. }
  248. private void apply(DirCacheEditor ed, final Command cmd) {
  249. String path = refPath(cmd.getRefName());
  250. Ref oldRef = cmd.getOldRef();
  251. final Ref newRef = cmd.getNewRef();
  252. if (newRef == null) {
  253. checkRef(contents.getEntry(path), cmd);
  254. ed.add(new DeletePath(path));
  255. cleanupPeeledRef(ed, oldRef);
  256. return;
  257. }
  258. if (newRef.isSymbolic()) {
  259. final String dst = newRef.getTarget().getName();
  260. ed.add(new PathEdit(path) {
  261. @Override
  262. public void apply(DirCacheEntry ent) {
  263. checkRef(ent, cmd);
  264. ObjectId id = Command.symref(dst);
  265. ent.setFileMode(SYMLINK);
  266. ent.setObjectId(id);
  267. if (pendingBlobs == null) {
  268. pendingBlobs = new HashMap<>(4);
  269. }
  270. pendingBlobs.put(id, dst);
  271. }
  272. }.setReplace(false));
  273. cleanupPeeledRef(ed, oldRef);
  274. return;
  275. }
  276. ed.add(new PathEdit(path) {
  277. @Override
  278. public void apply(DirCacheEntry ent) {
  279. checkRef(ent, cmd);
  280. ent.setFileMode(GITLINK);
  281. ent.setObjectId(newRef.getObjectId());
  282. }
  283. }.setReplace(false));
  284. if (newRef.getPeeledObjectId() != null) {
  285. ed.add(new PathEdit(peeledPath(newRef.getName())) {
  286. @Override
  287. public void apply(DirCacheEntry ent) {
  288. ent.setFileMode(GITLINK);
  289. ent.setObjectId(newRef.getPeeledObjectId());
  290. }
  291. }.setReplace(false));
  292. } else {
  293. cleanupPeeledRef(ed, oldRef);
  294. }
  295. }
  296. private static void checkRef(@Nullable DirCacheEntry ent, Command cmd) {
  297. if (!cmd.checkRef(ent)) {
  298. cmd.setResult(LOCK_FAILURE);
  299. throw new LockFailureException();
  300. }
  301. }
  302. private static void cleanupPeeledRef(DirCacheEditor ed, Ref ref) {
  303. if (ref != null && !ref.isSymbolic()
  304. && (!ref.isPeeled() || ref.getPeeledObjectId() != null)) {
  305. ed.add(new DeletePath(peeledPath(ref.getName())));
  306. }
  307. }
  308. private static boolean abort(Iterable<Command> cmdList) {
  309. for (Command cmd : cmdList) {
  310. if (cmd.getResult() == NOT_ATTEMPTED) {
  311. reject(cmd, JGitText.get().transactionAborted);
  312. }
  313. }
  314. return false;
  315. }
  316. private static void reject(Command cmd, String msg) {
  317. cmd.setResult(REJECTED_OTHER_REASON, msg);
  318. }
  319. /**
  320. * Convert a path name in a RefTree to the reference name known by Git.
  321. *
  322. * @param path
  323. * name read from the RefTree structure, for example
  324. * {@code "heads/master"}.
  325. * @return reference name for the path, {@code "refs/heads/master"}.
  326. */
  327. public static String refName(String path) {
  328. if (path.startsWith(ROOT_DOTDOT)) {
  329. return path.substring(2);
  330. }
  331. return R_REFS + path;
  332. }
  333. private static String refPath(String name) {
  334. if (name.startsWith(R_REFS)) {
  335. return name.substring(R_REFS.length());
  336. }
  337. return ROOT_DOTDOT + name;
  338. }
  339. private static String peeledPath(String name) {
  340. return refPath(name) + PEELED_SUFFIX;
  341. }
  342. /**
  343. * Write this reference tree.
  344. *
  345. * @param inserter
  346. * inserter to use when writing trees to the object database.
  347. * Caller is responsible for flushing the inserter before trying
  348. * to read the objects, or exposing them through a reference.
  349. * @return the top level tree.
  350. * @throws IOException
  351. * a tree could not be written.
  352. */
  353. public ObjectId writeTree(ObjectInserter inserter) throws IOException {
  354. if (pendingBlobs != null) {
  355. for (String s : pendingBlobs.values()) {
  356. inserter.insert(OBJ_BLOB, encode(s));
  357. }
  358. pendingBlobs = null;
  359. }
  360. return contents.writeTree(inserter);
  361. }
  362. /** @return a deep copy of this RefTree. */
  363. public RefTree copy() {
  364. RefTree r = new RefTree(DirCache.newInCore());
  365. DirCacheBuilder b = r.contents.builder();
  366. for (int i = 0; i < contents.getEntryCount(); i++) {
  367. b.add(new DirCacheEntry(contents.getEntry(i)));
  368. }
  369. b.finish();
  370. if (pendingBlobs != null) {
  371. r.pendingBlobs = new HashMap<>(pendingBlobs);
  372. }
  373. return r;
  374. }
  375. private static class LockFailureException extends RuntimeException {
  376. private static final long serialVersionUID = 1L;
  377. }
  378. }