BlameCommand.java

  1. /*
  2.  * Copyright (C) 2011, GitHub 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.api;

  44. import java.io.File;
  45. import java.io.FileInputStream;
  46. import java.io.FileNotFoundException;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.util.ArrayList;
  50. import java.util.Collection;
  51. import java.util.Collections;

  52. import org.eclipse.jgit.api.errors.GitAPIException;
  53. import org.eclipse.jgit.api.errors.JGitInternalException;
  54. import org.eclipse.jgit.blame.BlameGenerator;
  55. import org.eclipse.jgit.blame.BlameResult;
  56. import org.eclipse.jgit.diff.DiffAlgorithm;
  57. import org.eclipse.jgit.diff.RawText;
  58. import org.eclipse.jgit.diff.RawTextComparator;
  59. import org.eclipse.jgit.dircache.DirCache;
  60. import org.eclipse.jgit.lib.AnyObjectId;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.CoreConfig.AutoCRLF;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.treewalk.WorkingTreeOptions;
  66. import org.eclipse.jgit.util.IO;
  67. import org.eclipse.jgit.util.io.AutoLFInputStream;

  68. /**
  69.  * Blame command for building a {@link org.eclipse.jgit.blame.BlameResult} for a
  70.  * file path.
  71.  */
  72. public class BlameCommand extends GitCommand<BlameResult> {

  73.     private String path;

  74.     private DiffAlgorithm diffAlgorithm;

  75.     private RawTextComparator textComparator;

  76.     private ObjectId startCommit;

  77.     private Collection<ObjectId> reverseEndCommits;

  78.     private Boolean followFileRenames;

  79.     /**
  80.      * Constructor for BlameCommand
  81.      *
  82.      * @param repo
  83.      *            the {@link org.eclipse.jgit.lib.Repository}
  84.      */
  85.     public BlameCommand(Repository repo) {
  86.         super(repo);
  87.     }

  88.     /**
  89.      * Set file path.
  90.      *
  91.      * @param filePath
  92.      *            file path (with <code>/</code> as separator)
  93.      * @return this command
  94.      */
  95.     public BlameCommand setFilePath(String filePath) {
  96.         this.path = filePath;
  97.         return this;
  98.     }

  99.     /**
  100.      * Set diff algorithm
  101.      *
  102.      * @param diffAlgorithm
  103.      *            a {@link org.eclipse.jgit.diff.DiffAlgorithm} object.
  104.      * @return this command
  105.      */
  106.     public BlameCommand setDiffAlgorithm(DiffAlgorithm diffAlgorithm) {
  107.         this.diffAlgorithm = diffAlgorithm;
  108.         return this;
  109.     }

  110.     /**
  111.      * Set raw text comparator
  112.      *
  113.      * @param textComparator
  114.      *            a {@link org.eclipse.jgit.diff.RawTextComparator}
  115.      * @return this command
  116.      */
  117.     public BlameCommand setTextComparator(RawTextComparator textComparator) {
  118.         this.textComparator = textComparator;
  119.         return this;
  120.     }

  121.     /**
  122.      * Set start commit id
  123.      *
  124.      * @param commit
  125.      *            id of a commit
  126.      * @return this command
  127.      */
  128.     public BlameCommand setStartCommit(AnyObjectId commit) {
  129.         this.startCommit = commit.toObjectId();
  130.         return this;
  131.     }

  132.     /**
  133.      * Enable (or disable) following file renames.
  134.      * <p>
  135.      * If true renames are followed using the standard FollowFilter behavior
  136.      * used by RevWalk (which matches {@code git log --follow} in the C
  137.      * implementation). This is not the same as copy/move detection as
  138.      * implemented by the C implementation's of {@code git blame -M -C}.
  139.      *
  140.      * @param follow
  141.      *            enable following.
  142.      * @return {@code this}
  143.      */
  144.     public BlameCommand setFollowFileRenames(boolean follow) {
  145.         followFileRenames = Boolean.valueOf(follow);
  146.         return this;
  147.     }

  148.     /**
  149.      * Configure the command to compute reverse blame (history of deletes).
  150.      *
  151.      * @param start
  152.      *            oldest commit to traverse from. The result file will be loaded
  153.      *            from this commit's tree.
  154.      * @param end
  155.      *            most recent commit to stop traversal at. Usually an active
  156.      *            branch tip, tag, or HEAD.
  157.      * @return {@code this}
  158.      * @throws java.io.IOException
  159.      *             the repository cannot be read.
  160.      */
  161.     public BlameCommand reverse(AnyObjectId start, AnyObjectId end)
  162.             throws IOException {
  163.         return reverse(start, Collections.singleton(end.toObjectId()));
  164.     }

  165.     /**
  166.      * Configure the generator to compute reverse blame (history of deletes).
  167.      *
  168.      * @param start
  169.      *            oldest commit to traverse from. The result file will be loaded
  170.      *            from this commit's tree.
  171.      * @param end
  172.      *            most recent commits to stop traversal at. Usually an active
  173.      *            branch tip, tag, or HEAD.
  174.      * @return {@code this}
  175.      * @throws java.io.IOException
  176.      *             the repository cannot be read.
  177.      */
  178.     public BlameCommand reverse(AnyObjectId start, Collection<ObjectId> end)
  179.             throws IOException {
  180.         startCommit = start.toObjectId();
  181.         reverseEndCommits = new ArrayList<>(end);
  182.         return this;
  183.     }

  184.     /**
  185.      * {@inheritDoc}
  186.      * <p>
  187.      * Generate a list of lines with information about when the lines were
  188.      * introduced into the file path.
  189.      */
  190.     @Override
  191.     public BlameResult call() throws GitAPIException {
  192.         checkCallable();
  193.         try (BlameGenerator gen = new BlameGenerator(repo, path)) {
  194.             if (diffAlgorithm != null)
  195.                 gen.setDiffAlgorithm(diffAlgorithm);
  196.             if (textComparator != null)
  197.                 gen.setTextComparator(textComparator);
  198.             if (followFileRenames != null)
  199.                 gen.setFollowFileRenames(followFileRenames.booleanValue());

  200.             if (reverseEndCommits != null)
  201.                 gen.reverse(startCommit, reverseEndCommits);
  202.             else if (startCommit != null)
  203.                 gen.push(null, startCommit);
  204.             else {
  205.                 gen.push(null, repo.resolve(Constants.HEAD));
  206.                 if (!repo.isBare()) {
  207.                     DirCache dc = repo.readDirCache();
  208.                     int entry = dc.findEntry(path);
  209.                     if (0 <= entry)
  210.                         gen.push(null, dc.getEntry(entry).getObjectId());

  211.                     File inTree = new File(repo.getWorkTree(), path);
  212.                     if (repo.getFS().isFile(inTree)) {
  213.                         RawText rawText = getRawText(inTree);
  214.                         gen.push(null, rawText);
  215.                     }
  216.                 }
  217.             }
  218.             return gen.computeBlameResult();
  219.         } catch (IOException e) {
  220.             throw new JGitInternalException(e.getMessage(), e);
  221.         }
  222.     }

  223.     private RawText getRawText(File inTree) throws IOException,
  224.             FileNotFoundException {
  225.         RawText rawText;

  226.         WorkingTreeOptions workingTreeOptions = getRepository().getConfig()
  227.                 .get(WorkingTreeOptions.KEY);
  228.         AutoCRLF autoCRLF = workingTreeOptions.getAutoCRLF();
  229.         switch (autoCRLF) {
  230.         case FALSE:
  231.         case INPUT:
  232.             // Git used the repo format on checkout, but other tools
  233.             // may change the format to CRLF. We ignore that here.
  234.             rawText = new RawText(inTree);
  235.             break;
  236.         case TRUE:
  237.             try (AutoLFInputStream in = new AutoLFInputStream(
  238.                     new FileInputStream(inTree), true)) {
  239.                 // Canonicalization should lead to same or shorter length
  240.                 // (CRLF to LF), so the file size on disk is an upper size bound
  241.                 rawText = new RawText(toByteArray(in, (int) inTree.length()));
  242.             }
  243.             break;
  244.         default:
  245.             throw new IllegalArgumentException(
  246.                     "Unknown autocrlf option " + autoCRLF); //$NON-NLS-1$
  247.         }
  248.         return rawText;
  249.     }

  250.     private static byte[] toByteArray(InputStream source, int upperSizeLimit)
  251.             throws IOException {
  252.         byte[] buffer = new byte[upperSizeLimit];
  253.         try {
  254.             int read = IO.readFully(source, buffer, 0);
  255.             if (read == upperSizeLimit)
  256.                 return buffer;
  257.             else {
  258.                 byte[] copy = new byte[read];
  259.                 System.arraycopy(buffer, 0, copy, 0, read);
  260.                 return copy;
  261.             }
  262.         } finally {
  263.             source.close();
  264.         }
  265.     }
  266. }