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.

DescribeCommand.java 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * Copyright (C) 2013, CloudBees, 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.api;
  44. import org.eclipse.jgit.api.errors.GitAPIException;
  45. import org.eclipse.jgit.api.errors.JGitInternalException;
  46. import org.eclipse.jgit.api.errors.RefNotFoundException;
  47. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  48. import org.eclipse.jgit.errors.MissingObjectException;
  49. import org.eclipse.jgit.internal.JGitText;
  50. import org.eclipse.jgit.lib.Constants;
  51. import org.eclipse.jgit.lib.ObjectId;
  52. import org.eclipse.jgit.lib.Ref;
  53. import org.eclipse.jgit.lib.Repository;
  54. import org.eclipse.jgit.revwalk.*;
  55. import java.io.IOException;
  56. import java.text.MessageFormat;
  57. import java.util.ArrayList;
  58. import java.util.Collections;
  59. import java.util.Comparator;
  60. import java.util.HashMap;
  61. import java.util.List;
  62. import java.util.Map;
  63. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  64. /**
  65. * Given a commit, show the most recent tag that is reachable from a commit.
  66. *
  67. * @since 3.2
  68. */
  69. public class DescribeCommand extends GitCommand<String> {
  70. private final RevWalk w;
  71. /**
  72. * Commit to describe.
  73. */
  74. private RevCommit target;
  75. /**
  76. * How many tags we'll consider as candidates.
  77. * This can only go up to the number of flags JGit can support in a walk,
  78. * which is 24.
  79. */
  80. private int maxCandidates = 10;
  81. /**
  82. *
  83. * @param repo
  84. */
  85. protected DescribeCommand(Repository repo) {
  86. super(repo);
  87. w = new RevWalk(repo);
  88. w.setRetainBody(false);
  89. }
  90. /**
  91. * Sets the commit to be described.
  92. *
  93. * @param target
  94. * A non-null object ID to be described.
  95. * @return {@code this}
  96. * @throws MissingObjectException
  97. * the supplied commit does not exist.
  98. * @throws IncorrectObjectTypeException
  99. * the supplied id is not a commit or an annotated tag.
  100. * @throws IOException
  101. * a pack file or loose object could not be read.
  102. */
  103. public DescribeCommand setTarget(ObjectId target) throws IOException {
  104. this.target = w.parseCommit(target);
  105. return this;
  106. }
  107. /**
  108. * Sets the commit to be described.
  109. *
  110. * @param rev
  111. * Commit ID, tag, branch, ref, etc.
  112. * See {@link Repository#resolve(String)} for allowed syntax.
  113. * @return {@code this}
  114. * @throws IncorrectObjectTypeException
  115. * the supplied id is not a commit or an annotated tag.
  116. * @throws RefNotFoundException
  117. * the given rev didn't resolve to any object.
  118. * @throws IOException
  119. * a pack file or loose object could not be read.
  120. */
  121. public DescribeCommand setTarget(String rev) throws IOException,
  122. RefNotFoundException {
  123. ObjectId id = repo.resolve(rev);
  124. if (id == null)
  125. throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, rev));
  126. return setTarget(id);
  127. }
  128. /**
  129. * Describes the specified commit. Target defaults to HEAD if no commit was
  130. * set explicitly.
  131. *
  132. * @return if there's a tag that points to the commit being described, this
  133. * tag name is returned. Otherwise additional suffix is added to the
  134. * nearest tag, just like git-describe(1).
  135. * <p>
  136. * If none of the ancestors of the commit being described has any
  137. * tags at all, then this method returns null, indicating that
  138. * there's no way to describe this tag.
  139. */
  140. @Override
  141. public String call() throws GitAPIException {
  142. try {
  143. checkCallable();
  144. if (target == null)
  145. setTarget(Constants.HEAD);
  146. Map<ObjectId, Ref> tags = new HashMap<ObjectId, Ref>();
  147. for (Ref r : repo.getRefDatabase().getRefs(R_TAGS).values()) {
  148. ObjectId key = repo.peel(r).getPeeledObjectId();
  149. if (key == null)
  150. key = r.getObjectId();
  151. tags.put(key, r);
  152. }
  153. // combined flags of all the candidate instances
  154. final RevFlagSet allFlags = new RevFlagSet();
  155. /**
  156. * Tracks the depth of each tag as we find them.
  157. */
  158. class Candidate {
  159. final Ref tag;
  160. final RevFlag flag;
  161. /**
  162. * This field counts number of commits that are reachable from
  163. * the tip but not reachable from the tag.
  164. */
  165. int depth;
  166. Candidate(RevCommit commit, Ref tag) {
  167. this.tag = tag;
  168. this.flag = w.newFlag(tag.getName());
  169. // we'll mark all the nodes reachable from this tag accordingly
  170. allFlags.add(flag);
  171. w.carry(flag);
  172. commit.add(flag);
  173. // As of this writing, JGit carries a flag from a child to its parents
  174. // right before RevWalk.next() returns, so all the flags that are added
  175. // must be manually carried to its parents. If that gets fixed,
  176. // this will be unnecessary.
  177. commit.carry(flag);
  178. }
  179. /**
  180. * Does this tag contain the given commit?
  181. */
  182. boolean reaches(RevCommit c) {
  183. return c.has(flag);
  184. }
  185. String describe(ObjectId tip) throws IOException {
  186. return String.format("%s-%d-g%s", tag.getName().substring(R_TAGS.length()), //$NON-NLS-1$
  187. Integer.valueOf(depth), w.getObjectReader().abbreviate(tip).name());
  188. }
  189. }
  190. List<Candidate> candidates = new ArrayList<Candidate>(); // all the candidates we find
  191. // is the target already pointing to a tag? if so, we are done!
  192. Ref lucky = tags.get(target);
  193. if (lucky != null)
  194. return lucky.getName().substring(R_TAGS.length());
  195. w.markStart(target);
  196. int seen = 0; // commit seen thus far
  197. RevCommit c;
  198. while ((c = w.next()) != null) {
  199. if (!c.hasAny(allFlags)) {
  200. // if a tag already dominates this commit,
  201. // then there's no point in picking a tag on this commit
  202. // since the one that dominates it is always more preferable
  203. Ref t = tags.get(c);
  204. if (t != null) {
  205. Candidate cd = new Candidate(c, t);
  206. candidates.add(cd);
  207. cd.depth = seen;
  208. }
  209. }
  210. // if the newly discovered commit isn't reachable from a tag that we've seen
  211. // it counts toward the total depth.
  212. for (Candidate cd : candidates) {
  213. if (!cd.reaches(c))
  214. cd.depth++;
  215. }
  216. // if we have search going for enough tags, we will start
  217. // closing down. JGit can only give us a finite number of bits,
  218. // so we can't track all tags even if we wanted to.
  219. if (candidates.size() >= maxCandidates)
  220. break;
  221. // TODO: if all the commits in the queue of RevWalk has allFlags
  222. // there's no point in continuing search as we'll not discover any more
  223. // tags. But RevWalk doesn't expose this.
  224. seen++;
  225. }
  226. // at this point we aren't adding any more tags to our search,
  227. // but we still need to count all the depths correctly.
  228. while ((c = w.next()) != null) {
  229. if (c.hasAll(allFlags)) {
  230. // no point in visiting further from here, so cut the search here
  231. for (RevCommit p : c.getParents())
  232. p.add(RevFlag.SEEN);
  233. } else {
  234. for (Candidate cd : candidates) {
  235. if (!cd.reaches(c))
  236. cd.depth++;
  237. }
  238. }
  239. }
  240. // if all the nodes are dominated by all the tags, the walk stops
  241. if (candidates.isEmpty())
  242. return null;
  243. Candidate best = Collections.min(candidates, new Comparator<Candidate>() {
  244. public int compare(Candidate o1, Candidate o2) {
  245. return o1.depth - o2.depth;
  246. }
  247. });
  248. return best.describe(target);
  249. } catch (IOException e) {
  250. throw new JGitInternalException(e.getMessage(), e);
  251. } finally {
  252. setCallable(false);
  253. w.release();
  254. }
  255. }
  256. }