Example usage for org.eclipse.jgit.api Git blame

List of usage examples for org.eclipse.jgit.api Git blame

Introduction

In this page you can find the example usage for org.eclipse.jgit.api Git blame.

Prototype

public BlameCommand blame() 

Source Link

Document

Return a command object to execute a blame command

Usage

From source file:br.com.metricminer2.scm.GitRepository.java

License:Apache License

@Override
public String blame(String file, String currentCommit, Integer line) {
    Git git = null;
    try {// w w w . j a  v a 2  s  .  c  o  m
        git = Git.open(new File(path));

        Iterable<RevCommit> commits = git.log().add(git.getRepository().resolve(currentCommit)).call();
        ObjectId prior = commits.iterator().next().getParent(0).getId();

        BlameResult blameResult = git.blame().setFilePath(file).setStartCommit(prior).setFollowFileRenames(true)
                .call();

        return blameResult.getSourceCommit(line).getId().getName();

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (git != null)
            git.close();
    }

}

From source file:com.chungkwong.jgitgui.StageTreeItem.java

License:Open Source License

@Override
public Node getContentPage() {
    Git git = (Git) getValue();
    GridPane page = new GridPane();
    ListView<String> list = new ListView<String>();
    GridPane.setHgrow(list, Priority.ALWAYS);
    GridPane.setVgrow(list, Priority.ALWAYS);
    list.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    try {/*from   www  .ja  v  a 2 s . c  o m*/
        DirCache cache = ((Git) getValue()).getRepository().readDirCache();
        for (int i = 0; i < cache.getEntryCount(); i++)
            list.getItems().add(cache.getEntry(i).getPathString());
    } catch (Exception ex) {
        Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
        Util.informUser(ex);
    }
    Button remove = new Button(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("REMOVE"));
    remove.setOnAction((e) -> {
        RmCommand command = git.rm().setCached(true);
        list.getSelectionModel().getSelectedItems().stream().forEach((path) -> {
            command.addFilepattern(path);
        });
        list.getItems().removeAll(list.getSelectionModel().getSelectedItems());
        try {
            command.call();
        } catch (Exception ex) {
            Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Util.informUser(ex);
        }
    });
    Button blame = new Button(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME"));
    blame.setOnAction((e) -> {
        Stage dialog = new Stage();
        dialog.setTitle(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("BLAME"));
        StringBuilder buf = new StringBuilder();
        list.getSelectionModel().getSelectedItems().stream().forEach((path) -> {
            try {
                BlameResult command = git.blame().setFilePath(path).call();
                RawText contents = command.getResultContents();
                for (int i = 0; i < contents.size(); i++) {
                    buf.append(command.getSourcePath(i)).append(':');
                    buf.append(command.getSourceLine(i)).append(':');
                    buf.append(command.getSourceCommit(i)).append(':');
                    buf.append(command.getSourceAuthor(i)).append(':');
                    buf.append(contents.getString(i)).append('\n');
                }
            } catch (Exception ex) {
                Logger.getLogger(StageTreeItem.class.getName()).log(Level.SEVERE, null, ex);
                Util.informUser(ex);
            }
        });
        dialog.setScene(new Scene(new TextArea(buf.toString())));
        dialog.setMaximized(true);
        dialog.show();
    });
    page.addColumn(0, list, remove, blame);
    return page;
}

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);/*from  w  ww.  jav  a 2  s .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:org.apache.maven.scm.provider.git.jgit.command.blame.JGitBlameCommand.java

License:Apache License

@Override
public BlameScmResult executeBlameCommand(ScmProviderRepository repo, ScmFileSet workingDirectory,
        String filename) throws ScmException {

    Git git = null;
    File basedir = workingDirectory.getBasedir();
    try {//  w  w w . j av a 2  s . c om
        git = Git.open(basedir);
        BlameResult blameResult = git.blame().setFilePath(filename).call();

        List<BlameLine> lines = new ArrayList<BlameLine>();

        int i = 0;
        while ((i = blameResult.computeNext()) != -1) {
            lines.add(new BlameLine(blameResult.getSourceAuthor(i).getWhen(),
                    blameResult.getSourceCommit(i).getName(), blameResult.getSourceAuthor(i).getName(),
                    blameResult.getSourceCommitter(i).getName()));
        }

        return new BlameScmResult("JGit blame", lines);
    } catch (Exception e) {
        throw new ScmException("JGit blame failure!", e);
    } finally {
        JGitUtils.closeRepo(git);
    }
}

From source file:org.sonar.plugins.scm.git.JGitBlameCommand.java

License:Open Source License

private void blame(BlameOutput output, Git git, File gitBaseDir, InputFile inputFile) throws GitAPIException {
    String filename = pathResolver.relativePath(gitBaseDir, inputFile.file());
    org.eclipse.jgit.blame.BlameResult blameResult = git.blame()
            // Equivalent to -w command line option
            .setTextComparator(RawTextComparator.WS_IGNORE_ALL).setFilePath(filename).call();
    List<BlameLine> lines = new ArrayList<BlameLine>();
    for (int i = 0; i < blameResult.getResultContents().size(); i++) {
        if (blameResult.getSourceAuthor(i) == null || blameResult.getSourceCommit(i) == null) {
            LOG.info("Author: " + blameResult.getSourceAuthor(i));
            LOG.info("Source commit: " + blameResult.getSourceCommit(i));
            throw new IllegalStateException("Unable to blame file " + inputFile.relativePath()
                    + ". No blame info at line " + (i + 1) + ". Is file commited?");
        }/*from  w ww. j  a v  a 2 s  .  c o m*/
        lines.add(new org.sonar.api.batch.scm.BlameLine().date(blameResult.getSourceAuthor(i).getWhen())
                .revision(blameResult.getSourceCommit(i).getName())
                .author(blameResult.getSourceAuthor(i).getEmailAddress()));
    }
    if (lines.size() == inputFile.lines() - 1) {
        // SONARPLUGINS-3097 Git do not report blame on last empty line
        lines.add(lines.get(lines.size() - 1));
    }
    output.blameResult(inputFile, lines);
}

