Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DescribeCommand.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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 org.eclipse.jgit.api.errors.GitAPIException;
  45. import org.eclipse.jgit.api.errors.JGitInternalException;
  46. import org.eclipse.jgit.api.errors.RefNotFoundException;
  47. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  48. import org.eclipse.jgit.errors.MissingObjectException;
  49. import org.eclipse.jgit.internal.JGitText;
  50. import org.eclipse.jgit.lib.ObjectId;
  51. import org.eclipse.jgit.lib.Ref;
  52. import org.eclipse.jgit.lib.Repository;
  53. import org.eclipse.jgit.revwalk.*;
  54. import java.io.IOException;
  55. import java.text.MessageFormat;
  56. import java.util.ArrayList;
  57. import java.util.Collections;
  58. import java.util.Comparator;
  59. import java.util.HashMap;
  60. import java.util.List;
  61. import java.util.Map;
  62. import static org.eclipse.jgit.lib.Constants.R_TAGS;
  63. /**
  64. * Given a commit, show the most recent tag that is reachable from a commit.
  65. *
  66. * @since 3.1
  67. */
  68. public class DescribeCommand extends GitCommand<String> {
  69. private final RevWalk w;
  70. /**
  71. * Commit to describe.
  72. */
  73. private RevCommit target;
  74. /**
  75. * How many tags we'll consider as candidates.
  76. * This can only go up to the number of flags JGit can support in a walk,
  77. * which is 24.
  78. */
  79. private int maxCandidates = 10;
  80. /**
  81. *
  82. * @param repo
  83. */
  84. protected DescribeCommand(Repository repo) {
  85. super(repo);
  86. w = new RevWalk(repo);
  87. w.setRetainBody(false);
  88. }
  89. /**
  90. * Sets the commit to be described.
  91. *
  92. * @param target
  93. * A non-null object ID to be described.
  94. * @return {@code this}
  95. * @throws MissingObjectException
  96. * the supplied commit does not exist.
  97. * @throws IncorrectObjectTypeException
  98. * the supplied id is not a commit or an annotated tag.
  99. * @throws IOException
  100. * a pack file or loose object could not be read.
  101. */
  102. DescribeCommand setTarget(ObjectId target) throws IOException {
  103. this.target = w.parseCommit(target);
  104. return this;
  105. }
  106. /**
  107. * Sets the commit to be described.
  108. *
  109. * @param rev
  110. * Commit ID, tag, branch, ref, etc.
  111. * See {@link Repository#resolve(String)} for allowed syntax.
  112. * @return {@code this}
  113. * @throws IncorrectObjectTypeException
  114. * the supplied id is not a commit or an annotated tag.
  115. * @throws RefNotFoundException
  116. * the given rev didn't resolve to any object.
  117. * @throws IOException
  118. * a pack file or loose object could not be read.
  119. */
  120. DescribeCommand setTarget(String rev) throws IOException, RefNotFoundException {
  121. ObjectId id = repo.resolve(rev);
  122. if (id == null)
  123. throw new RefNotFoundException(MessageFormat.format(JGitText.get().refNotResolved, rev));
  124. return setTarget(id);
  125. }
  126. /**
  127. * Describes the specified commit.
  128. *
  129. * @return if there's a tag that points to the commit being described, this tag name
  130. * is returned. Otherwise additional suffix is added to the nearest tag, just
  131. * like git-describe(1).
  132. * <p/>
  133. * If none of the ancestors of the commit being described has any tags at all,
  134. * then this method returns null, indicating that there's no way to describe this tag.
  135. */
  136. @Override
  137. public String call() throws GitAPIException {
  138. try {
  139. checkCallable();
  140. if (target == null)
  141. throw new IllegalArgumentException(JGitText.get().targetIsNotSet);
  142. Map<ObjectId, Ref> tags = new HashMap<ObjectId, Ref>();
  143. for (Ref r : repo.getTags().values()) {
  144. ObjectId key = repo.peel(r).getPeeledObjectId();
  145. if (key == null)
  146. key = r.getObjectId();
  147. tags.put(key, r);
  148. }
  149. // combined flags of all the candidate instances
  150. final RevFlagSet allFlags = new RevFlagSet();
  151. /**
  152. * Tracks the depth of each tag as we find them.
  153. */
  154. class Candidate {
  155. final Ref tag;
  156. final RevFlag flag;
  157. /**
  158. * This field counts number of commits that are reachable from
  159. * the tip but not reachable from the tag.
  160. */
  161. int depth;
  162. Candidate(RevCommit commit, Ref tag) {
  163. this.tag = tag;
  164. this.flag = w.newFlag(tag.getName());
  165. // we'll mark all the nodes reachable from this tag accordingly
  166. allFlags.add(flag);
  167. w.carry(flag);
  168. commit.add(flag);
  169. // As of this writing, JGit carries a flag from a child to its parents
  170. // right before RevWalk.next() returns, so all the flags that are added
  171. // must be manually carried to its parents. If that gets fixed,
  172. // this will be unnecessary.
  173. commit.carry(flag);
  174. }
  175. /**
  176. * Does this tag contain the given commit?
  177. */
  178. boolean reaches(RevCommit c) {
  179. return c.has(flag);
  180. }
  181. String describe(ObjectId tip) throws IOException {
  182. return String.format("%s-%d-g%s", tag.getName().substring(R_TAGS.length()), //$NON-NLS-1$
  183. Integer.valueOf(depth), w.getObjectReader().abbreviate(tip).name());
  184. }
  185. }
  186. List<Candidate> candidates = new ArrayList<Candidate>(); // all the candidates we find
  187. // is the target already pointing to a tag? if so, we are done!
  188. Ref lucky = tags.get(target);
  189. if (lucky != null)
  190. return lucky.getName().substring(R_TAGS.length());
  191. w.markStart(target);
  192. int seen = 0; // commit seen thus far
  193. RevCommit c;
  194. while ((c = w.next()) != null) {
  195. if (!c.hasAny(allFlags)) {
  196. // if a tag already dominates this commit,
  197. // then there's no point in picking a tag on this commit
  198. // since the one that dominates it is always more preferable
  199. Ref t = tags.get(c);
  200. if (t != null) {
  201. Candidate cd = new Candidate(c, t);
  202. candidates.add(cd);
  203. cd.depth = seen;
  204. }
  205. }
  206. // if the newly discovered commit isn't reachable from a tag that we've seen
  207. // it counts toward the total depth.
  208. for (Candidate cd : candidates) {
  209. if (!cd.reaches(c))
  210. cd.depth++;
  211. }
  212. // if we have search going for enough tags, we will start
  213. // closing down. JGit can only give us a finite number of bits,
  214. // so we can't track all tags even if we wanted to.
  215. if (candidates.size() >= maxCandidates)
  216. break;
  217. // TODO: if all the commits in the queue of RevWalk has allFlags
  218. // there's no point in continuing search as we'll not discover any more
  219. // tags. But RevWalk doesn't expose this.
  220. seen++;
  221. }
  222. // at this point we aren't adding any more tags to our search,
  223. // but we still need to count all the depths correctly.
  224. while ((c = w.next()) != null) {
  225. if (c.hasAll(allFlags)) {
  226. // no point in visiting further from here, so cut the search here
  227. for (RevCommit p : c.getParents())
  228. p.add(RevFlag.SEEN);
  229. } else {
  230. for (Candidate cd : candidates) {
  231. if (!cd.reaches(c))
  232. cd.depth++;
  233. }
  234. }
  235. }
  236. // if all the nodes are dominated by all the tags, the walk stops
  237. if (candidates.isEmpty())
  238. return null;
  239. Candidate best = Collections.min(candidates, new Comparator<Candidate>() {
  240. public int compare(Candidate o1, Candidate o2) {
  241. return o1.depth - o2.depth;
  242. }
  243. });
  244. return best.describe(target);
  245. } catch (IOException e) {
  246. throw new JGitInternalException(e.getMessage(), e);
  247. } finally {
  248. setCallable(false);
  249. w.release();
  250. }
  251. }
  252. }