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.

BlameGenerator.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. /*
  2. * Copyright (C) 2011, 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.blame;
  44. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  45. import java.io.IOException;
  46. import java.util.Collection;
  47. import java.util.Collections;
  48. import org.eclipse.jgit.blame.Candidate.BlobCandidate;
  49. import org.eclipse.jgit.blame.Candidate.ReverseCandidate;
  50. import org.eclipse.jgit.blame.ReverseWalk.ReverseCommit;
  51. import org.eclipse.jgit.diff.DiffAlgorithm;
  52. import org.eclipse.jgit.diff.DiffEntry;
  53. import org.eclipse.jgit.diff.DiffEntry.ChangeType;
  54. import org.eclipse.jgit.diff.EditList;
  55. import org.eclipse.jgit.diff.HistogramDiff;
  56. import org.eclipse.jgit.diff.RawText;
  57. import org.eclipse.jgit.diff.RawTextComparator;
  58. import org.eclipse.jgit.diff.RenameDetector;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.lib.AnyObjectId;
  61. import org.eclipse.jgit.lib.MutableObjectId;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectLoader;
  64. import org.eclipse.jgit.lib.ObjectReader;
  65. import org.eclipse.jgit.lib.PersonIdent;
  66. import org.eclipse.jgit.lib.Repository;
  67. import org.eclipse.jgit.revwalk.RevCommit;
  68. import org.eclipse.jgit.revwalk.RevFlag;
  69. import org.eclipse.jgit.revwalk.RevWalk;
  70. import org.eclipse.jgit.treewalk.TreeWalk;
  71. import org.eclipse.jgit.treewalk.filter.PathFilter;
  72. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  73. /**
  74. * Generate author information for lines based on a provided file.
  75. * <p>
  76. * Applications that want a simple one-shot computation of blame for a file
  77. * should use {@link #computeBlameResult()} to prepare the entire result in one
  78. * method call. This may block for significant time as the history of the
  79. * repository must be traversed until information is gathered for every line.
  80. * <p>
  81. * Applications that want more incremental update behavior may use either the
  82. * raw {@link #next()} streaming approach supported by this class, or construct
  83. * a {@link BlameResult} using {@link BlameResult#create(BlameGenerator)} and
  84. * incrementally construct the result with {@link BlameResult#computeNext()}.
  85. * <p>
  86. * This class is not thread-safe.
  87. * <p>
  88. * An instance of BlameGenerator can only be used once. To blame multiple files
  89. * the application must create a new BlameGenerator.
  90. * <p>
  91. * During blame processing there are two files involved:
  92. * <ul>
  93. * <li>result - The file whose lines are being examined. This is the revision
  94. * the user is trying to view blame/annotation information alongside of.</li>
  95. * <li>source - The file that was blamed with supplying one or more lines of
  96. * data into result. The source may be a different file path (due to copy or
  97. * rename). Source line numbers may differ from result line numbers due to lines
  98. * being added/removed in intermediate revisions.</li>
  99. * </ul>
  100. * <p>
  101. * The blame algorithm is implemented by initially assigning responsibility for
  102. * all lines of the result to the starting commit. A difference against the
  103. * commit's ancestor is computed, and responsibility is passed to the ancestor
  104. * commit for any lines that are common. The starting commit is blamed only for
  105. * the lines that do not appear in the ancestor, if any. The loop repeats using
  106. * the ancestor, until there are no more lines to acquire information on, or the
  107. * file's creation point is discovered in history.
  108. */
  109. public class BlameGenerator {
  110. private final Repository repository;
  111. private final PathFilter resultPath;
  112. private final MutableObjectId idBuf;
  113. /** Revision pool used to acquire commits from. */
  114. private RevWalk revPool;
  115. /** Indicates the commit was put into the queue at least once. */
  116. private RevFlag SEEN;
  117. private ObjectReader reader;
  118. private TreeWalk treeWalk;
  119. private DiffAlgorithm diffAlgorithm = new HistogramDiff();
  120. private RawTextComparator textComparator = RawTextComparator.DEFAULT;
  121. private RenameDetector renameDetector;
  122. /** Potential candidates, sorted by commit time descending. */
  123. private Candidate queue;
  124. /** Number of lines that still need to be discovered. */
  125. private int remaining;
  126. /** Blame is currently assigned to this source. */
  127. private Candidate currentSource;
  128. /**
  129. * Create a blame generator for the repository and path (relative to
  130. * repository)
  131. *
  132. * @param repository
  133. * repository to access revision data from.
  134. * @param path
  135. * initial path of the file to start scanning (relative to the
  136. * repository).
  137. */
  138. public BlameGenerator(Repository repository, String path) {
  139. this.repository = repository;
  140. this.resultPath = PathFilter.create(path);
  141. idBuf = new MutableObjectId();
  142. setFollowFileRenames(true);
  143. initRevPool(false);
  144. remaining = -1;
  145. }
  146. private void initRevPool(boolean reverse) {
  147. if (queue != null)
  148. throw new IllegalStateException();
  149. if (revPool != null)
  150. revPool.release();
  151. if (reverse)
  152. revPool = new ReverseWalk(getRepository());
  153. else
  154. revPool = new RevWalk(getRepository());
  155. revPool.setRetainBody(true);
  156. SEEN = revPool.newFlag("SEEN"); //$NON-NLS-1$
  157. reader = revPool.getObjectReader();
  158. treeWalk = new TreeWalk(reader);
  159. treeWalk.setRecursive(true);
  160. }
  161. /** @return repository being scanned for revision history. */
  162. public Repository getRepository() {
  163. return repository;
  164. }
  165. /** @return path file path being processed. */
  166. public String getResultPath() {
  167. return resultPath.getPath();
  168. }
  169. /**
  170. * Difference algorithm to use when comparing revisions.
  171. *
  172. * @param algorithm
  173. * @return {@code this}
  174. */
  175. public BlameGenerator setDiffAlgorithm(DiffAlgorithm algorithm) {
  176. diffAlgorithm = algorithm;
  177. return this;
  178. }
  179. /**
  180. * Text comparator to use when comparing revisions.
  181. *
  182. * @param comparator
  183. * @return {@code this}
  184. */
  185. public BlameGenerator setTextComparator(RawTextComparator comparator) {
  186. textComparator = comparator;
  187. return this;
  188. }
  189. /**
  190. * Enable (or disable) following file renames, on by default.
  191. * <p>
  192. * If true renames are followed using the standard FollowFilter behavior
  193. * used by RevWalk (which matches {@code git log --follow} in the C
  194. * implementation). This is not the same as copy/move detection as
  195. * implemented by the C implementation's of {@code git blame -M -C}.
  196. *
  197. * @param follow
  198. * enable following.
  199. * @return {@code this}
  200. */
  201. public BlameGenerator setFollowFileRenames(boolean follow) {
  202. if (follow)
  203. renameDetector = new RenameDetector(getRepository());
  204. else
  205. renameDetector = null;
  206. return this;
  207. }
  208. /**
  209. * Obtain the RenameDetector if {@code setFollowFileRenames(true)}.
  210. *
  211. * @return the rename detector, allowing the application to configure its
  212. * settings for rename score and breaking behavior.
  213. */
  214. public RenameDetector getRenameDetector() {
  215. return renameDetector;
  216. }
  217. /**
  218. * Push a candidate blob onto the generator's traversal stack.
  219. * <p>
  220. * Candidates should be pushed in history order from oldest-to-newest.
  221. * Applications should push the starting commit first, then the index
  222. * revision (if the index is interesting), and finally the working tree
  223. * copy (if the working tree is interesting).
  224. *
  225. * @param description
  226. * description of the blob revision, such as "Working Tree".
  227. * @param contents
  228. * contents of the file.
  229. * @return {@code this}
  230. * @throws IOException
  231. * the repository cannot be read.
  232. */
  233. public BlameGenerator push(String description, byte[] contents)
  234. throws IOException {
  235. return push(description, new RawText(contents));
  236. }
  237. /**
  238. * Push a candidate blob onto the generator's traversal stack.
  239. * <p>
  240. * Candidates should be pushed in history order from oldest-to-newest.
  241. * Applications should push the starting commit first, then the index
  242. * revision (if the index is interesting), and finally the working tree copy
  243. * (if the working tree is interesting).
  244. *
  245. * @param description
  246. * description of the blob revision, such as "Working Tree".
  247. * @param contents
  248. * contents of the file.
  249. * @return {@code this}
  250. * @throws IOException
  251. * the repository cannot be read.
  252. */
  253. public BlameGenerator push(String description, RawText contents)
  254. throws IOException {
  255. if (description == null)
  256. description = JGitText.get().blameNotCommittedYet;
  257. BlobCandidate c = new BlobCandidate(description, resultPath);
  258. c.sourceText = contents;
  259. c.regionList = new Region(0, 0, contents.size());
  260. remaining = contents.size();
  261. push(c);
  262. return this;
  263. }
  264. /**
  265. * Push a candidate object onto the generator's traversal stack.
  266. * <p>
  267. * Candidates should be pushed in history order from oldest-to-newest.
  268. * Applications should push the starting commit first, then the index
  269. * revision (if the index is interesting), and finally the working tree copy
  270. * (if the working tree is interesting).
  271. *
  272. * @param description
  273. * description of the blob revision, such as "Working Tree".
  274. * @param id
  275. * may be a commit or a blob.
  276. * @return {@code this}
  277. * @throws IOException
  278. * the repository cannot be read.
  279. */
  280. public BlameGenerator push(String description, AnyObjectId id)
  281. throws IOException {
  282. ObjectLoader ldr = reader.open(id);
  283. if (ldr.getType() == OBJ_BLOB) {
  284. if (description == null)
  285. description = JGitText.get().blameNotCommittedYet;
  286. BlobCandidate c = new BlobCandidate(description, resultPath);
  287. c.sourceBlob = id.toObjectId();
  288. c.sourceText = new RawText(ldr.getCachedBytes(Integer.MAX_VALUE));
  289. c.regionList = new Region(0, 0, c.sourceText.size());
  290. remaining = c.sourceText.size();
  291. push(c);
  292. return this;
  293. }
  294. RevCommit commit = revPool.parseCommit(id);
  295. if (!find(commit, resultPath))
  296. return this;
  297. Candidate c = new Candidate(commit, resultPath);
  298. c.sourceBlob = idBuf.toObjectId();
  299. c.loadText(reader);
  300. c.regionList = new Region(0, 0, c.sourceText.size());
  301. remaining = c.sourceText.size();
  302. push(c);
  303. return this;
  304. }
  305. /**
  306. * Configure the generator to compute reverse blame (history of deletes).
  307. * <p>
  308. * This method is expensive as it immediately runs a RevWalk over the
  309. * history spanning the expression {@code start..end} (end being more recent
  310. * than start) and then performs the equivalent operation as
  311. * {@link #push(String, AnyObjectId)} to begin blame traversal from the
  312. * commit named by {@code start} walking forwards through history until
  313. * {@code end} blaming line deletions.
  314. * <p>
  315. * A reverse blame may produce multiple sources for the same result line,
  316. * each of these is a descendant commit that removed the line, typically
  317. * this occurs when the same deletion appears in multiple side branches such
  318. * as due to a cherry-pick. Applications relying on reverse should use
  319. * {@link BlameResult} as it filters these duplicate sources and only
  320. * remembers the first (oldest) deletion.
  321. *
  322. * @param start
  323. * oldest commit to traverse from. The result file will be loaded
  324. * from this commit's tree.
  325. * @param end
  326. * most recent commit to stop traversal at. Usually an active
  327. * branch tip, tag, or HEAD.
  328. * @return {@code this}
  329. * @throws IOException
  330. * the repository cannot be read.
  331. */
  332. public BlameGenerator reverse(AnyObjectId start, AnyObjectId end)
  333. throws IOException {
  334. return reverse(start, Collections.singleton(end.toObjectId()));
  335. }
  336. /**
  337. * Configure the generator to compute reverse blame (history of deletes).
  338. * <p>
  339. * This method is expensive as it immediately runs a RevWalk over the
  340. * history spanning the expression {@code start..end} (end being more recent
  341. * than start) and then performs the equivalent operation as
  342. * {@link #push(String, AnyObjectId)} to begin blame traversal from the
  343. * commit named by {@code start} walking forwards through history until
  344. * {@code end} blaming line deletions.
  345. * <p>
  346. * A reverse blame may produce multiple sources for the same result line,
  347. * each of these is a descendant commit that removed the line, typically
  348. * this occurs when the same deletion appears in multiple side branches such
  349. * as due to a cherry-pick. Applications relying on reverse should use
  350. * {@link BlameResult} as it filters these duplicate sources and only
  351. * remembers the first (oldest) deletion.
  352. *
  353. * @param start
  354. * oldest commit to traverse from. The result file will be loaded
  355. * from this commit's tree.
  356. * @param end
  357. * most recent commits to stop traversal at. Usually an active
  358. * branch tip, tag, or HEAD.
  359. * @return {@code this}
  360. * @throws IOException
  361. * the repository cannot be read.
  362. */
  363. public BlameGenerator reverse(AnyObjectId start,
  364. Collection<? extends ObjectId> end) throws IOException {
  365. initRevPool(true);
  366. ReverseCommit result = (ReverseCommit) revPool.parseCommit(start);
  367. if (!find(result, resultPath))
  368. return this;
  369. revPool.markUninteresting(result);
  370. for (ObjectId id : end)
  371. revPool.markStart(revPool.parseCommit(id));
  372. while (revPool.next() != null) {
  373. // just pump the queue
  374. }
  375. ReverseCandidate c = new ReverseCandidate(result, resultPath);
  376. c.sourceBlob = idBuf.toObjectId();
  377. c.loadText(reader);
  378. c.regionList = new Region(0, 0, c.sourceText.size());
  379. remaining = c.sourceText.size();
  380. push(c);
  381. return this;
  382. }
  383. /**
  384. * Allocate a new RevFlag for use by the caller.
  385. *
  386. * @param name
  387. * unique name of the flag in the blame context.
  388. * @return the newly allocated flag.
  389. * @since 3.4
  390. */
  391. public RevFlag newFlag(String name) {
  392. return revPool.newFlag(name);
  393. }
  394. /**
  395. * Execute the generator in a blocking fashion until all data is ready.
  396. *
  397. * @return the complete result. Null if no file exists for the given path.
  398. * @throws IOException
  399. * the repository cannot be read.
  400. */
  401. public BlameResult computeBlameResult() throws IOException {
  402. try {
  403. BlameResult r = BlameResult.create(this);
  404. if (r != null)
  405. r.computeAll();
  406. return r;
  407. } finally {
  408. release();
  409. }
  410. }
  411. /**
  412. * Step the blame algorithm one iteration.
  413. *
  414. * @return true if the generator has found a region's source. The getSource*
  415. * and {@link #getResultStart()}, {@link #getResultEnd()} methods
  416. * can be used to inspect the region found. False if there are no
  417. * more regions to describe.
  418. * @throws IOException
  419. * repository cannot be read.
  420. */
  421. public boolean next() throws IOException {
  422. // If there is a source still pending, produce the next region.
  423. if (currentSource != null) {
  424. Region r = currentSource.regionList;
  425. Region n = r.next;
  426. remaining -= r.length;
  427. if (n != null) {
  428. currentSource.regionList = n;
  429. return true;
  430. }
  431. if (currentSource.queueNext != null)
  432. return result(currentSource.queueNext);
  433. currentSource = null;
  434. }
  435. // If there are no lines remaining, the entire result is done,
  436. // even if there are revisions still available for the path.
  437. if (remaining == 0)
  438. return done();
  439. for (;;) {
  440. Candidate n = pop();
  441. if (n == null)
  442. return done();
  443. int pCnt = n.getParentCount();
  444. if (pCnt == 1) {
  445. if (processOne(n))
  446. return true;
  447. } else if (1 < pCnt) {
  448. if (processMerge(n))
  449. return true;
  450. } else if (n instanceof ReverseCandidate) {
  451. // Do not generate a tip of a reverse. The region
  452. // survives and should not appear to be deleted.
  453. } else /* if (pCnt == 0) */{
  454. // Root commit, with at least one surviving region.
  455. // Assign the remaining blame here.
  456. return result(n);
  457. }
  458. }
  459. }
  460. private boolean done() {
  461. release();
  462. return false;
  463. }
  464. private boolean result(Candidate n) throws IOException {
  465. if (n.sourceCommit != null)
  466. revPool.parseBody(n.sourceCommit);
  467. currentSource = n;
  468. return true;
  469. }
  470. private boolean reverseResult(Candidate parent, Candidate source)
  471. throws IOException {
  472. // On a reverse blame present the application the parent
  473. // (as this is what did the removals), however the region
  474. // list to enumerate is the source's surviving list.
  475. Candidate res = parent.copy(parent.sourceCommit);
  476. res.regionList = source.regionList;
  477. return result(res);
  478. }
  479. private Candidate pop() {
  480. Candidate n = queue;
  481. if (n != null) {
  482. queue = n.queueNext;
  483. n.queueNext = null;
  484. }
  485. return n;
  486. }
  487. private void push(BlobCandidate toInsert) {
  488. Candidate c = queue;
  489. if (c != null) {
  490. c.remove(SEEN); // will be pushed by toInsert
  491. c.regionList = null;
  492. toInsert.parent = c;
  493. }
  494. queue = toInsert;
  495. }
  496. private void push(Candidate toInsert) {
  497. if (toInsert.has(SEEN)) {
  498. // We have already added a Candidate for this commit to the queue,
  499. // this can happen if the commit is a merge base for two or more
  500. // parallel branches that were merged together.
  501. //
  502. // It is likely the candidate was not yet processed. The queue
  503. // sorts descending by commit time and usually descendant commits
  504. // have higher timestamps than the ancestors.
  505. //
  506. // Find the existing candidate and merge the new candidate's
  507. // region list into it.
  508. for (Candidate p = queue; p != null; p = p.queueNext) {
  509. if (p.canMergeRegions(toInsert)) {
  510. p.mergeRegions(toInsert);
  511. return;
  512. }
  513. }
  514. }
  515. toInsert.add(SEEN);
  516. // Insert into the queue using descending commit time, so
  517. // the most recent commit will pop next.
  518. int time = toInsert.getTime();
  519. Candidate n = queue;
  520. if (n == null || time >= n.getTime()) {
  521. toInsert.queueNext = n;
  522. queue = toInsert;
  523. return;
  524. }
  525. for (Candidate p = n;; p = n) {
  526. n = p.queueNext;
  527. if (n == null || time >= n.getTime()) {
  528. toInsert.queueNext = n;
  529. p.queueNext = toInsert;
  530. return;
  531. }
  532. }
  533. }
  534. private boolean processOne(Candidate n) throws IOException {
  535. RevCommit parent = n.getParent(0);
  536. if (parent == null)
  537. return split(n.getNextCandidate(0), n);
  538. revPool.parseHeaders(parent);
  539. if (find(parent, n.sourcePath)) {
  540. if (idBuf.equals(n.sourceBlob)) {
  541. // The common case of the file not being modified in
  542. // a simple string-of-pearls history. Blame parent.
  543. n.sourceCommit = parent;
  544. push(n);
  545. return false;
  546. }
  547. Candidate next = n.create(parent, n.sourcePath);
  548. next.sourceBlob = idBuf.toObjectId();
  549. next.loadText(reader);
  550. return split(next, n);
  551. }
  552. if (n.sourceCommit == null)
  553. return result(n);
  554. DiffEntry r = findRename(parent, n.sourceCommit, n.sourcePath);
  555. if (r == null)
  556. return result(n);
  557. if (0 == r.getOldId().prefixCompare(n.sourceBlob)) {
  558. // A 100% rename without any content change can also
  559. // skip directly to the parent.
  560. n.sourceCommit = parent;
  561. n.sourcePath = PathFilter.create(r.getOldPath());
  562. push(n);
  563. return false;
  564. }
  565. Candidate next = n.create(parent, PathFilter.create(r.getOldPath()));
  566. next.sourceBlob = r.getOldId().toObjectId();
  567. next.renameScore = r.getScore();
  568. next.loadText(reader);
  569. return split(next, n);
  570. }
  571. private boolean split(Candidate parent, Candidate source)
  572. throws IOException {
  573. EditList editList = diffAlgorithm.diff(textComparator,
  574. parent.sourceText, source.sourceText);
  575. if (editList.isEmpty()) {
  576. // Ignoring whitespace (or some other special comparator) can
  577. // cause non-identical blobs to have an empty edit list. In
  578. // a case like this push the parent alone.
  579. parent.regionList = source.regionList;
  580. push(parent);
  581. return false;
  582. }
  583. parent.takeBlame(editList, source);
  584. if (parent.regionList != null)
  585. push(parent);
  586. if (source.regionList != null) {
  587. if (source instanceof ReverseCandidate)
  588. return reverseResult(parent, source);
  589. return result(source);
  590. }
  591. return false;
  592. }
  593. private boolean processMerge(Candidate n) throws IOException {
  594. int pCnt = n.getParentCount();
  595. // If any single parent exactly matches the merge, follow only
  596. // that one parent through history.
  597. ObjectId[] ids = null;
  598. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  599. RevCommit parent = n.getParent(pIdx);
  600. revPool.parseHeaders(parent);
  601. if (!find(parent, n.sourcePath))
  602. continue;
  603. if (!(n instanceof ReverseCandidate) && idBuf.equals(n.sourceBlob)) {
  604. n.sourceCommit = parent;
  605. push(n);
  606. return false;
  607. }
  608. if (ids == null)
  609. ids = new ObjectId[pCnt];
  610. ids[pIdx] = idBuf.toObjectId();
  611. }
  612. // If rename detection is enabled, search for any relevant names.
  613. DiffEntry[] renames = null;
  614. if (renameDetector != null) {
  615. renames = new DiffEntry[pCnt];
  616. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  617. RevCommit parent = n.getParent(pIdx);
  618. if (ids != null && ids[pIdx] != null)
  619. continue;
  620. DiffEntry r = findRename(parent, n.sourceCommit, n.sourcePath);
  621. if (r == null)
  622. continue;
  623. if (n instanceof ReverseCandidate) {
  624. if (ids == null)
  625. ids = new ObjectId[pCnt];
  626. ids[pCnt] = r.getOldId().toObjectId();
  627. } else if (0 == r.getOldId().prefixCompare(n.sourceBlob)) {
  628. // A 100% rename without any content change can also
  629. // skip directly to the parent. Note this bypasses an
  630. // earlier parent that had the path (above) but did not
  631. // have an exact content match. For performance reasons
  632. // we choose to follow the one parent over trying to do
  633. // possibly both parents.
  634. n.sourceCommit = parent;
  635. n.sourcePath = PathFilter.create(r.getOldPath());
  636. push(n);
  637. return false;
  638. }
  639. renames[pIdx] = r;
  640. }
  641. }
  642. // Construct the candidate for each parent.
  643. Candidate[] parents = new Candidate[pCnt];
  644. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  645. RevCommit parent = n.getParent(pIdx);
  646. Candidate p;
  647. if (renames != null && renames[pIdx] != null) {
  648. p = n.create(parent,
  649. PathFilter.create(renames[pIdx].getOldPath()));
  650. p.renameScore = renames[pIdx].getScore();
  651. p.sourceBlob = renames[pIdx].getOldId().toObjectId();
  652. } else if (ids != null && ids[pIdx] != null) {
  653. p = n.create(parent, n.sourcePath);
  654. p.sourceBlob = ids[pIdx];
  655. } else {
  656. continue;
  657. }
  658. EditList editList;
  659. if (n instanceof ReverseCandidate
  660. && p.sourceBlob.equals(n.sourceBlob)) {
  661. // This special case happens on ReverseCandidate forks.
  662. p.sourceText = n.sourceText;
  663. editList = new EditList(0);
  664. } else {
  665. p.loadText(reader);
  666. editList = diffAlgorithm.diff(textComparator,
  667. p.sourceText, n.sourceText);
  668. }
  669. if (editList.isEmpty()) {
  670. // Ignoring whitespace (or some other special comparator) can
  671. // cause non-identical blobs to have an empty edit list. In
  672. // a case like this push the parent alone.
  673. if (n instanceof ReverseCandidate) {
  674. parents[pIdx] = p;
  675. continue;
  676. }
  677. p.regionList = n.regionList;
  678. push(p);
  679. return false;
  680. }
  681. p.takeBlame(editList, n);
  682. // Only remember this parent candidate if there is at least
  683. // one region that was blamed on the parent.
  684. if (p.regionList != null) {
  685. // Reverse blame requires inverting the regions. This puts
  686. // the regions the parent deleted from us into the parent,
  687. // and retains the common regions to look at other parents
  688. // for deletions.
  689. if (n instanceof ReverseCandidate) {
  690. Region r = p.regionList;
  691. p.regionList = n.regionList;
  692. n.regionList = r;
  693. }
  694. parents[pIdx] = p;
  695. }
  696. }
  697. if (n instanceof ReverseCandidate) {
  698. // On a reverse blame report all deletions found in the children,
  699. // and pass on to them a copy of our region list.
  700. Candidate resultHead = null;
  701. Candidate resultTail = null;
  702. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  703. Candidate p = parents[pIdx];
  704. if (p == null)
  705. continue;
  706. if (p.regionList != null) {
  707. Candidate r = p.copy(p.sourceCommit);
  708. if (resultTail != null) {
  709. resultTail.queueNext = r;
  710. resultTail = r;
  711. } else {
  712. resultHead = r;
  713. resultTail = r;
  714. }
  715. }
  716. if (n.regionList != null) {
  717. p.regionList = n.regionList.deepCopy();
  718. push(p);
  719. }
  720. }
  721. if (resultHead != null)
  722. return result(resultHead);
  723. return false;
  724. }
  725. // Push any parents that are still candidates.
  726. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  727. if (parents[pIdx] != null)
  728. push(parents[pIdx]);
  729. }
  730. if (n.regionList != null)
  731. return result(n);
  732. return false;
  733. }
  734. /**
  735. * Get the revision blamed for the current region.
  736. * <p>
  737. * The source commit may be null if the line was blamed to an uncommitted
  738. * revision, such as the working tree copy, or during a reverse blame if the
  739. * line survives to the end revision (e.g. the branch tip).
  740. *
  741. * @return current revision being blamed.
  742. */
  743. public RevCommit getSourceCommit() {
  744. return currentSource.sourceCommit;
  745. }
  746. /** @return current author being blamed. */
  747. public PersonIdent getSourceAuthor() {
  748. return currentSource.getAuthor();
  749. }
  750. /** @return current committer being blamed. */
  751. public PersonIdent getSourceCommitter() {
  752. RevCommit c = getSourceCommit();
  753. return c != null ? c.getCommitterIdent() : null;
  754. }
  755. /** @return path of the file being blamed. */
  756. public String getSourcePath() {
  757. return currentSource.sourcePath.getPath();
  758. }
  759. /** @return rename score if a rename occurred in {@link #getSourceCommit}. */
  760. public int getRenameScore() {
  761. return currentSource.renameScore;
  762. }
  763. /**
  764. * @return first line of the source data that has been blamed for the
  765. * current region. This is line number of where the region was added
  766. * during {@link #getSourceCommit()} in file
  767. * {@link #getSourcePath()}.
  768. */
  769. public int getSourceStart() {
  770. return currentSource.regionList.sourceStart;
  771. }
  772. /**
  773. * @return one past the range of the source data that has been blamed for
  774. * the current region. This is line number of where the region was
  775. * added during {@link #getSourceCommit()} in file
  776. * {@link #getSourcePath()}.
  777. */
  778. public int getSourceEnd() {
  779. Region r = currentSource.regionList;
  780. return r.sourceStart + r.length;
  781. }
  782. /**
  783. * @return first line of the result that {@link #getSourceCommit()} has been
  784. * blamed for providing. Line numbers use 0 based indexing.
  785. */
  786. public int getResultStart() {
  787. return currentSource.regionList.resultStart;
  788. }
  789. /**
  790. * @return one past the range of the result that {@link #getSourceCommit()}
  791. * has been blamed for providing. Line numbers use 0 based indexing.
  792. * Because a source cannot be blamed for an empty region of the
  793. * result, {@link #getResultEnd()} is always at least one larger
  794. * than {@link #getResultStart()}.
  795. */
  796. public int getResultEnd() {
  797. Region r = currentSource.regionList;
  798. return r.resultStart + r.length;
  799. }
  800. /**
  801. * @return number of lines in the current region being blamed to
  802. * {@link #getSourceCommit()}. This is always the value of the
  803. * expression {@code getResultEnd() - getResultStart()}, but also
  804. * {@code getSourceEnd() - getSourceStart()}.
  805. */
  806. public int getRegionLength() {
  807. return currentSource.regionList.length;
  808. }
  809. /**
  810. * @return complete contents of the source file blamed for the current
  811. * output region. This is the contents of {@link #getSourcePath()}
  812. * within {@link #getSourceCommit()}. The source contents is
  813. * temporarily available as an artifact of the blame algorithm. Most
  814. * applications will want the result contents for display to users.
  815. */
  816. public RawText getSourceContents() {
  817. return currentSource.sourceText;
  818. }
  819. /**
  820. * @return complete file contents of the result file blame is annotating.
  821. * This value is accessible only after being configured and only
  822. * immediately before the first call to {@link #next()}. Returns
  823. * null if the path does not exist.
  824. * @throws IOException
  825. * repository cannot be read.
  826. * @throws IllegalStateException
  827. * {@link #next()} has already been invoked.
  828. */
  829. public RawText getResultContents() throws IOException {
  830. return queue != null ? queue.sourceText : null;
  831. }
  832. /** Release the current blame session. */
  833. public void release() {
  834. revPool.release();
  835. queue = null;
  836. currentSource = null;
  837. }
  838. private boolean find(RevCommit commit, PathFilter path) throws IOException {
  839. treeWalk.setFilter(path);
  840. treeWalk.reset(commit.getTree());
  841. while (treeWalk.next()) {
  842. if (path.isDone(treeWalk)) {
  843. if (treeWalk.getFileMode(0).getObjectType() != OBJ_BLOB)
  844. return false;
  845. treeWalk.getObjectId(idBuf, 0);
  846. return true;
  847. }
  848. if (treeWalk.isSubtree())
  849. treeWalk.enterSubtree();
  850. }
  851. return false;
  852. }
  853. private DiffEntry findRename(RevCommit parent, RevCommit commit,
  854. PathFilter path) throws IOException {
  855. if (renameDetector == null)
  856. return null;
  857. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  858. treeWalk.reset(parent.getTree(), commit.getTree());
  859. renameDetector.reset();
  860. renameDetector.addAll(DiffEntry.scan(treeWalk));
  861. for (DiffEntry ent : renameDetector.compute()) {
  862. if (isRename(ent) && ent.getNewPath().equals(path.getPath()))
  863. return ent;
  864. }
  865. return null;
  866. }
  867. private static boolean isRename(DiffEntry ent) {
  868. return ent.getChangeType() == ChangeType.RENAME
  869. || ent.getChangeType() == ChangeType.COPY;
  870. }
  871. }