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