Example usage for org.eclipse.jgit.api BlameCommand call

List of usage examples for org.eclipse.jgit.api BlameCommand call

Introduction

In this page you can find the example usage for org.eclipse.jgit.api BlameCommand call.

Prototype

@Override
public BlameResult call() throws GitAPIException 

Source Link

Document

Generate a list of lines with information about when the lines were introduced into the file path.

Usage

From source file:br.com.riselabs.cotonet.builder.commands.RecursiveBlame.java

License:Open Source License

private BlameResult blameCommit(RevCommit commitToBlame) throws GitAPIException {
    BlameCommand blamer = new BlameCommand(this.repo);
    ObjectId commitToBlameID = commitToBlame.getId();
    blamer.setStartCommit(commitToBlameID);
    blamer.setFilePath(this.path);
    return blamer.call();
}

From source file:com.buildautomation.jgit.api.ShowBlame.java

License:Apache License

public static void showBlame() throws IOException, GitAPIException {
    // prepare a new test-repository
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        BlameCommand blamer = new BlameCommand(repository);
        ObjectId commitID = repository.resolve("HEAD");
        blamer.setStartCommit(commitID);
        blamer.setFilePath("README.md");
        BlameResult blame = blamer.call();

        // read the number of lines from the commit to not look at changes in the working copy
        int lines = countFiles(repository, commitID, "README.md");
        for (int i = 0; i < lines; i++) {
            RevCommit commit = blame.getSourceCommit(i);
            System.out.println("Line: " + i + ": " + commit);
        }/*  w w  w. j av a  2  s  . co m*/

        System.out.println("Displayed commits responsible for " + lines + " lines of README.md");
    }
}

From source file:com.gitblit.utils.DiffUtils.java

License:Apache License

/**
 * Returns the list of lines in the specified source file annotated with the
 * source commit metadata.//from  ww  w  . j  av  a 2  s  . c  om
 *
 * @param repository
 * @param blobPath
 * @param objectId
 * @return list of annotated lines
 */
public static List<AnnotatedLine> blame(Repository repository, String blobPath, String objectId) {
    List<AnnotatedLine> lines = new ArrayList<AnnotatedLine>();
    try {
        ObjectId object;
        if (StringUtils.isEmpty(objectId)) {
            object = JGitUtils.getDefaultBranch(repository);
        } else {
            object = repository.resolve(objectId);
        }
        BlameCommand blameCommand = new BlameCommand(repository);
        blameCommand.setFilePath(blobPath);
        blameCommand.setStartCommit(object);
        BlameResult blameResult = blameCommand.call();
        RawText rawText = blameResult.getResultContents();
        int length = rawText.size();
        for (int i = 0; i < length; i++) {
            RevCommit commit = blameResult.getSourceCommit(i);
            AnnotatedLine line = new AnnotatedLine(commit, i + 1, rawText.getString(i));
            lines.add(line);
        }
    } catch (Throwable t) {
        LOGGER.error(MessageFormat.format("failed to generate blame for {0} {1}!", blobPath, objectId), t);
    }
    return lines;
}

From source file:com.googlesource.gerrit.plugins.reviewersbyblame.ReviewersByBlame.java

License:Apache License

/**
 * Compute the blame data for the parent, we are not interested in the
 * specific commit but the parent, since we only want to know the last person
 * that edited this specific part of the code.
 *
 * @param entry {@link PatchListEntry}/*from w ww .  ja va  2  s. c  om*/
 * @param commit Parent {@link RevCommit}
 * @return Result of blame computation, null if the computation fails
 */
