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

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