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

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