private BlameResult computeBlame(final PatchListEntry entry, final RevCommit parent) {
    BlameCommand blameCommand = new BlameCommand(repo);
    blameCommand.setStartCommit(parent);
    blameCommand.setFilePath(entry.getNewName());
    try {
        BlameResult blameResult = blameCommand.call();
        blameResult.computeAll();
        return blameResult;
    } catch (GitAPIException ex) {
        log.error("Couldn't execute blame for commit {}", parent.getName(), ex);
    } catch (IOException err) {
        log.error("Error while computing blame for commit {}", parent.getName(), err);
    }
    return null;
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

private List<CodeOwner> getBlameInfo(int codeLinesSize, String repoName, String repoLocations,
        String fileName) {//from  w w w  .j a va 2 s  .  c  o m
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
    try {
        // The / part is required due to centos bug for version 1.1.1
        // This appears to be correct
        String repoLoc = repoLocations + "/" + repoName + "/.git";

        Repository localRepository = new FileRepository(new File(repoLoc));
        BlameCommand blamer = new BlameCommand(localRepository);

        ObjectId commitID = localRepository.resolve("HEAD");

        if (commitID == null) {
            Singleton.getLogger().info("getBlameInfo commitID is null for " + repoLoc + " " + fileName);
            return codeOwners;
        }

        BlameResult blame;

        // Somewhere in here appears to be wrong...
        blamer.setStartCommit(commitID);
        blamer.setFilePath(fileName);
        blame = blamer.call();

        // Hail mary attempt to solve issue on CentOS Attempt to set at all costs
        if (blame == null) { // This one appears to solve the issue so don't remove it
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath(String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }
        if (blame == null) {
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath("/" + String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }

        if (blame == null) {
            Singleton.getLogger().info("getBlameInfo blame is null for " + repoLoc + " " + fileName);
        }

        if (blame != null) {
            // Get all the owners their number of commits and most recent commit
            HashMap<String, CodeOwner> owners = new HashMap<>();
            RevCommit commit;
            PersonIdent authorIdent;

            try {
                for (int i = 0; i < codeLinesSize; i++) {
                    commit = blame.getSourceCommit(i);
                    authorIdent = commit.getAuthorIdent();

                    if (owners.containsKey(authorIdent.getName())) {
                        CodeOwner codeOwner = owners.get(authorIdent.getName());
                        codeOwner.incrementLines();

                        int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                        if (commit.getCommitTime() > timestamp) {
                            codeOwner.setMostRecentUnixCommitTimestamp(commit.getCommitTime());
                        }
                        owners.put(authorIdent.getName(), codeOwner);
                    } else {
                        owners.put(authorIdent.getName(),
                                new CodeOwner(authorIdent.getName(), 1, commit.getCommitTime()));
                    }
                }
            } catch (IndexOutOfBoundsException ex) {
                // Ignore this as its not really a problem or is it?
                Singleton.getLogger()
                        .info("IndexOutOfBoundsException when trying to get blame for " + repoName + fileName);
            }

            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }

    System.gc(); // Try to clean up
    return codeOwners;
}

From source file:com.searchcode.app.jobs.repository.IndexGitRepoJob.java

License:Open Source License

/**
 * Uses the inbuilt git/*from   ww  w.ja  v a 2 s .  c  o m*/
 * TODO this method appears to leak memory like crazy... need to investigate
 * TODO lots of hairy bits in here need tests to capture issues
 */
public List<CodeOwner> getBlameInfo(int codeLinesSize, String repoName, String repoLocations, String fileName) {
    List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize);
    try {
        // The / part is required due to centos bug for version 1.1.1
        // This appears to be correct
        String repoLoc = repoLocations + "/" + repoName + "/.git";

        Repository localRepository = new FileRepository(new File(repoLoc));
        BlameCommand blamer = new BlameCommand(localRepository);

        ObjectId commitID = localRepository.resolve("HEAD");

        if (commitID == null) {
            Singleton.getLogger().info("getBlameInfo commitID is null for " + repoLoc + " " + fileName);
            return codeOwners;
        }

        BlameResult blame;

        // Somewhere in here appears to be wrong...
        blamer.setStartCommit(commitID);
        blamer.setFilePath(fileName);
        blame = blamer.call();

        // Hail mary attempt to solve issue on CentOS Attempt to set at all costs
        if (blame == null) { // This one appears to solve the issue so don't remove it
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath(String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }
        if (blame == null) {
            String[] split = fileName.split("/");
            blamer.setStartCommit(commitID);
            if (split.length != 1) {
                blamer.setFilePath("/" + String.join("/", Arrays.asList(split).subList(1, split.length)));
            }
            blame = blamer.call();
        }

        if (blame == null) {
            Singleton.getLogger().info("getBlameInfo blame is null for " + repoLoc + " " + fileName);
        }

        if (blame != null) {
            // Get all the owners their number of commits and most recent commit
            HashMap<String, CodeOwner> owners = new HashMap<>();
            RevCommit commit;
            PersonIdent authorIdent;

            try {
                for (int i = 0; i < codeLinesSize; i++) {
                    commit = blame.getSourceCommit(i);
                    authorIdent = commit.getAuthorIdent();

                    if (owners.containsKey(authorIdent.getName())) {
                        CodeOwner codeOwner = owners.get(authorIdent.getName());
                        codeOwner.incrementLines();

                        int timestamp = codeOwner.getMostRecentUnixCommitTimestamp();

                        if (commit.getCommitTime() > timestamp) {
                            codeOwner.setMostRecentUnixCommitTimestamp(commit.getCommitTime());
                        }
                        owners.put(authorIdent.getName(), codeOwner);
                    } else {
                        owners.put(authorIdent.getName(),
                                new CodeOwner(authorIdent.getName(), 1, commit.getCommitTime()));
                    }
                }
            } catch (IndexOutOfBoundsException ex) {
                // Ignore this as its not really a problem or is it?
                Singleton.getLogger().info(
                        "IndexOutOfBoundsException when trying to get blame for " + repoName + " " + fileName);
            }

            codeOwners = new ArrayList<>(owners.values());
        }

    } catch (IOException ex) {
        Singleton.getLogger().info("IOException getBlameInfo when trying to get blame for " + repoName + " "
                + fileName + " " + ex.toString());
    } catch (GitAPIException ex) {
        Singleton.getLogger().info("GitAPIException getBlameInfo when trying to get blame for " + repoName + " "
                + fileName + " " + ex.toString());
    } catch (IllegalArgumentException ex) {
        Singleton.getLogger().info("IllegalArgumentException getBlameInfo when trying to get blame for "
                + repoName + " " + fileName + " " + ex.toString());
    }

    System.gc(); // Try to clean up
    return codeOwners;
}

From source file:com.tasktop.c2c.server.scm.service.GitBrowseUtil.java

License:Open Source License

public static Blame getBlame(Repository r, String revision, String path) throws IOException, GitAPIException {

    if (path.startsWith("/")) {
        path = path.substring(1);// w w  w .  j ava2s.  co m
    }

    Git git = new Git(r);

    ObjectId revId = r.resolve(revision);

    BlameCommand bc = git.blame();
    bc.setStartCommit(revId);
    bc.setFilePath(path);
    BlameResult br = bc.call();

    Blame blame = new Blame();
    blame.path = path;
    blame.revision = revision;
    blame.commits = new ArrayList<Commit>();
    blame.lines = new ArrayList<Blame.Line>();

    Map<String, Integer> sha2idx = new HashMap<String, Integer>();

    RawText resultContents = br.getResultContents();

    for (int i = 0; i < br.getResultContents().size(); i++) {

        RevCommit sourceCommit = br.getSourceCommit(i); // XXX should it really be the source commit
        String sha = sourceCommit.getName();
        Integer cIdx = sha2idx.get(sha);
        if (cIdx == null) {
            cIdx = blame.commits.size();
            Commit commit = GitDomain.createCommit(sourceCommit);
            blame.commits.add(commit);
            sha2idx.put(sha, cIdx);
        }

        Blame.Line bl = new Blame.Line();
        bl.commit = cIdx;
        bl.text = resultContents.getString(i);
        blame.lines.add(bl);
    }

    return blame;
}

From source file:edu.nju.cs.inform.jgit.porcelain.ShowBlame.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    // prepare a new test-repository
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        BlameCommand blamer = new BlameCommand(repository);
        ObjectId commitID = repository.resolve("HEAD");
        blamer.setStartCommit(commitID);
        blamer.setFilePath("README.md");
        BlameResult blame = blamer.call();

        // read the number of lines from the commit to not look at changes in the working copy
        int lines = countFiles(repository, commitID, "README.md");
        for (int i = 0; i < lines; i++) {
            RevCommit commit = blame.getSourceCommit(i);
            System.out.println("Line: " + i + ": " + commit);
        }/*  www .  ja v a2s  . c  om*/

        System.out.println("Displayed commits responsible for " + lines + " lines of README.md");
    }
}

From source file:org.dstadler.jgit.porcelain.ShowBlame.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    // prepare a new test-repository
    try (Repository repository = CookbookHelper.openJGitCookbookRepository()) {
        BlameCommand blamer = new BlameCommand(repository);
        ObjectId commitID = repository.resolve("HEAD~~");
        blamer.setStartCommit(commitID);
        blamer.setFilePath("README.md");
        BlameResult blame = blamer.call();

        // read the number of lines from the given revision, this excludes changes from the last two commits due to the "~~" above
        int lines = countLinesOfFileInCommit(repository, commitID, "README.md");
        for (int i = 0; i < lines; i++) {
            RevCommit commit = blame.getSourceCommit(i);
            System.out.println("Line: " + i + ": " + commit);
        }//from   w  ww .  j a v a  2 s.com

        final int currentLines;
        try (final FileInputStream input = new FileInputStream("README.md")) {
            currentLines = IOUtils.readLines(input, "UTF-8").size();
        }

        System.out.println("Displayed commits responsible for " + lines
                + " lines of README.md, current version has " + currentLines + " lines");
    }
}

From source file:org.eclipse.egit.ui.internal.blame.BlameOperation.java

License:Open Source License

public void execute(IProgressMonitor monitor) throws CoreException {
    final RevisionInformation info = new RevisionInformation();
    info.setHoverControlCreator(new BlameInformationControlCreator(false));
    info.setInformationPresenterControlCreator(new BlameInformationControlCreator(true));

    final BlameCommand command = new BlameCommand(repository).setFollowFileRenames(true).setFilePath(path);
    if (startCommit != null)
        command.setStartCommit(startCommit);
    if (Activator.getDefault().getPreferenceStore().getBoolean(UIPreferences.BLAME_IGNORE_WHITESPACE))
        command.setTextComparator(RawTextComparator.WS_IGNORE_ALL);

    BlameResult result;/*from   ww w  .  j ava 2 s  . co  m*/
    try {
        result = command.call();
    } catch (Exception e1) {
        Activator.error(e1.getMessage(), e1);
        return;
    }
    if (result == null)
        return;

    Map<RevCommit, BlameRevision> revisions = new HashMap<RevCommit, BlameRevision>();
    int lineCount = result.getResultContents().size();
    BlameRevision previous = null;
    for (int i = 0; i < lineCount; i++) {
        RevCommit commit = result.getSourceCommit(i);
        if (commit == null) {
            // Unregister the current revision
            if (previous != null) {
                previous.register();
                previous = null;
            }
            continue;
        }
        BlameRevision revision = revisions.get(commit);
        if (revision == null) {
            revision = new BlameRevision();
            revision.setRepository(repository);
            revision.setCommit(commit);
            revisions.put(commit, revision);
            info.addRevision(revision);
        }
        if (previous != null)
            if (previous == revision)
                previous.addLine();
            else {
                previous.register();
                previous = revision.reset(i);
            }
        else
            previous = revision.reset(i);
    }
    if (previous != null)
        previous.register();

    shell.getDisplay().asyncExec(new Runnable() {
        public void run() {
            openEditor(info);
        }
    });
}