You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

NameRevCommand.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. * Copyright (C) 2013, Google 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 java.io.IOException;
  45. import java.util.ArrayList;
  46. import java.util.HashMap;
  47. import java.util.LinkedHashMap;
  48. import java.util.List;
  49. import java.util.Map;
  50. import org.eclipse.jgit.api.errors.GitAPIException;
  51. import org.eclipse.jgit.api.errors.JGitInternalException;
  52. import org.eclipse.jgit.errors.MissingObjectException;
  53. import org.eclipse.jgit.lib.AnyObjectId;
  54. import org.eclipse.jgit.lib.Constants;
  55. import org.eclipse.jgit.lib.ObjectId;
  56. import org.eclipse.jgit.lib.Ref;
  57. import org.eclipse.jgit.lib.RefDatabase;
  58. import org.eclipse.jgit.lib.Repository;
  59. import org.eclipse.jgit.revwalk.FIFORevQueue;
  60. import org.eclipse.jgit.revwalk.RevCommit;
  61. import org.eclipse.jgit.revwalk.RevObject;
  62. import org.eclipse.jgit.revwalk.RevTag;
  63. import org.eclipse.jgit.revwalk.RevWalk;
  64. /**
  65. * Command to find human-readable names of revisions.
  66. *
  67. * @see <a
  68. * href="http://www.kernel.org/pub/software/scm/git/docs/git-name-rev.html"
  69. * >Git documentation about name-rev</a>
  70. * @since 3.0
  71. */
  72. public class NameRevCommand extends GitCommand<Map<ObjectId, String>> {
  73. /** Amount of slop to allow walking past the earliest requested commit. */
  74. private static final int COMMIT_TIME_SLOP = 60 * 60 * 24;
  75. /** Cost of traversing a merge commit compared to a linear history. */
  76. private static final int MERGE_COST = 65535;
  77. private static class NameRevCommit extends RevCommit {
  78. private String tip;
  79. private int distance;
  80. private long cost;
  81. private NameRevCommit(AnyObjectId id) {
  82. super(id);
  83. }
  84. private StringBuilder format() {
  85. StringBuilder sb = new StringBuilder(tip);
  86. if (distance > 0)
  87. sb.append('~').append(distance);
  88. return sb;
  89. }
  90. @Override
  91. public String toString() {
  92. StringBuilder sb = new StringBuilder(getClass().getSimpleName())
  93. .append('[');
  94. if (tip != null)
  95. sb.append(format());
  96. else
  97. sb.append((Object) null);
  98. sb.append(',').append(cost).append(']').append(' ')
  99. .append(super.toString()).toString();
  100. return sb.toString();
  101. }
  102. }
  103. private final RevWalk walk;
  104. private final List<String> prefixes;
  105. private final List<Ref> refs;
  106. private final List<ObjectId> revs;
  107. private int mergeCost;
  108. /**
  109. * Create a new name-rev command.
  110. *
  111. * @param repo
  112. */
  113. protected NameRevCommand(Repository repo) {
  114. super(repo);
  115. mergeCost = MERGE_COST;
  116. prefixes = new ArrayList<String>(2);
  117. refs = new ArrayList<Ref>();
  118. revs = new ArrayList<ObjectId>(2);
  119. walk = new RevWalk(repo) {
  120. @Override
  121. public NameRevCommit createCommit(AnyObjectId id) {
  122. return new NameRevCommit(id);
  123. }
  124. };
  125. }
  126. @Override
  127. public Map<ObjectId, String> call() throws GitAPIException {
  128. try {
  129. Map<ObjectId, String> nonCommits = new HashMap<ObjectId, String>();
  130. FIFORevQueue pending = new FIFORevQueue();
  131. for (Ref ref : refs)
  132. addRef(ref, nonCommits, pending);
  133. addPrefixes(nonCommits, pending);
  134. int cutoff = minCommitTime() - COMMIT_TIME_SLOP;
  135. while (true) {
  136. NameRevCommit c = (NameRevCommit) pending.next();
  137. if (c == null)
  138. break;
  139. if (c.getCommitTime() < cutoff)
  140. continue;
  141. for (int i = 0; i < c.getParentCount(); i++) {
  142. NameRevCommit p = (NameRevCommit) walk.parseCommit(c.getParent(i));
  143. long cost = c.cost + (i > 0 ? mergeCost : 1);
  144. if (p.tip == null || compare(c.tip, cost, p.tip, p.cost) < 0) {
  145. if (i > 0) {
  146. p.tip = c.format().append('^').append(i + 1).toString();
  147. p.distance = 0;
  148. } else {
  149. p.tip = c.tip;
  150. p.distance = c.distance + 1;
  151. }
  152. p.cost = cost;
  153. pending.add(p);
  154. }
  155. }
  156. }
  157. Map<ObjectId, String> result =
  158. new LinkedHashMap<ObjectId, String>(revs.size());
  159. for (ObjectId id : revs) {
  160. RevObject o = walk.parseAny(id);
  161. if (o instanceof NameRevCommit) {
  162. NameRevCommit c = (NameRevCommit) o;
  163. if (c.tip != null)
  164. result.put(id, simplify(c.format().toString()));
  165. } else {
  166. String name = nonCommits.get(id);
  167. if (name != null)
  168. result.put(id, simplify(name));
  169. }
  170. }
  171. setCallable(false);
  172. walk.release();
  173. return result;
  174. } catch (IOException e) {
  175. walk.reset();
  176. throw new JGitInternalException(e.getMessage(), e);
  177. }
  178. }
  179. /**
  180. * Add an object to search for.
  181. *
  182. * @param id
  183. * object ID to add.
  184. * @return {@code this}
  185. * @throws MissingObjectException
  186. * the object supplied is not available from the object
  187. * database.
  188. * @throws JGitInternalException
  189. * a low-level exception of JGit has occurred. The original
  190. * exception can be retrieved by calling
  191. * {@link Exception#getCause()}.
  192. */
  193. public NameRevCommand add(ObjectId id) throws MissingObjectException,
  194. JGitInternalException {
  195. checkCallable();
  196. try {
  197. walk.parseAny(id);
  198. } catch (MissingObjectException e) {
  199. throw e;
  200. } catch (IOException e) {
  201. throw new JGitInternalException(e.getMessage(), e);
  202. }
  203. revs.add(id.copy());
  204. return this;
  205. }
  206. /**
  207. * Add multiple objects to search for.
  208. *
  209. * @param ids
  210. * object IDs to add.
  211. * @return {@code this}
  212. * @throws MissingObjectException
  213. * the object supplied is not available from the object
  214. * database.
  215. * @throws JGitInternalException
  216. * a low-level exception of JGit has occurred. The original
  217. * exception can be retrieved by calling
  218. * {@link Exception#getCause()}.
  219. */
  220. public NameRevCommand add(Iterable<ObjectId> ids)
  221. throws MissingObjectException, JGitInternalException {
  222. for (ObjectId id : ids)
  223. add(id);
  224. return this;
  225. }
  226. /**
  227. * Add a ref prefix to the set that results must match.
  228. * <p>
  229. * If an object matches multiple refs equally well, the first matching ref
  230. * added with {@link #addRef(Ref)} is preferred, or else the first matching
  231. * prefix added by {@link #addPrefix(String)}.
  232. *
  233. * @param prefix
  234. * prefix to add; see {@link RefDatabase#getRefs(String)}
  235. * @return {@code this}
  236. */
  237. public NameRevCommand addPrefix(String prefix) {
  238. checkCallable();
  239. prefixes.add(prefix);
  240. return this;
  241. }
  242. /**
  243. * Add all annotated tags under {@code refs/tags/} to the set that all results
  244. * must match.
  245. * <p>
  246. * Calls {@link #addRef(Ref)}; see that method for a note on matching
  247. * priority.
  248. *
  249. * @return {@code this}
  250. * @throws JGitInternalException
  251. * a low-level exception of JGit has occurred. The original
  252. * exception can be retrieved by calling
  253. * {@link Exception#getCause()}.
  254. */
  255. public NameRevCommand addAnnotatedTags() {
  256. checkCallable();
  257. try {
  258. for (Ref ref : repo.getRefDatabase().getRefs(Constants.R_TAGS).values()) {
  259. ObjectId id = ref.getObjectId();
  260. if (id != null && (walk.parseAny(id) instanceof RevTag))
  261. addRef(ref);
  262. }
  263. } catch (IOException e) {
  264. throw new JGitInternalException(e.getMessage(), e);
  265. }
  266. return this;
  267. }
  268. /**
  269. * Add a ref to the set that all results must match.
  270. * <p>
  271. * If an object matches multiple refs equally well, the first matching ref
  272. * added with {@link #addRef(Ref)} is preferred, or else the first matching
  273. * prefix added by {@link #addPrefix(String)}.
  274. *
  275. * @param ref
  276. * ref to add.
  277. * @return {@code this}
  278. */
  279. public NameRevCommand addRef(Ref ref) {
  280. checkCallable();
  281. refs.add(ref);
  282. return this;
  283. }
  284. NameRevCommand setMergeCost(int cost) {
  285. mergeCost = cost;
  286. return this;
  287. }
  288. private void addPrefixes(Map<ObjectId, String> nonCommits,
  289. FIFORevQueue pending) throws IOException {
  290. if (!prefixes.isEmpty()) {
  291. for (String prefix : prefixes)
  292. addPrefix(prefix, nonCommits, pending);
  293. } else if (refs.isEmpty())
  294. addPrefix(Constants.R_REFS, nonCommits, pending);
  295. }
  296. private void addPrefix(String prefix, Map<ObjectId, String> nonCommits,
  297. FIFORevQueue pending) throws IOException {
  298. for (Ref ref : repo.getRefDatabase().getRefs(prefix).values())
  299. addRef(ref, nonCommits, pending);
  300. }
  301. private void addRef(Ref ref, Map<ObjectId, String> nonCommits,
  302. FIFORevQueue pending) throws IOException {
  303. if (ref.getObjectId() == null)
  304. return;
  305. RevObject o = walk.parseAny(ref.getObjectId());
  306. while (o instanceof RevTag) {
  307. RevTag t = (RevTag) o;
  308. nonCommits.put(o, ref.getName());
  309. o = t.getObject();
  310. walk.parseHeaders(o);
  311. }
  312. if (o instanceof NameRevCommit) {
  313. NameRevCommit c = (NameRevCommit) o;
  314. if (c.tip == null)
  315. c.tip = ref.getName();
  316. pending.add(c);
  317. } else if (!nonCommits.containsKey(o))
  318. nonCommits.put(o, ref.getName());
  319. }
  320. private int minCommitTime() throws IOException {
  321. int min = Integer.MAX_VALUE;
  322. for (ObjectId id : revs) {
  323. RevObject o = walk.parseAny(id);
  324. while (o instanceof RevTag) {
  325. o = ((RevTag) o).getObject();
  326. walk.parseHeaders(o);
  327. }
  328. if (o instanceof RevCommit) {
  329. RevCommit c = (RevCommit) o;
  330. if (c.getCommitTime() < min)
  331. min = c.getCommitTime();
  332. }
  333. }
  334. return min;
  335. }
  336. private long compare(String leftTip, long leftCost, String rightTip, long rightCost) {
  337. long c = leftCost - rightCost;
  338. if (c != 0 || prefixes.isEmpty())
  339. return c;
  340. int li = -1;
  341. int ri = -1;
  342. for (int i = 0; i < prefixes.size(); i++) {
  343. String prefix = prefixes.get(i);
  344. if (li < 0 && leftTip.startsWith(prefix))
  345. li = i;
  346. if (ri < 0 && rightTip.startsWith(prefix))
  347. ri = i;
  348. }
  349. // Don't tiebreak if prefixes are the same, in order to prefer first-parent
  350. // paths.
  351. return li - ri;
  352. }
  353. private static String simplify(String refName) {
  354. if (refName.startsWith(Constants.R_HEADS))
  355. return refName.substring(Constants.R_HEADS.length());
  356. if (refName.startsWith(Constants.R_TAGS))
  357. return refName.substring(Constants.R_TAGS.length());
  358. if (refName.startsWith(Constants.R_REFS))
  359. return refName.substring(Constants.R_REFS.length());
  360. return refName;
  361. }
  362. }