From source file:org.sonarsource.scm.git.JGitBlameCommand.java

License:Open Source License

private void blame(BlameOutput output, Git git, File gitBaseDir, InputFile inputFile) throws GitAPIException {
    String filename = pathResolver.relativePath(gitBaseDir, inputFile.file());
    LOG.debug("Blame file {}", filename);
    org.eclipse.jgit.blame.BlameResult blameResult;
    try {// w  w  w .ja  va  2  s.c o  m
        blameResult = git.blame()
                // Equivalent to -w command line option
                .setTextComparator(RawTextComparator.WS_IGNORE_ALL).setFilePath(filename).call();
    } catch (Exception e) {
        throw new IllegalStateException("Unable to blame file " + inputFile.relativePath(), e);
    }
    List<BlameLine> lines = new ArrayList<>();
    if (blameResult == null) {
        LOG.debug("Unable to blame file {}. It is probably a symlink.", inputFile.relativePath());
        return;
    }
    for (int i = 0; i < blameResult.getResultContents().size(); i++) {
        if (blameResult.getSourceAuthor(i) == null || blameResult.getSourceCommit(i) == null) {
            LOG.debug(
                    "Unable to blame file {}. No blame info at line {}. Is file committed? [Author: {} Source commit: {}]",
                    inputFile.relativePath(), i + 1, blameResult.getSourceAuthor(i),
                    blameResult.getSourceCommit(i));
            return;
        }
        lines.add(new org.sonar.api.batch.scm.BlameLine().date(blameResult.getSourceCommitter(i).getWhen())
                .revision(blameResult.getSourceCommit(i).getName())
                .author(blameResult.getSourceAuthor(i).getEmailAddress()));
    }
    if (lines.size() == inputFile.lines() - 1) {
        // SONARPLUGINS-3097 Git do not report blame on last empty line
        lines.add(lines.get(lines.size() - 1));
    }
    output.blameResult(inputFile, lines);
}