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.9KB

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