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

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