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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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.Collection;
  49. import java.util.Collections;
  50. import java.util.Comparator;
  51. import java.util.Date;
  52. import java.util.List;
  53. import java.util.Map;
  54. import java.util.Optional;
  55. import java.util.stream.Collectors;
  56. import java.util.stream.Stream;
  57. import org.eclipse.jgit.api.errors.GitAPIException;
  58. import org.eclipse.jgit.api.errors.JGitInternalException;
  59. import org.eclipse.jgit.api.errors.RefNotFoundException;
  60. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  61. import org.eclipse.jgit.errors.InvalidPatternException;
  62. import org.eclipse.jgit.errors.MissingObjectException;
  63. import org.eclipse.jgit.ignore.internal.IMatcher;
  64. import org.eclipse.jgit.ignore.internal.PathMatcher;
  65. import org.eclipse.jgit.internal.JGitText;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.ObjectId;
  68. import org.eclipse.jgit.lib.Ref;
  69. import org.eclipse.jgit.lib.Repository;
  70. import org.eclipse.jgit.revwalk.RevCommit;
  71. import org.eclipse.jgit.revwalk.RevFlag;
  72. import org.eclipse.jgit.revwalk.RevFlagSet;
  73. import org.eclipse.jgit.revwalk.RevTag;
  74. import org.eclipse.jgit.revwalk.RevWalk;
  75. /**
  76. * Given a commit, show the most recent tag that is reachable from a commit.
  77. *
  78. * @since 3.2
  79. */
  80. public class DescribeCommand extends GitCommand<String> {
  81. private final RevWalk w;
  82. /**
  83. * Commit to describe.
  84. */
  85. private RevCommit target;
  86. /**
  87. * How many tags we'll consider as candidates.
  88. * This can only go up to the number of flags JGit can support in a walk,
  89. * which is 24.
  90. */
  91. private int maxCandidates = 10;
  92. /**
  93. * Whether to always use long output format or not.
  94. */
  95. private boolean longDesc;
  96. /**
  97. * Pattern matchers to be applied to tags under consideration
  98. */
  99. private List<IMatcher> matchers = new ArrayList<>();
  100. /**
  101. * Whether to use all tags (incl. lightweight) or not
  102. */
  103. private boolean useTags = false;
  104. /**
  105. * Constructor for DescribeCommand.
  106. *
  107. * @param repo
  108. * the {@link org.eclipse.jgit.lib.Repository}
  109. */
  110. protected DescribeCommand(Repository repo) {
  111. super(repo);
  112. w = new RevWalk(repo);
  113. w.setRetainBody(false);
  114. }
  115. /**
  116. * Sets the commit to be described.
  117. *
  118. * @param target
  119. * A non-null object ID to be described.
  120. * @return {@code this}
  121. * @throws MissingObjectException
  122. * the supplied commit does not exist.
  123. * @throws IncorrectObjectTypeException
  124. * the supplied id is not a commit or an annotated tag.
  125. * @throws java.io.IOException
  126. * a pack file or loose object could not be read.
  127. */
  128. public DescribeCommand setTarget(ObjectId target) throws IOException {
  129. this.target = w.parseCommit(target);
  130. return this;
  131. }
  132. /**
  133. * Sets the commit to be described.
  134. *
  135. * @param rev
  136. * Commit ID, tag, branch, ref, etc. See
  137. * {@link org.eclipse.jgit.lib.Repository#resolve(String)} for
  138. * allowed syntax.
  139. * @return {@code this}
  140. * @throws IncorrectObjectTypeException
  141. * the supplied id is not a commit or an annotated tag.
  142. * @throws org.eclipse.jgit.api.errors.RefNotFoundException
  143. * the given rev didn't resolve to any object.
  144. * @throws java.io.IOException
  145. * a pack file or loose object could not be read.
  146. */
  147. public DescribeCommand setTarget(String rev) throws IOException,
  148. RefNotFoundException {
  149. ObjectId id = repo.resolve(rev);
  150. if (id == null)
  151. throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, rev));
  152. return setTarget(id);
  153. }
  154. /**
  155. * Determine whether always to use the long format or not. When set to
  156. * <code>true</code> the long format is used even the commit matches a tag.
  157. *
  158. * @param longDesc
  159. * <code>true</code> if always the long format should be used.
  160. * @return {@code this}
  161. * @see <a
  162. * href="https://www.kernel.org/pub/software/scm/git/docs/git-describe.html"
  163. * >Git documentation about describe</a>
  164. * @since 4.0
  165. */
  166. public DescribeCommand setLong(boolean longDesc) {
  167. this.longDesc = longDesc;
  168. return this;
  169. }
  170. /**
  171. * Instead of using only the annotated tags, use any tag found in refs/tags
  172. * namespace. This option enables matching lightweight (non-annotated) tags
  173. * or not.
  174. *
  175. * @param tags
  176. * <code>true</code> enables matching lightweight (non-annotated)
  177. * tags like setting option --tags in c git
  178. * @return {@code this}
  179. * @since 5.0
  180. */
  181. public DescribeCommand setTags(boolean tags) {
  182. this.useTags = tags;
  183. return this;
  184. }
  185. private String longDescription(Ref tag, int depth, ObjectId tip)
  186. throws IOException {
  187. return String.format(
  188. "%s-%d-g%s", tag.getName().substring(R_TAGS.length()), //$NON-NLS-1$
  189. Integer.valueOf(depth), w.getObjectReader().abbreviate(tip)
  190. .name());
  191. }
  192. /**
  193. * Sets one or more {@code glob(7)} patterns that tags must match to be
  194. * considered. If multiple patterns are provided, tags only need match one
  195. * of them.
  196. *
  197. * @param patterns
  198. * the {@code glob(7)} pattern or patterns
  199. * @return {@code this}
  200. * @throws org.eclipse.jgit.errors.InvalidPatternException
  201. * if the pattern passed in was invalid.
  202. * @see <a href=
  203. * "https://www.kernel.org/pub/software/scm/git/docs/git-describe.html"
  204. * >Git documentation about describe</a>
  205. * @since 4.9
  206. */
  207. public DescribeCommand setMatch(String... patterns) throws InvalidPatternException {
  208. for (String p : patterns) {
  209. matchers.add(PathMatcher.createPathMatcher(p, null, false));
  210. }
  211. return this;
  212. }
  213. private final Comparator<Ref> TAG_TIE_BREAKER = new Comparator<Ref>() {
  214. @Override
  215. public int compare(Ref o1, Ref o2) {
  216. try {
  217. return tagDate(o2).compareTo(tagDate(o1));
  218. } catch (IOException e) {
  219. return 0;
  220. }
  221. }
  222. private Date tagDate(Ref tag) throws IOException {
  223. RevTag t = w.parseTag(tag.getObjectId());
  224. w.parseBody(t);
  225. return t.getTaggerIdent().getWhen();
  226. }
  227. };
  228. private Optional<Ref> getBestMatch(List<Ref> tags) {
  229. if (tags == null || tags.size() == 0) {
  230. return Optional.empty();
  231. } else if (matchers.size() == 0) {
  232. Collections.sort(tags, TAG_TIE_BREAKER);
  233. return Optional.of(tags.get(0));
  234. } else {
  235. // Find the first tag that matches in the stream of all tags
  236. // filtered by matchers ordered by tie break order
  237. Stream<Ref> matchingTags = Stream.empty();
  238. for (IMatcher matcher : matchers) {
  239. Stream<Ref> m = tags.stream().filter(
  240. tag -> matcher.matches(tag.getName(), false, false));
  241. matchingTags = Stream.of(matchingTags, m).flatMap(i -> i);
  242. }
  243. return matchingTags.sorted(TAG_TIE_BREAKER).findFirst();
  244. }
  245. }
  246. private ObjectId getObjectIdFromRef(Ref r) throws JGitInternalException {
  247. try {
  248. ObjectId key = repo.getRefDatabase().peel(r).getPeeledObjectId();
  249. if (key == null) {
  250. key = r.getObjectId();
  251. }
  252. return key;
  253. } catch (IOException e) {
  254. throw new JGitInternalException(e.getMessage(), e);
  255. }
  256. }
  257. /**
  258. * {@inheritDoc}
  259. * <p>
  260. * Describes the specified commit. Target defaults to HEAD if no commit was
  261. * set explicitly.
  262. */
  263. @Override
  264. public String call() throws GitAPIException {
  265. try {
  266. checkCallable();
  267. if (target == null) {
  268. setTarget(Constants.HEAD);
  269. }
  270. Collection<Ref> tagList = repo.getRefDatabase()
  271. .getRefsByPrefix(R_TAGS);
  272. Map<ObjectId, List<Ref>> tags = tagList.stream()
  273. .filter(this::filterLightweightTags)
  274. .collect(Collectors.groupingBy(this::getObjectIdFromRef));
  275. // combined flags of all the candidate instances
  276. final RevFlagSet allFlags = new RevFlagSet();
  277. /**
  278. * Tracks the depth of each tag as we find them.
  279. */
  280. class Candidate {
  281. final Ref tag;
  282. final RevFlag flag;
  283. /**
  284. * This field counts number of commits that are reachable from
  285. * the tip but not reachable from the tag.
  286. */
  287. int depth;
  288. Candidate(RevCommit commit, Ref tag) {
  289. this.tag = tag;
  290. this.flag = w.newFlag(tag.getName());
  291. // we'll mark all the nodes reachable from this tag accordingly
  292. allFlags.add(flag);
  293. w.carry(flag);
  294. commit.add(flag);
  295. // As of this writing, JGit carries a flag from a child to its parents
  296. // right before RevWalk.next() returns, so all the flags that are added
  297. // must be manually carried to its parents. If that gets fixed,
  298. // this will be unnecessary.
  299. commit.carry(flag);
  300. }
  301. /**
  302. * Does this tag contain the given commit?
  303. */
  304. boolean reaches(RevCommit c) {
  305. return c.has(flag);
  306. }
  307. String describe(ObjectId tip) throws IOException {
  308. return longDescription(tag, depth, tip);
  309. }
  310. }
  311. List<Candidate> candidates = new ArrayList<>(); // all the candidates we find
  312. // is the target already pointing to a suitable tag? if so, we are done!
  313. Optional<Ref> bestMatch = getBestMatch(tags.get(target));
  314. if (bestMatch.isPresent()) {
  315. return longDesc ? longDescription(bestMatch.get(), 0, target) :
  316. bestMatch.get().getName().substring(R_TAGS.length());
  317. }
  318. w.markStart(target);
  319. int seen = 0; // commit seen thus far
  320. RevCommit c;
  321. while ((c = w.next()) != null) {
  322. if (!c.hasAny(allFlags)) {
  323. // if a tag already dominates this commit,
  324. // then there's no point in picking a tag on this commit
  325. // since the one that dominates it is always more preferable
  326. bestMatch = getBestMatch(tags.get(c));
  327. if (bestMatch.isPresent()) {
  328. Candidate cd = new Candidate(c, bestMatch.get());
  329. candidates.add(cd);
  330. cd.depth = seen;
  331. }
  332. }
  333. // if the newly discovered commit isn't reachable from a tag that we've seen
  334. // it counts toward the total depth.
  335. for (Candidate cd : candidates) {
  336. if (!cd.reaches(c))
  337. cd.depth++;
  338. }
  339. // if we have search going for enough tags, we will start
  340. // closing down. JGit can only give us a finite number of bits,
  341. // so we can't track all tags even if we wanted to.
  342. if (candidates.size() >= maxCandidates)
  343. break;
  344. // TODO: if all the commits in the queue of RevWalk has allFlags
  345. // there's no point in continuing search as we'll not discover any more
  346. // tags. But RevWalk doesn't expose this.
  347. seen++;
  348. }
  349. // at this point we aren't adding any more tags to our search,
  350. // but we still need to count all the depths correctly.
  351. while ((c = w.next()) != null) {
  352. if (c.hasAll(allFlags)) {
  353. // no point in visiting further from here, so cut the search here
  354. for (RevCommit p : c.getParents())
  355. p.add(RevFlag.SEEN);
  356. } else {
  357. for (Candidate cd : candidates) {
  358. if (!cd.reaches(c))
  359. cd.depth++;
  360. }
  361. }
  362. }
  363. // if all the nodes are dominated by all the tags, the walk stops
  364. if (candidates.isEmpty())
  365. return null;
  366. Candidate best = Collections.min(candidates, new Comparator<Candidate>() {
  367. @Override
  368. public int compare(Candidate o1, Candidate o2) {
  369. return o1.depth - o2.depth;
  370. }
  371. });
  372. return best.describe(target);
  373. } catch (IOException e) {
  374. throw new JGitInternalException(e.getMessage(), e);
  375. } finally {
  376. setCallable(false);
  377. w.close();
  378. }
  379. }
  380. /**
  381. * Whether we use lightweight tags or not for describe Candidates
  382. *
  383. * @param ref
  384. * reference under inspection
  385. * @return true if it should be used for describe or not regarding
  386. * {@link org.eclipse.jgit.api.DescribeCommand#useTags}
  387. */
  388. @SuppressWarnings("null")
  389. private boolean filterLightweightTags(Ref ref) {
  390. ObjectId id = ref.getObjectId();
  391. try {
  392. return this.useTags || (id != null && (w.parseTag(id) != null));
  393. } catch (IOException e) {
  394. return false;
  395. }
  396. }
  397. }