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.

RevWalk.java 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. /*
  2. * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com>
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.revwalk;
  45. import java.io.IOException;
  46. import java.util.ArrayList;
  47. import java.util.Collection;
  48. import java.util.EnumSet;
  49. import java.util.Iterator;
  50. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  51. import org.eclipse.jgit.errors.MissingObjectException;
  52. import org.eclipse.jgit.errors.RevWalkException;
  53. import org.eclipse.jgit.lib.AnyObjectId;
  54. import org.eclipse.jgit.lib.Constants;
  55. import org.eclipse.jgit.lib.MutableObjectId;
  56. import org.eclipse.jgit.lib.ObjectId;
  57. import org.eclipse.jgit.lib.ObjectIdSubclassMap;
  58. import org.eclipse.jgit.lib.ObjectLoader;
  59. import org.eclipse.jgit.lib.Repository;
  60. import org.eclipse.jgit.lib.WindowCursor;
  61. import org.eclipse.jgit.revwalk.filter.RevFilter;
  62. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  63. /**
  64. * Walks a commit graph and produces the matching commits in order.
  65. * <p>
  66. * A RevWalk instance can only be used once to generate results. Running a
  67. * second time requires creating a new RevWalk instance, or invoking
  68. * {@link #reset()} before starting again. Resetting an existing instance may be
  69. * faster for some applications as commit body parsing can be avoided on the
  70. * later invocations.
  71. * <p>
  72. * RevWalk instances are not thread-safe. Applications must either restrict
  73. * usage of a RevWalk instance to a single thread, or implement their own
  74. * synchronization at a higher level.
  75. * <p>
  76. * Multiple simultaneous RevWalk instances per {@link Repository} are permitted,
  77. * even from concurrent threads. Equality of {@link RevCommit}s from two
  78. * different RevWalk instances is never true, even if their {@link ObjectId}s
  79. * are equal (and thus they describe the same commit).
  80. * <p>
  81. * The offered iterator is over the list of RevCommits described by the
  82. * configuration of this instance. Applications should restrict themselves to
  83. * using either the provided Iterator or {@link #next()}, but never use both on
  84. * the same RevWalk at the same time. The Iterator may buffer RevCommits, while
  85. * {@link #next()} does not.
  86. */
  87. public class RevWalk implements Iterable<RevCommit> {
  88. /**
  89. * Set on objects whose important header data has been loaded.
  90. * <p>
  91. * For a RevCommit this indicates we have pulled apart the tree and parent
  92. * references from the raw bytes available in the repository and translated
  93. * those to our own local RevTree and RevCommit instances. The raw buffer is
  94. * also available for message and other header filtering.
  95. * <p>
  96. * For a RevTag this indicates we have pulled part the tag references to
  97. * find out who the tag refers to, and what that object's type is.
  98. */
  99. static final int PARSED = 1 << 0;
  100. /**
  101. * Set on RevCommit instances added to our {@link #pending} queue.
  102. * <p>
  103. * We use this flag to avoid adding the same commit instance twice to our
  104. * queue, especially if we reached it by more than one path.
  105. */
  106. static final int SEEN = 1 << 1;
  107. /**
  108. * Set on RevCommit instances the caller does not want output.
  109. * <p>
  110. * We flag commits as uninteresting if the caller does not want commits
  111. * reachable from a commit given to {@link #markUninteresting(RevCommit)}.
  112. * This flag is always carried into the commit's parents and is a key part
  113. * of the "rev-list B --not A" feature; A is marked UNINTERESTING.
  114. */
  115. static final int UNINTERESTING = 1 << 2;
  116. /**
  117. * Set on a RevCommit that can collapse out of the history.
  118. * <p>
  119. * If the {@link #treeFilter} concluded that this commit matches his
  120. * parents' for all of the paths that the filter is interested in then we
  121. * mark the commit REWRITE. Later we can rewrite the parents of a REWRITE
  122. * child to remove chains of REWRITE commits before we produce the child to
  123. * the application.
  124. *
  125. * @see RewriteGenerator
  126. */
  127. static final int REWRITE = 1 << 3;
  128. /**
  129. * Temporary mark for use within generators or filters.
  130. * <p>
  131. * This mark is only for local use within a single scope. If someone sets
  132. * the mark they must unset it before any other code can see the mark.
  133. */
  134. static final int TEMP_MARK = 1 << 4;
  135. /**
  136. * Temporary mark for use within {@link TopoSortGenerator}.
  137. * <p>
  138. * This mark indicates the commit could not produce when it wanted to, as at
  139. * least one child was behind it. Commits with this flag are delayed until
  140. * all children have been output first.
  141. */
  142. static final int TOPO_DELAY = 1 << 5;
  143. /** Number of flag bits we keep internal for our own use. See above flags. */
  144. static final int RESERVED_FLAGS = 6;
  145. private static final int APP_FLAGS = -1 & ~((1 << RESERVED_FLAGS) - 1);
  146. final Repository db;
  147. final WindowCursor curs;
  148. final MutableObjectId idBuffer;
  149. private final ObjectIdSubclassMap<RevObject> objects;
  150. private int freeFlags = APP_FLAGS;
  151. private int delayFreeFlags;
  152. int carryFlags = UNINTERESTING;
  153. private final ArrayList<RevCommit> roots;
  154. AbstractRevQueue queue;
  155. Generator pending;
  156. private final EnumSet<RevSort> sorting;
  157. private RevFilter filter;
  158. private TreeFilter treeFilter;
  159. private boolean retainBody;
  160. /**
  161. * Create a new revision walker for a given repository.
  162. *
  163. * @param repo
  164. * the repository the walker will obtain data from.
  165. */
  166. public RevWalk(final Repository repo) {
  167. db = repo;
  168. curs = new WindowCursor();
  169. idBuffer = new MutableObjectId();
  170. objects = new ObjectIdSubclassMap<RevObject>();
  171. roots = new ArrayList<RevCommit>();
  172. queue = new DateRevQueue();
  173. pending = new StartGenerator(this);
  174. sorting = EnumSet.of(RevSort.NONE);
  175. filter = RevFilter.ALL;
  176. treeFilter = TreeFilter.ALL;
  177. retainBody = true;
  178. }
  179. /**
  180. * Get the repository this walker loads objects from.
  181. *
  182. * @return the repository this walker was created to read.
  183. */
  184. public Repository getRepository() {
  185. return db;
  186. }
  187. /**
  188. * Mark a commit to start graph traversal from.
  189. * <p>
  190. * Callers are encouraged to use {@link #parseCommit(AnyObjectId)} to obtain
  191. * the commit reference, rather than {@link #lookupCommit(AnyObjectId)}, as
  192. * this method requires the commit to be parsed before it can be added as a
  193. * root for the traversal.
  194. * <p>
  195. * The method will automatically parse an unparsed commit, but error
  196. * handling may be more difficult for the application to explain why a
  197. * RevCommit is not actually a commit. The object pool of this walker would
  198. * also be 'poisoned' by the non-commit RevCommit.
  199. *
  200. * @param c
  201. * the commit to start traversing from. The commit passed must be
  202. * from this same revision walker.
  203. * @throws MissingObjectException
  204. * the commit supplied is not available from the object
  205. * database. This usually indicates the supplied commit is
  206. * invalid, but the reference was constructed during an earlier
  207. * invocation to {@link #lookupCommit(AnyObjectId)}.
  208. * @throws IncorrectObjectTypeException
  209. * the object was not parsed yet and it was discovered during
  210. * parsing that it is not actually a commit. This usually
  211. * indicates the caller supplied a non-commit SHA-1 to
  212. * {@link #lookupCommit(AnyObjectId)}.
  213. * @throws IOException
  214. * a pack file or loose object could not be read.
  215. */
  216. public void markStart(final RevCommit c) throws MissingObjectException,
  217. IncorrectObjectTypeException, IOException {
  218. if ((c.flags & SEEN) != 0)
  219. return;
  220. if ((c.flags & PARSED) == 0)
  221. c.parseHeaders(this);
  222. c.flags |= SEEN;
  223. roots.add(c);
  224. queue.add(c);
  225. }
  226. /**
  227. * Mark commits to start graph traversal from.
  228. *
  229. * @param list
  230. * commits to start traversing from. The commits passed must be
  231. * from this same revision walker.
  232. * @throws MissingObjectException
  233. * one of the commits supplied is not available from the object
  234. * database. This usually indicates the supplied commit is
  235. * invalid, but the reference was constructed during an earlier
  236. * invocation to {@link #lookupCommit(AnyObjectId)}.
  237. * @throws IncorrectObjectTypeException
  238. * the object was not parsed yet and it was discovered during
  239. * parsing that it is not actually a commit. This usually
  240. * indicates the caller supplied a non-commit SHA-1 to
  241. * {@link #lookupCommit(AnyObjectId)}.
  242. * @throws IOException
  243. * a pack file or loose object could not be read.
  244. */
  245. public void markStart(final Collection<RevCommit> list)
  246. throws MissingObjectException, IncorrectObjectTypeException,
  247. IOException {
  248. for (final RevCommit c : list)
  249. markStart(c);
  250. }
  251. /**
  252. * Mark a commit to not produce in the output.
  253. * <p>
  254. * Uninteresting commits denote not just themselves but also their entire
  255. * ancestry chain, back until the merge base of an uninteresting commit and
  256. * an otherwise interesting commit.
  257. * <p>
  258. * Callers are encouraged to use {@link #parseCommit(AnyObjectId)} to obtain
  259. * the commit reference, rather than {@link #lookupCommit(AnyObjectId)}, as
  260. * this method requires the commit to be parsed before it can be added as a
  261. * root for the traversal.
  262. * <p>
  263. * The method will automatically parse an unparsed commit, but error
  264. * handling may be more difficult for the application to explain why a
  265. * RevCommit is not actually a commit. The object pool of this walker would
  266. * also be 'poisoned' by the non-commit RevCommit.
  267. *
  268. * @param c
  269. * the commit to start traversing from. The commit passed must be
  270. * from this same revision walker.
  271. * @throws MissingObjectException
  272. * the commit supplied is not available from the object
  273. * database. This usually indicates the supplied commit is
  274. * invalid, but the reference was constructed during an earlier
  275. * invocation to {@link #lookupCommit(AnyObjectId)}.
  276. * @throws IncorrectObjectTypeException
  277. * the object was not parsed yet and it was discovered during
  278. * parsing that it is not actually a commit. This usually
  279. * indicates the caller supplied a non-commit SHA-1 to
  280. * {@link #lookupCommit(AnyObjectId)}.
  281. * @throws IOException
  282. * a pack file or loose object could not be read.
  283. */
  284. public void markUninteresting(final RevCommit c)
  285. throws MissingObjectException, IncorrectObjectTypeException,
  286. IOException {
  287. c.flags |= UNINTERESTING;
  288. carryFlagsImpl(c);
  289. markStart(c);
  290. }
  291. /**
  292. * Determine if a commit is reachable from another commit.
  293. * <p>
  294. * A commit <code>base</code> is an ancestor of <code>tip</code> if we
  295. * can find a path of commits that leads from <code>tip</code> and ends at
  296. * <code>base</code>.
  297. * <p>
  298. * This utility function resets the walker, inserts the two supplied
  299. * commits, and then executes a walk until an answer can be obtained.
  300. * Currently allocated RevFlags that have been added to RevCommit instances
  301. * will be retained through the reset.
  302. *
  303. * @param base
  304. * commit the caller thinks is reachable from <code>tip</code>.
  305. * @param tip
  306. * commit to start iteration from, and which is most likely a
  307. * descendant (child) of <code>base</code>.
  308. * @return true if there is a path directly from <code>tip</code> to
  309. * <code>base</code> (and thus <code>base</code> is fully merged
  310. * into <code>tip</code>); false otherwise.
  311. * @throws MissingObjectException
  312. * one or or more of the next commit's parents are not available
  313. * from the object database, but were thought to be candidates
  314. * for traversal. This usually indicates a broken link.
  315. * @throws IncorrectObjectTypeException
  316. * one or or more of the next commit's parents are not actually
  317. * commit objects.
  318. * @throws IOException
  319. * a pack file or loose object could not be read.
  320. */
  321. public boolean isMergedInto(final RevCommit base, final RevCommit tip)
  322. throws MissingObjectException, IncorrectObjectTypeException,
  323. IOException {
  324. final RevFilter oldRF = filter;
  325. final TreeFilter oldTF = treeFilter;
  326. try {
  327. finishDelayedFreeFlags();
  328. reset(~freeFlags & APP_FLAGS);
  329. filter = RevFilter.MERGE_BASE;
  330. treeFilter = TreeFilter.ALL;
  331. markStart(tip);
  332. markStart(base);
  333. return next() == base;
  334. } finally {
  335. filter = oldRF;
  336. treeFilter = oldTF;
  337. }
  338. }
  339. /**
  340. * Pop the next most recent commit.
  341. *
  342. * @return next most recent commit; null if traversal is over.
  343. * @throws MissingObjectException
  344. * one or or more of the next commit's parents are not available
  345. * from the object database, but were thought to be candidates
  346. * for traversal. This usually indicates a broken link.
  347. * @throws IncorrectObjectTypeException
  348. * one or or more of the next commit's parents are not actually
  349. * commit objects.
  350. * @throws IOException
  351. * a pack file or loose object could not be read.
  352. */
  353. public RevCommit next() throws MissingObjectException,
  354. IncorrectObjectTypeException, IOException {
  355. return pending.next();
  356. }
  357. /**
  358. * Obtain the sort types applied to the commits returned.
  359. *
  360. * @return the sorting strategies employed. At least one strategy is always
  361. * used, but that strategy may be {@link RevSort#NONE}.
  362. */
  363. public EnumSet<RevSort> getRevSort() {
  364. return sorting.clone();
  365. }
  366. /**
  367. * Check whether the provided sorting strategy is enabled.
  368. *
  369. * @param sort
  370. * a sorting strategy to look for.
  371. * @return true if this strategy is enabled, false otherwise
  372. */
  373. public boolean hasRevSort(RevSort sort) {
  374. return sorting.contains(sort);
  375. }
  376. /**
  377. * Select a single sorting strategy for the returned commits.
  378. * <p>
  379. * Disables all sorting strategies, then enables only the single strategy
  380. * supplied by the caller.
  381. *
  382. * @param s
  383. * a sorting strategy to enable.
  384. */
  385. public void sort(final RevSort s) {
  386. assertNotStarted();
  387. sorting.clear();
  388. sorting.add(s);
  389. }
  390. /**
  391. * Add or remove a sorting strategy for the returned commits.
  392. * <p>
  393. * Multiple strategies can be applied at once, in which case some strategies
  394. * may take precedence over others. As an example, {@link RevSort#TOPO} must
  395. * take precedence over {@link RevSort#COMMIT_TIME_DESC}, otherwise it
  396. * cannot enforce its ordering.
  397. *
  398. * @param s
  399. * a sorting strategy to enable or disable.
  400. * @param use
  401. * true if this strategy should be used, false if it should be
  402. * removed.
  403. */
  404. public void sort(final RevSort s, final boolean use) {
  405. assertNotStarted();
  406. if (use)
  407. sorting.add(s);
  408. else
  409. sorting.remove(s);
  410. if (sorting.size() > 1)
  411. sorting.remove(RevSort.NONE);
  412. else if (sorting.size() == 0)
  413. sorting.add(RevSort.NONE);
  414. }
  415. /**
  416. * Get the currently configured commit filter.
  417. *
  418. * @return the current filter. Never null as a filter is always needed.
  419. */
  420. public RevFilter getRevFilter() {
  421. return filter;
  422. }
  423. /**
  424. * Set the commit filter for this walker.
  425. * <p>
  426. * Multiple filters may be combined by constructing an arbitrary tree of
  427. * <code>AndRevFilter</code> or <code>OrRevFilter</code> instances to
  428. * describe the boolean expression required by the application. Custom
  429. * filter implementations may also be constructed by applications.
  430. * <p>
  431. * Note that filters are not thread-safe and may not be shared by concurrent
  432. * RevWalk instances. Every RevWalk must be supplied its own unique filter,
  433. * unless the filter implementation specifically states it is (and always
  434. * will be) thread-safe. Callers may use {@link RevFilter#clone()} to create
  435. * a unique filter tree for this RevWalk instance.
  436. *
  437. * @param newFilter
  438. * the new filter. If null the special {@link RevFilter#ALL}
  439. * filter will be used instead, as it matches every commit.
  440. * @see org.eclipse.jgit.revwalk.filter.AndRevFilter
  441. * @see org.eclipse.jgit.revwalk.filter.OrRevFilter
  442. */
  443. public void setRevFilter(final RevFilter newFilter) {
  444. assertNotStarted();
  445. filter = newFilter != null ? newFilter : RevFilter.ALL;
  446. }
  447. /**
  448. * Get the tree filter used to simplify commits by modified paths.
  449. *
  450. * @return the current filter. Never null as a filter is always needed. If
  451. * no filter is being applied {@link TreeFilter#ALL} is returned.
  452. */
  453. public TreeFilter getTreeFilter() {
  454. return treeFilter;
  455. }
  456. /**
  457. * Set the tree filter used to simplify commits by modified paths.
  458. * <p>
  459. * If null or {@link TreeFilter#ALL} the path limiter is removed. Commits
  460. * will not be simplified.
  461. * <p>
  462. * If non-null and not {@link TreeFilter#ALL} then the tree filter will be
  463. * installed and commits will have their ancestry simplified to hide commits
  464. * that do not contain tree entries matched by the filter.
  465. * <p>
  466. * Usually callers should be inserting a filter graph including
  467. * {@link TreeFilter#ANY_DIFF} along with one or more
  468. * {@link org.eclipse.jgit.treewalk.filter.PathFilter} instances.
  469. *
  470. * @param newFilter
  471. * new filter. If null the special {@link TreeFilter#ALL} filter
  472. * will be used instead, as it matches everything.
  473. * @see org.eclipse.jgit.treewalk.filter.PathFilter
  474. */
  475. public void setTreeFilter(final TreeFilter newFilter) {
  476. assertNotStarted();
  477. treeFilter = newFilter != null ? newFilter : TreeFilter.ALL;
  478. }
  479. /**
  480. * Should the body of a commit or tag be retained after parsing its headers?
  481. * <p>
  482. * Usually the body is always retained, but some application code might not
  483. * care and would prefer to discard the body of a commit as early as
  484. * possible, to reduce memory usage.
  485. *
  486. * @return true if the body should be retained; false it is discarded.
  487. */
  488. public boolean isRetainBody() {
  489. return retainBody;
  490. }
  491. /**
  492. * Set whether or not the body of a commit or tag is retained.
  493. * <p>
  494. * If a body of a commit or tag is not retained, the application must
  495. * call {@link #parseBody(RevObject)} before the body can be safely
  496. * accessed through the type specific access methods.
  497. *
  498. * @param retain true to retain bodies; false to discard them early.
  499. */
  500. public void setRetainBody(final boolean retain) {
  501. retainBody = retain;
  502. }
  503. /**
  504. * Locate a reference to a blob without loading it.
  505. * <p>
  506. * The blob may or may not exist in the repository. It is impossible to tell
  507. * from this method's return value.
  508. *
  509. * @param id
  510. * name of the blob object.
  511. * @return reference to the blob object. Never null.
  512. */
  513. public RevBlob lookupBlob(final AnyObjectId id) {
  514. RevBlob c = (RevBlob) objects.get(id);
  515. if (c == null) {
  516. c = new RevBlob(id);
  517. objects.add(c);
  518. }
  519. return c;
  520. }
  521. /**
  522. * Locate a reference to a tree without loading it.
  523. * <p>
  524. * The tree may or may not exist in the repository. It is impossible to tell
  525. * from this method's return value.
  526. *
  527. * @param id
  528. * name of the tree object.
  529. * @return reference to the tree object. Never null.
  530. */
  531. public RevTree lookupTree(final AnyObjectId id) {
  532. RevTree c = (RevTree) objects.get(id);
  533. if (c == null) {
  534. c = new RevTree(id);
  535. objects.add(c);
  536. }
  537. return c;
  538. }
  539. /**
  540. * Locate a reference to a commit without loading it.
  541. * <p>
  542. * The commit may or may not exist in the repository. It is impossible to
  543. * tell from this method's return value.
  544. *
  545. * @param id
  546. * name of the commit object.
  547. * @return reference to the commit object. Never null.
  548. */
  549. public RevCommit lookupCommit(final AnyObjectId id) {
  550. RevCommit c = (RevCommit) objects.get(id);
  551. if (c == null) {
  552. c = createCommit(id);
  553. objects.add(c);
  554. }
  555. return c;
  556. }
  557. /**
  558. * Locate a reference to any object without loading it.
  559. * <p>
  560. * The object may or may not exist in the repository. It is impossible to
  561. * tell from this method's return value.
  562. *
  563. * @param id
  564. * name of the object.
  565. * @param type
  566. * type of the object. Must be a valid Git object type.
  567. * @return reference to the object. Never null.
  568. */
  569. public RevObject lookupAny(final AnyObjectId id, final int type) {
  570. RevObject r = objects.get(id);
  571. if (r == null) {
  572. switch (type) {
  573. case Constants.OBJ_COMMIT:
  574. r = createCommit(id);
  575. break;
  576. case Constants.OBJ_TREE:
  577. r = new RevTree(id);
  578. break;
  579. case Constants.OBJ_BLOB:
  580. r = new RevBlob(id);
  581. break;
  582. case Constants.OBJ_TAG:
  583. r = new RevTag(id);
  584. break;
  585. default:
  586. throw new IllegalArgumentException("invalid git type: " + type);
  587. }
  588. objects.add(r);
  589. }
  590. return r;
  591. }
  592. /**
  593. * Locate a reference to a commit and immediately parse its content.
  594. * <p>
  595. * Unlike {@link #lookupCommit(AnyObjectId)} this method only returns
  596. * successfully if the commit object exists, is verified to be a commit, and
  597. * was parsed without error.
  598. *
  599. * @param id
  600. * name of the commit object.
  601. * @return reference to the commit object. Never null.
  602. * @throws MissingObjectException
  603. * the supplied commit does not exist.
  604. * @throws IncorrectObjectTypeException
  605. * the supplied id is not a commit or an annotated tag.
  606. * @throws IOException
  607. * a pack file or loose object could not be read.
  608. */
  609. public RevCommit parseCommit(final AnyObjectId id)
  610. throws MissingObjectException, IncorrectObjectTypeException,
  611. IOException {
  612. RevObject c = parseAny(id);
  613. while (c instanceof RevTag) {
  614. c = ((RevTag) c).getObject();
  615. parseHeaders(c);
  616. }
  617. if (!(c instanceof RevCommit))
  618. throw new IncorrectObjectTypeException(id.toObjectId(),
  619. Constants.TYPE_COMMIT);
  620. return (RevCommit) c;
  621. }
  622. /**
  623. * Locate a reference to a tree.
  624. * <p>
  625. * This method only returns successfully if the tree object exists, is
  626. * verified to be a tree.
  627. *
  628. * @param id
  629. * name of the tree object, or a commit or annotated tag that may
  630. * reference a tree.
  631. * @return reference to the tree object. Never null.
  632. * @throws MissingObjectException
  633. * the supplied tree does not exist.
  634. * @throws IncorrectObjectTypeException
  635. * the supplied id is not a tree, a commit or an annotated tag.
  636. * @throws IOException
  637. * a pack file or loose object could not be read.
  638. */
  639. public RevTree parseTree(final AnyObjectId id)
  640. throws MissingObjectException, IncorrectObjectTypeException,
  641. IOException {
  642. RevObject c = parseAny(id);
  643. while (c instanceof RevTag) {
  644. c = ((RevTag) c).getObject();
  645. parseHeaders(c);
  646. }
  647. final RevTree t;
  648. if (c instanceof RevCommit)
  649. t = ((RevCommit) c).getTree();
  650. else if (!(c instanceof RevTree))
  651. throw new IncorrectObjectTypeException(id.toObjectId(),
  652. Constants.TYPE_TREE);
  653. else
  654. t = (RevTree) c;
  655. parseHeaders(t);
  656. return t;
  657. }
  658. /**
  659. * Locate a reference to any object and immediately parse its headers.
  660. * <p>
  661. * This method only returns successfully if the object exists and was parsed
  662. * without error. Parsing an object can be expensive as the type must be
  663. * determined. For blobs this may mean the blob content was unpacked
  664. * unnecessarily, and thrown away.
  665. *
  666. * @param id
  667. * name of the object.
  668. * @return reference to the object. Never null.
  669. * @throws MissingObjectException
  670. * the supplied does not exist.
  671. * @throws IOException
  672. * a pack file or loose object could not be read.
  673. */
  674. public RevObject parseAny(final AnyObjectId id)
  675. throws MissingObjectException, IOException {
  676. RevObject r = objects.get(id);
  677. if (r == null) {
  678. final ObjectLoader ldr = db.openObject(curs, id);
  679. if (ldr == null)
  680. throw new MissingObjectException(id.toObjectId(), "unknown");
  681. final byte[] data = ldr.getCachedBytes();
  682. final int type = ldr.getType();
  683. switch (type) {
  684. case Constants.OBJ_COMMIT: {
  685. final RevCommit c = createCommit(id);
  686. c.parseCanonical(this, data);
  687. r = c;
  688. break;
  689. }
  690. case Constants.OBJ_TREE: {
  691. r = new RevTree(id);
  692. r.flags |= PARSED;
  693. break;
  694. }
  695. case Constants.OBJ_BLOB: {
  696. r = new RevBlob(id);
  697. r.flags |= PARSED;
  698. break;
  699. }
  700. case Constants.OBJ_TAG: {
  701. final RevTag t = new RevTag(id);
  702. t.parseCanonical(this, data);
  703. r = t;
  704. break;
  705. }
  706. default:
  707. throw new IllegalArgumentException("Bad object type: " + type);
  708. }
  709. objects.add(r);
  710. } else
  711. parseHeaders(r);
  712. return r;
  713. }
  714. /**
  715. * Ensure the object's critical headers have been parsed.
  716. * <p>
  717. * This method only returns successfully if the object exists and was parsed
  718. * without error.
  719. *
  720. * @param obj
  721. * the object the caller needs to be parsed.
  722. * @throws MissingObjectException
  723. * the supplied does not exist.
  724. * @throws IOException
  725. * a pack file or loose object could not be read.
  726. */
  727. public void parseHeaders(final RevObject obj)
  728. throws MissingObjectException, IOException {
  729. if ((obj.flags & PARSED) == 0)
  730. obj.parseHeaders(this);
  731. }
  732. /**
  733. * Ensure the object's fully body content is available.
  734. * <p>
  735. * This method only returns successfully if the object exists and was parsed
  736. * without error.
  737. *
  738. * @param obj
  739. * the object the caller needs to be parsed.
  740. * @throws MissingObjectException
  741. * the supplied does not exist.
  742. * @throws IOException
  743. * a pack file or loose object could not be read.
  744. */
  745. public void parseBody(final RevObject obj)
  746. throws MissingObjectException, IOException {
  747. obj.parseBody(this);
  748. }
  749. /**
  750. * Create a new flag for application use during walking.
  751. * <p>
  752. * Applications are only assured to be able to create 24 unique flags on any
  753. * given revision walker instance. Any flags beyond 24 are offered only if
  754. * the implementation has extra free space within its internal storage.
  755. *
  756. * @param name
  757. * description of the flag, primarily useful for debugging.
  758. * @return newly constructed flag instance.
  759. * @throws IllegalArgumentException
  760. * too many flags have been reserved on this revision walker.
  761. */
  762. public RevFlag newFlag(final String name) {
  763. final int m = allocFlag();
  764. return new RevFlag(this, name, m);
  765. }
  766. int allocFlag() {
  767. if (freeFlags == 0)
  768. throw new IllegalArgumentException(32 - RESERVED_FLAGS
  769. + " flags already created.");
  770. final int m = Integer.lowestOneBit(freeFlags);
  771. freeFlags &= ~m;
  772. return m;
  773. }
  774. /**
  775. * Automatically carry a flag from a child commit to its parents.
  776. * <p>
  777. * A carried flag is copied from the child commit onto its parents when the
  778. * child commit is popped from the lowest level of walk's internal graph.
  779. *
  780. * @param flag
  781. * the flag to carry onto parents, if set on a descendant.
  782. */
  783. public void carry(final RevFlag flag) {
  784. if ((freeFlags & flag.mask) != 0)
  785. throw new IllegalArgumentException(flag.name + " is disposed.");
  786. if (flag.walker != this)
  787. throw new IllegalArgumentException(flag.name + " not from this.");
  788. carryFlags |= flag.mask;
  789. }
  790. /**
  791. * Automatically carry flags from a child commit to its parents.
  792. * <p>
  793. * A carried flag is copied from the child commit onto its parents when the
  794. * child commit is popped from the lowest level of walk's internal graph.
  795. *
  796. * @param set
  797. * the flags to carry onto parents, if set on a descendant.
  798. */
  799. public void carry(final Collection<RevFlag> set) {
  800. for (final RevFlag flag : set)
  801. carry(flag);
  802. }
  803. /**
  804. * Allow a flag to be recycled for a different use.
  805. * <p>
  806. * Recycled flags always come back as a different Java object instance when
  807. * assigned again by {@link #newFlag(String)}.
  808. * <p>
  809. * If the flag was previously being carried, the carrying request is
  810. * removed. Disposing of a carried flag while a traversal is in progress has
  811. * an undefined behavior.
  812. *
  813. * @param flag
  814. * the to recycle.
  815. */
  816. public void disposeFlag(final RevFlag flag) {
  817. freeFlag(flag.mask);
  818. }
  819. void freeFlag(final int mask) {
  820. if (isNotStarted()) {
  821. freeFlags |= mask;
  822. carryFlags &= ~mask;
  823. } else {
  824. delayFreeFlags |= mask;
  825. }
  826. }
  827. private void finishDelayedFreeFlags() {
  828. if (delayFreeFlags != 0) {
  829. freeFlags |= delayFreeFlags;
  830. carryFlags &= ~delayFreeFlags;
  831. delayFreeFlags = 0;
  832. }
  833. }
  834. /**
  835. * Resets internal state and allows this instance to be used again.
  836. * <p>
  837. * Unlike {@link #dispose()} previously acquired RevObject (and RevCommit)
  838. * instances are not invalidated. RevFlag instances are not invalidated, but
  839. * are removed from all RevObjects.
  840. */
  841. public final void reset() {
  842. reset(0);
  843. }
  844. /**
  845. * Resets internal state and allows this instance to be used again.
  846. * <p>
  847. * Unlike {@link #dispose()} previously acquired RevObject (and RevCommit)
  848. * instances are not invalidated. RevFlag instances are not invalidated, but
  849. * are removed from all RevObjects.
  850. *
  851. * @param retainFlags
  852. * application flags that should <b>not</b> be cleared from
  853. * existing commit objects.
  854. */
  855. public final void resetRetain(final RevFlagSet retainFlags) {
  856. reset(retainFlags.mask);
  857. }
  858. /**
  859. * Resets internal state and allows this instance to be used again.
  860. * <p>
  861. * Unlike {@link #dispose()} previously acquired RevObject (and RevCommit)
  862. * instances are not invalidated. RevFlag instances are not invalidated, but
  863. * are removed from all RevObjects.
  864. *
  865. * @param retainFlags
  866. * application flags that should <b>not</b> be cleared from
  867. * existing commit objects.
  868. */
  869. public final void resetRetain(final RevFlag... retainFlags) {
  870. int mask = 0;
  871. for (final RevFlag flag : retainFlags)
  872. mask |= flag.mask;
  873. reset(mask);
  874. }
  875. /**
  876. * Resets internal state and allows this instance to be used again.
  877. * <p>
  878. * Unlike {@link #dispose()} previously acquired RevObject (and RevCommit)
  879. * instances are not invalidated. RevFlag instances are not invalidated, but
  880. * are removed from all RevObjects.
  881. *
  882. * @param retainFlags
  883. * application flags that should <b>not</b> be cleared from
  884. * existing commit objects.
  885. */
  886. protected void reset(int retainFlags) {
  887. finishDelayedFreeFlags();
  888. retainFlags |= PARSED;
  889. final int clearFlags = ~retainFlags;
  890. final FIFORevQueue q = new FIFORevQueue();
  891. for (final RevCommit c : roots) {
  892. if ((c.flags & clearFlags) == 0)
  893. continue;
  894. c.flags &= retainFlags;
  895. c.reset();
  896. q.add(c);
  897. }
  898. for (;;) {
  899. final RevCommit c = q.next();
  900. if (c == null)
  901. break;
  902. if (c.parents == null)
  903. continue;
  904. for (final RevCommit p : c.parents) {
  905. if ((p.flags & clearFlags) == 0)
  906. continue;
  907. p.flags &= retainFlags;
  908. p.reset();
  909. q.add(p);
  910. }
  911. }
  912. curs.release();
  913. roots.clear();
  914. queue = new DateRevQueue();
  915. pending = new StartGenerator(this);
  916. }
  917. /**
  918. * Dispose all internal state and invalidate all RevObject instances.
  919. * <p>
  920. * All RevObject (and thus RevCommit, etc.) instances previously acquired
  921. * from this RevWalk are invalidated by a dispose call. Applications must
  922. * not retain or use RevObject instances obtained prior to the dispose call.
  923. * All RevFlag instances are also invalidated, and must not be reused.
  924. */
  925. public void dispose() {
  926. freeFlags = APP_FLAGS;
  927. delayFreeFlags = 0;
  928. carryFlags = UNINTERESTING;
  929. objects.clear();
  930. curs.release();
  931. roots.clear();
  932. queue = new DateRevQueue();
  933. pending = new StartGenerator(this);
  934. }
  935. /**
  936. * Returns an Iterator over the commits of this walker.
  937. * <p>
  938. * The returned iterator is only useful for one walk. If this RevWalk gets
  939. * reset a new iterator must be obtained to walk over the new results.
  940. * <p>
  941. * Applications must not use both the Iterator and the {@link #next()} API
  942. * at the same time. Pick one API and use that for the entire walk.
  943. * <p>
  944. * If a checked exception is thrown during the walk (see {@link #next()})
  945. * it is rethrown from the Iterator as a {@link RevWalkException}.
  946. *
  947. * @return an iterator over this walker's commits.
  948. * @see RevWalkException
  949. */
  950. public Iterator<RevCommit> iterator() {
  951. final RevCommit first;
  952. try {
  953. first = RevWalk.this.next();
  954. } catch (MissingObjectException e) {
  955. throw new RevWalkException(e);
  956. } catch (IncorrectObjectTypeException e) {
  957. throw new RevWalkException(e);
  958. } catch (IOException e) {
  959. throw new RevWalkException(e);
  960. }
  961. return new Iterator<RevCommit>() {
  962. RevCommit next = first;
  963. public boolean hasNext() {
  964. return next != null;
  965. }
  966. public RevCommit next() {
  967. try {
  968. final RevCommit r = next;
  969. next = RevWalk.this.next();
  970. return r;
  971. } catch (MissingObjectException e) {
  972. throw new RevWalkException(e);
  973. } catch (IncorrectObjectTypeException e) {
  974. throw new RevWalkException(e);
  975. } catch (IOException e) {
  976. throw new RevWalkException(e);
  977. }
  978. }
  979. public void remove() {
  980. throw new UnsupportedOperationException();
  981. }
  982. };
  983. }
  984. /** Throws an exception if we have started producing output. */
  985. protected void assertNotStarted() {
  986. if (isNotStarted())
  987. return;
  988. throw new IllegalStateException("Output has already been started.");
  989. }
  990. private boolean isNotStarted() {
  991. return pending instanceof StartGenerator;
  992. }
  993. /**
  994. * Construct a new unparsed commit for the given object.
  995. *
  996. * @param id
  997. * the object this walker requires a commit reference for.
  998. * @return a new unparsed reference for the object.
  999. */
  1000. protected RevCommit createCommit(final AnyObjectId id) {
  1001. return new RevCommit(id);
  1002. }
  1003. void carryFlagsImpl(final RevCommit c) {
  1004. final int carry = c.flags & carryFlags;
  1005. if (carry != 0)
  1006. RevCommit.carryFlags(c, carry);
  1007. }
  1008. }