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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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<ObjectId> revs;
  106. private List<Ref> refs;
  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. revs = new ArrayList<ObjectId>(2);
  118. walk = new RevWalk(repo) {
  119. @Override
  120. public NameRevCommit createCommit(AnyObjectId id) {
  121. return new NameRevCommit(id);
  122. }
  123. };
  124. }
  125. @Override
  126. public Map<ObjectId, String> call() throws GitAPIException {
  127. try {
  128. Map<ObjectId, String> nonCommits = new HashMap<ObjectId, String>();
  129. FIFORevQueue pending = new FIFORevQueue();
  130. if (refs != null) {
  131. for (Ref ref : refs)
  132. addRef(ref, nonCommits, pending);
  133. }
  134. addPrefixes(nonCommits, pending);
  135. int cutoff = minCommitTime() - COMMIT_TIME_SLOP;
  136. while (true) {
  137. NameRevCommit c = (NameRevCommit) pending.next();
  138. if (c == null)
  139. break;
  140. if (c.getCommitTime() < cutoff)
  141. continue;
  142. for (int i = 0; i < c.getParentCount(); i++) {
  143. NameRevCommit p = (NameRevCommit) walk.parseCommit(c.getParent(i));
  144. long cost = c.cost + (i > 0 ? mergeCost : 1);
  145. if (p.tip == null || compare(c.tip, cost, p.tip, p.cost) < 0) {
  146. if (i > 0) {
  147. p.tip = c.format().append('^').append(i + 1).toString();
  148. p.distance = 0;
  149. } else {
  150. p.tip = c.tip;
  151. p.distance = c.distance + 1;
  152. }
  153. p.cost = cost;
  154. pending.add(p);
  155. }
  156. }
  157. }
  158. Map<ObjectId, String> result =
  159. new LinkedHashMap<ObjectId, String>(revs.size());
  160. for (ObjectId id : revs) {
  161. RevObject o = walk.parseAny(id);
  162. if (o instanceof NameRevCommit) {
  163. NameRevCommit c = (NameRevCommit) o;
  164. if (c.tip != null)
  165. result.put(id, simplify(c.format().toString()));
  166. } else {
  167. String name = nonCommits.get(id);
  168. if (name != null)
  169. result.put(id, simplify(name));
  170. }
  171. }
  172. setCallable(false);
  173. walk.release();
  174. return result;
  175. } catch (IOException e) {
  176. walk.reset();
  177. throw new JGitInternalException(e.getMessage(), e);
  178. }
  179. }
  180. /**
  181. * Add an object to search for.
  182. *
  183. * @param id
  184. * object ID to add.
  185. * @return {@code this}
  186. * @throws MissingObjectException
  187. * the object supplied is not available from the object
  188. * database.
  189. * @throws JGitInternalException
  190. * a low-level exception of JGit has occurred. The original
  191. * exception can be retrieved by calling
  192. * {@link Exception#getCause()}.
  193. */
  194. public NameRevCommand add(ObjectId id) throws MissingObjectException,
  195. JGitInternalException {
  196. checkCallable();
  197. try {
  198. walk.parseAny(id);
  199. } catch (MissingObjectException e) {
  200. throw e;
  201. } catch (IOException e) {
  202. throw new JGitInternalException(e.getMessage(), e);
  203. }
  204. revs.add(id.copy());
  205. return this;
  206. }
  207. /**
  208. * Add multiple objects to search for.
  209. *
  210. * @param ids
  211. * object IDs to add.
  212. * @return {@code this}
  213. * @throws MissingObjectException
  214. * the object supplied is not available from the object
  215. * database.
  216. * @throws JGitInternalException
  217. * a low-level exception of JGit has occurred. The original
  218. * exception can be retrieved by calling
  219. * {@link Exception#getCause()}.
  220. */
  221. public NameRevCommand add(Iterable<ObjectId> ids)
  222. throws MissingObjectException, JGitInternalException {
  223. for (ObjectId id : ids)
  224. add(id);
  225. return this;
  226. }
  227. /**
  228. * Add a ref prefix to the set that results must match.
  229. * <p>
  230. * If an object matches multiple refs equally well, the first matching ref
  231. * added with {@link #addRef(Ref)} is preferred, or else the first matching
  232. * prefix added by {@link #addPrefix(String)}.
  233. *
  234. * @param prefix
  235. * prefix to add; see {@link RefDatabase#getRefs(String)}
  236. * @return {@code this}
  237. */
  238. public NameRevCommand addPrefix(String prefix) {
  239. checkCallable();
  240. prefixes.add(prefix);
  241. return this;
  242. }
  243. /**
  244. * Add all annotated tags under {@code refs/tags/} to the set that all results
  245. * must match.
  246. * <p>
  247. * Calls {@link #addRef(Ref)}; see that method for a note on matching
  248. * priority.
  249. *
  250. * @return {@code this}
  251. * @throws JGitInternalException
  252. * a low-level exception of JGit has occurred. The original
  253. * exception can be retrieved by calling
  254. * {@link Exception#getCause()}.
  255. */
  256. public NameRevCommand addAnnotatedTags() {
  257. checkCallable();
  258. if (refs == null)
  259. refs = new ArrayList<Ref>();
  260. try {
  261. for (Ref ref : repo.getRefDatabase().getRefs(Constants.R_TAGS).values()) {
  262. ObjectId id = ref.getObjectId();
  263. if (id != null && (walk.parseAny(id) instanceof RevTag))
  264. addRef(ref);
  265. }
  266. } catch (IOException e) {
  267. throw new JGitInternalException(e.getMessage(), e);
  268. }
  269. return this;
  270. }
  271. /**
  272. * Add a ref to the set that all results must match.
  273. * <p>
  274. * If an object matches multiple refs equally well, the first matching ref
  275. * added with {@link #addRef(Ref)} is preferred, or else the first matching
  276. * prefix added by {@link #addPrefix(String)}.
  277. *
  278. * @param ref
  279. * ref to add.
  280. * @return {@code this}
  281. */
  282. public NameRevCommand addRef(Ref ref) {
  283. checkCallable();
  284. if (refs == null)
  285. refs = new ArrayList<Ref>();
  286. refs.add(ref);
  287. return this;
  288. }
  289. NameRevCommand setMergeCost(int cost) {
  290. mergeCost = cost;
  291. return this;
  292. }
  293. private void addPrefixes(Map<ObjectId, String> nonCommits,
  294. FIFORevQueue pending) throws IOException {
  295. if (!prefixes.isEmpty()) {
  296. for (String prefix : prefixes)
  297. addPrefix(prefix, nonCommits, pending);
  298. } else if (refs == null)
  299. addPrefix(Constants.R_REFS, nonCommits, pending);
  300. }
  301. private void addPrefix(String prefix, Map<ObjectId, String> nonCommits,
  302. FIFORevQueue pending) throws IOException {
  303. for (Ref ref : repo.getRefDatabase().getRefs(prefix).values())
  304. addRef(ref, nonCommits, pending);
  305. }
  306. private void addRef(Ref ref, Map<ObjectId, String> nonCommits,
  307. FIFORevQueue pending) throws IOException {
  308. if (ref.getObjectId() == null)
  309. return;
  310. RevObject o = walk.parseAny(ref.getObjectId());
  311. while (o instanceof RevTag) {
  312. RevTag t = (RevTag) o;
  313. nonCommits.put(o, ref.getName());
  314. o = t.getObject();
  315. walk.parseHeaders(o);
  316. }
  317. if (o instanceof NameRevCommit) {
  318. NameRevCommit c = (NameRevCommit) o;
  319. if (c.tip == null)
  320. c.tip = ref.getName();
  321. pending.add(c);
  322. } else if (!nonCommits.containsKey(o))
  323. nonCommits.put(o, ref.getName());
  324. }
  325. private int minCommitTime() throws IOException {
  326. int min = Integer.MAX_VALUE;
  327. for (ObjectId id : revs) {
  328. RevObject o = walk.parseAny(id);
  329. while (o instanceof RevTag) {
  330. o = ((RevTag) o).getObject();
  331. walk.parseHeaders(o);
  332. }
  333. if (o instanceof RevCommit) {
  334. RevCommit c = (RevCommit) o;
  335. if (c.getCommitTime() < min)
  336. min = c.getCommitTime();
  337. }
  338. }
  339. return min;
  340. }
  341. private long compare(String leftTip, long leftCost, String rightTip, long rightCost) {
  342. long c = leftCost - rightCost;
  343. if (c != 0 || prefixes.isEmpty())
  344. return c;
  345. int li = -1;
  346. int ri = -1;
  347. for (int i = 0; i < prefixes.size(); i++) {
  348. String prefix = prefixes.get(i);
  349. if (li < 0 && leftTip.startsWith(prefix))
  350. li = i;
  351. if (ri < 0 && rightTip.startsWith(prefix))
  352. ri = i;
  353. }
  354. // Don't tiebreak if prefixes are the same, in order to prefer first-parent
  355. // paths.
  356. return li - ri;
  357. }
  358. private static String simplify(String refName) {
  359. if (refName.startsWith(Constants.R_HEADS))
  360. return refName.substring(Constants.R_HEADS.length());
  361. if (refName.startsWith(Constants.R_TAGS))
  362. return refName.substring(Constants.R_TAGS.length());
  363. if (refName.startsWith(Constants.R_REFS))
  364. return refName.substring(Constants.R_REFS.length());
  365. return refName;
  366. }
  367. }