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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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 has already been processed. */
  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. * Execute the generator in a blocking fashion until all data is ready.
  385. *
  386. * @return the complete result. Null if no file exists for the given path.
  387. * @throws IOException
  388. * the repository cannot be read.
  389. */
  390. public BlameResult computeBlameResult() throws IOException {
  391. try {
  392. BlameResult r = BlameResult.create(this);
  393. if (r != null)
  394. r.computeAll();
  395. return r;
  396. } finally {
  397. release();
  398. }
  399. }
  400. /**
  401. * Step the blame algorithm one iteration.
  402. *
  403. * @return true if the generator has found a region's source. The getSource*
  404. * and {@link #getResultStart()}, {@link #getResultEnd()} methods
  405. * can be used to inspect the region found. False if there are no
  406. * more regions to describe.
  407. * @throws IOException
  408. * repository cannot be read.
  409. */
  410. public boolean next() throws IOException {
  411. // If there is a source still pending, produce the next region.
  412. if (currentSource != null) {
  413. Region r = currentSource.regionList;
  414. Region n = r.next;
  415. remaining -= r.length;
  416. if (n != null) {
  417. currentSource.regionList = n;
  418. return true;
  419. }
  420. if (currentSource.queueNext != null)
  421. return result(currentSource.queueNext);
  422. currentSource = null;
  423. }
  424. // If there are no lines remaining, the entire result is done,
  425. // even if there are revisions still available for the path.
  426. if (remaining == 0)
  427. return done();
  428. for (;;) {
  429. Candidate n = pop();
  430. if (n == null)
  431. return done();
  432. int pCnt = n.getParentCount();
  433. if (pCnt == 1) {
  434. if (processOne(n))
  435. return true;
  436. } else if (1 < pCnt) {
  437. if (processMerge(n))
  438. return true;
  439. } else if (n instanceof ReverseCandidate) {
  440. // Do not generate a tip of a reverse. The region
  441. // survives and should not appear to be deleted.
  442. } else /* if (pCnt == 0) */{
  443. // Root commit, with at least one surviving region.
  444. // Assign the remaining blame here.
  445. return result(n);
  446. }
  447. }
  448. }
  449. private boolean done() {
  450. release();
  451. return false;
  452. }
  453. private boolean result(Candidate n) throws IOException {
  454. if (n.sourceCommit != null)
  455. revPool.parseBody(n.sourceCommit);
  456. currentSource = n;
  457. return true;
  458. }
  459. private boolean reverseResult(Candidate parent, Candidate source)
  460. throws IOException {
  461. // On a reverse blame present the application the parent
  462. // (as this is what did the removals), however the region
  463. // list to enumerate is the source's surviving list.
  464. Candidate res = parent.copy(parent.sourceCommit);
  465. res.regionList = source.regionList;
  466. return result(res);
  467. }
  468. private Candidate pop() {
  469. Candidate n = queue;
  470. if (n != null) {
  471. queue = n.queueNext;
  472. n.queueNext = null;
  473. }
  474. return n;
  475. }
  476. private void push(BlobCandidate toInsert) {
  477. Candidate c = queue;
  478. if (c != null) {
  479. c.regionList = null;
  480. toInsert.parent = c;
  481. }
  482. queue = toInsert;
  483. }
  484. private void push(Candidate toInsert) {
  485. // Mark sources to ensure they get discarded (above) if
  486. // another path to the same commit.
  487. toInsert.add(SEEN);
  488. // Insert into the queue using descending commit time, so
  489. // the most recent commit will pop next.
  490. int time = toInsert.getTime();
  491. Candidate n = queue;
  492. if (n == null || time >= n.getTime()) {
  493. toInsert.queueNext = n;
  494. queue = toInsert;
  495. return;
  496. }
  497. for (Candidate p = n;; p = n) {
  498. n = p.queueNext;
  499. if (n == null || time >= n.getTime()) {
  500. toInsert.queueNext = n;
  501. p.queueNext = toInsert;
  502. return;
  503. }
  504. }
  505. }
  506. private boolean processOne(Candidate n) throws IOException {
  507. RevCommit parent = n.getParent(0);
  508. if (parent == null)
  509. return split(n.getNextCandidate(0), n);
  510. if (parent.has(SEEN))
  511. return false;
  512. revPool.parseHeaders(parent);
  513. if (find(parent, n.sourcePath)) {
  514. if (idBuf.equals(n.sourceBlob)) {
  515. // The common case of the file not being modified in
  516. // a simple string-of-pearls history. Blame parent.
  517. n.sourceCommit = parent;
  518. push(n);
  519. return false;
  520. }
  521. Candidate next = n.create(parent, n.sourcePath);
  522. next.sourceBlob = idBuf.toObjectId();
  523. next.loadText(reader);
  524. return split(next, n);
  525. }
  526. if (n.sourceCommit == null)
  527. return result(n);
  528. DiffEntry r = findRename(parent, n.sourceCommit, n.sourcePath);
  529. if (r == null)
  530. return result(n);
  531. if (0 == r.getOldId().prefixCompare(n.sourceBlob)) {
  532. // A 100% rename without any content change can also
  533. // skip directly to the parent.
  534. n.sourceCommit = parent;
  535. n.sourcePath = PathFilter.create(r.getOldPath());
  536. push(n);
  537. return false;
  538. }
  539. Candidate next = n.create(parent, PathFilter.create(r.getOldPath()));
  540. next.sourceBlob = r.getOldId().toObjectId();
  541. next.renameScore = r.getScore();
  542. next.loadText(reader);
  543. return split(next, n);
  544. }
  545. private boolean split(Candidate parent, Candidate source)
  546. throws IOException {
  547. EditList editList = diffAlgorithm.diff(textComparator,
  548. parent.sourceText, source.sourceText);
  549. if (editList.isEmpty()) {
  550. // Ignoring whitespace (or some other special comparator) can
  551. // cause non-identical blobs to have an empty edit list. In
  552. // a case like this push the parent alone.
  553. parent.regionList = source.regionList;
  554. push(parent);
  555. return false;
  556. }
  557. parent.takeBlame(editList, source);
  558. if (parent.regionList != null)
  559. push(parent);
  560. if (source.regionList != null) {
  561. if (source instanceof ReverseCandidate)
  562. return reverseResult(parent, source);
  563. return result(source);
  564. }
  565. return false;
  566. }
  567. private boolean processMerge(Candidate n) throws IOException {
  568. int pCnt = n.getParentCount();
  569. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  570. RevCommit parent = n.getParent(pIdx);
  571. if (parent.has(SEEN))
  572. continue;
  573. revPool.parseHeaders(parent);
  574. }
  575. // If any single parent exactly matches the merge, follow only
  576. // that one parent through history.
  577. ObjectId[] ids = null;
  578. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  579. RevCommit parent = n.getParent(pIdx);
  580. if (parent.has(SEEN))
  581. continue;
  582. if (!find(parent, n.sourcePath))
  583. continue;
  584. if (!(n instanceof ReverseCandidate) && idBuf.equals(n.sourceBlob)) {
  585. n.sourceCommit = parent;
  586. push(n);
  587. return false;
  588. }
  589. if (ids == null)
  590. ids = new ObjectId[pCnt];
  591. ids[pIdx] = idBuf.toObjectId();
  592. }
  593. // If rename detection is enabled, search for any relevant names.
  594. DiffEntry[] renames = null;
  595. if (renameDetector != null) {
  596. renames = new DiffEntry[pCnt];
  597. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  598. RevCommit parent = n.getParent(pIdx);
  599. if (parent.has(SEEN))
  600. continue;
  601. if (ids != null && ids[pIdx] != null)
  602. continue;
  603. DiffEntry r = findRename(parent, n.sourceCommit, n.sourcePath);
  604. if (r == null)
  605. continue;
  606. if (n instanceof ReverseCandidate) {
  607. if (ids == null)
  608. ids = new ObjectId[pCnt];
  609. ids[pCnt] = r.getOldId().toObjectId();
  610. } else if (0 == r.getOldId().prefixCompare(n.sourceBlob)) {
  611. // A 100% rename without any content change can also
  612. // skip directly to the parent. Note this bypasses an
  613. // earlier parent that had the path (above) but did not
  614. // have an exact content match. For performance reasons
  615. // we choose to follow the one parent over trying to do
  616. // possibly both parents.
  617. n.sourceCommit = parent;
  618. n.sourcePath = PathFilter.create(r.getOldPath());
  619. push(n);
  620. return false;
  621. }
  622. renames[pIdx] = r;
  623. }
  624. }
  625. // Construct the candidate for each parent.
  626. Candidate[] parents = new Candidate[pCnt];
  627. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  628. RevCommit parent = n.getParent(pIdx);
  629. if (parent.has(SEEN))
  630. continue;
  631. Candidate p;
  632. if (renames != null && renames[pIdx] != null) {
  633. p = n.create(parent,
  634. PathFilter.create(renames[pIdx].getOldPath()));
  635. p.renameScore = renames[pIdx].getScore();
  636. p.sourceBlob = renames[pIdx].getOldId().toObjectId();
  637. } else if (ids != null && ids[pIdx] != null) {
  638. p = n.create(parent, n.sourcePath);
  639. p.sourceBlob = ids[pIdx];
  640. } else {
  641. continue;
  642. }
  643. EditList editList;
  644. if (n instanceof ReverseCandidate
  645. && p.sourceBlob.equals(n.sourceBlob)) {
  646. // This special case happens on ReverseCandidate forks.
  647. p.sourceText = n.sourceText;
  648. editList = new EditList(0);
  649. } else {
  650. p.loadText(reader);
  651. editList = diffAlgorithm.diff(textComparator,
  652. p.sourceText, n.sourceText);
  653. }
  654. if (editList.isEmpty()) {
  655. // Ignoring whitespace (or some other special comparator) can
  656. // cause non-identical blobs to have an empty edit list. In
  657. // a case like this push the parent alone.
  658. if (n instanceof ReverseCandidate) {
  659. parents[pIdx] = p;
  660. continue;
  661. }
  662. p.regionList = n.regionList;
  663. push(p);
  664. return false;
  665. }
  666. p.takeBlame(editList, n);
  667. // Only remember this parent candidate if there is at least
  668. // one region that was blamed on the parent.
  669. if (p.regionList != null) {
  670. // Reverse blame requires inverting the regions. This puts
  671. // the regions the parent deleted from us into the parent,
  672. // and retains the common regions to look at other parents
  673. // for deletions.
  674. if (n instanceof ReverseCandidate) {
  675. Region r = p.regionList;
  676. p.regionList = n.regionList;
  677. n.regionList = r;
  678. }
  679. parents[pIdx] = p;
  680. }
  681. }
  682. if (n instanceof ReverseCandidate) {
  683. // On a reverse blame report all deletions found in the children,
  684. // and pass on to them a copy of our region list.
  685. Candidate resultHead = null;
  686. Candidate resultTail = null;
  687. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  688. Candidate p = parents[pIdx];
  689. if (p == null)
  690. continue;
  691. if (p.regionList != null) {
  692. Candidate r = p.copy(p.sourceCommit);
  693. if (resultTail != null) {
  694. resultTail.queueNext = r;
  695. resultTail = r;
  696. } else {
  697. resultHead = r;
  698. resultTail = r;
  699. }
  700. }
  701. if (n.regionList != null) {
  702. p.regionList = n.regionList.deepCopy();
  703. push(p);
  704. }
  705. }
  706. if (resultHead != null)
  707. return result(resultHead);
  708. return false;
  709. }
  710. // Push any parents that are still candidates.
  711. for (int pIdx = 0; pIdx < pCnt; pIdx++) {
  712. if (parents[pIdx] != null)
  713. push(parents[pIdx]);
  714. }
  715. if (n.regionList != null)
  716. return result(n);
  717. return false;
  718. }
  719. /**
  720. * Get the revision blamed for the current region.
  721. * <p>
  722. * The source commit may be null if the line was blamed to an uncommitted
  723. * revision, such as the working tree copy, or during a reverse blame if the
  724. * line survives to the end revision (e.g. the branch tip).
  725. *
  726. * @return current revision being blamed.
  727. */
  728. public RevCommit getSourceCommit() {
  729. return currentSource.sourceCommit;
  730. }
  731. /** @return current author being blamed. */
  732. public PersonIdent getSourceAuthor() {
  733. return currentSource.getAuthor();
  734. }
  735. /** @return current committer being blamed. */
  736. public PersonIdent getSourceCommitter() {
  737. RevCommit c = getSourceCommit();
  738. return c != null ? c.getCommitterIdent() : null;
  739. }
  740. /** @return path of the file being blamed. */
  741. public String getSourcePath() {
  742. return currentSource.sourcePath.getPath();
  743. }
  744. /** @return rename score if a rename occurred in {@link #getSourceCommit}. */
  745. public int getRenameScore() {
  746. return currentSource.renameScore;
  747. }
  748. /**
  749. * @return first line of the source data that has been blamed for the
  750. * current region. This is line number of where the region was added
  751. * during {@link #getSourceCommit()} in file
  752. * {@link #getSourcePath()}.
  753. */
  754. public int getSourceStart() {
  755. return currentSource.regionList.sourceStart;
  756. }
  757. /**
  758. * @return one past the range of the source data that has been blamed for
  759. * the current region. This is line number of where the region was
  760. * added during {@link #getSourceCommit()} in file
  761. * {@link #getSourcePath()}.
  762. */
  763. public int getSourceEnd() {
  764. Region r = currentSource.regionList;
  765. return r.sourceStart + r.length;
  766. }
  767. /**
  768. * @return first line of the result that {@link #getSourceCommit()} has been
  769. * blamed for providing. Line numbers use 0 based indexing.
  770. */
  771. public int getResultStart() {
  772. return currentSource.regionList.resultStart;
  773. }
  774. /**
  775. * @return one past the range of the result that {@link #getSourceCommit()}
  776. * has been blamed for providing. Line numbers use 0 based indexing.
  777. * Because a source cannot be blamed for an empty region of the
  778. * result, {@link #getResultEnd()} is always at least one larger
  779. * than {@link #getResultStart()}.
  780. */
  781. public int getResultEnd() {
  782. Region r = currentSource.regionList;
  783. return r.resultStart + r.length;
  784. }
  785. /**
  786. * @return number of lines in the current region being blamed to
  787. * {@link #getSourceCommit()}. This is always the value of the
  788. * expression {@code getResultEnd() - getResultStart()}, but also
  789. * {@code getSourceEnd() - getSourceStart()}.
  790. */
  791. public int getRegionLength() {
  792. return currentSource.regionList.length;
  793. }
  794. /**
  795. * @return complete contents of the source file blamed for the current
  796. * output region. This is the contents of {@link #getSourcePath()}
  797. * within {@link #getSourceCommit()}. The source contents is
  798. * temporarily available as an artifact of the blame algorithm. Most
  799. * applications will want the result contents for display to users.
  800. */
  801. public RawText getSourceContents() {
  802. return currentSource.sourceText;
  803. }
  804. /**
  805. * @return complete file contents of the result file blame is annotating.
  806. * This value is accessible only after being configured and only
  807. * immediately before the first call to {@link #next()}. Returns
  808. * null if the path does not exist.
  809. * @throws IOException
  810. * repository cannot be read.
  811. * @throws IllegalStateException
  812. * {@link #next()} has already been invoked.
  813. */
  814. public RawText getResultContents() throws IOException {
  815. return queue != null ? queue.sourceText : null;
  816. }
  817. /** Release the current blame session. */
  818. public void release() {
  819. revPool.release();
  820. queue = null;
  821. currentSource = null;
  822. }
  823. private boolean find(RevCommit commit, PathFilter path) throws IOException {
  824. treeWalk.setFilter(path);
  825. treeWalk.reset(commit.getTree());
  826. while (treeWalk.next()) {
  827. if (path.isDone(treeWalk)) {
  828. if (treeWalk.getFileMode(0).getObjectType() != OBJ_BLOB)
  829. return false;
  830. treeWalk.getObjectId(idBuf, 0);
  831. return true;
  832. }
  833. if (treeWalk.isSubtree())
  834. treeWalk.enterSubtree();
  835. }
  836. return false;
  837. }
  838. private DiffEntry findRename(RevCommit parent, RevCommit commit,
  839. PathFilter path) throws IOException {
  840. if (renameDetector == null)
  841. return null;
  842. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  843. treeWalk.reset(parent.getTree(), commit.getTree());
  844. renameDetector.reset();
  845. renameDetector.addAll(DiffEntry.scan(treeWalk));
  846. for (DiffEntry ent : renameDetector.compute()) {
  847. if (isRename(ent) && ent.getNewPath().equals(path.getPath()))
  848. return ent;
  849. }
  850. return null;
  851. }
  852. private static boolean isRename(DiffEntry ent) {
  853. return ent.getChangeType() == ChangeType.RENAME
  854. || ent.getChangeType() == ChangeType.COPY;
  855. }
  856. }