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