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