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