Example usage for org.eclipse.jgit.diff DiffFormatter format

List of usage examples for org.eclipse.jgit.diff DiffFormatter format

Introduction

In this page you can find the example usage for org.eclipse.jgit.diff DiffFormatter format.

Prototype

private String format(AbbreviatedObjectId id) 

Source Link

Usage

From source file:ShowFileDiff.java

License:Apache License

public static void main(String[] args) throws IOException, GitAPIException {
    Repository repository = null; //CookbookHelper.openJGitCookbookRepository();

    // the diff works on TreeIterators, we prepare two for the two branches
    AbstractTreeIterator oldTreeParser = prepareTreeParser(repository,
            "09c65401f3730eb3e619c33bf31e2376fb393727");
    AbstractTreeIterator newTreeParser = prepareTreeParser(repository,
            "aa31703b65774e4a06010824601e56375a70078c");

    // then the procelain diff-command returns a list of diff entries
    List<DiffEntry> diff = new Git(repository).diff().setOldTree(oldTreeParser).setNewTree(newTreeParser)
            .setPathFilter(PathFilter.create("README.md")).call();
    for (DiffEntry entry : diff) {
        System.out.println("Entry: " + entry + ", from: " + entry.getOldId() + ", to: " + entry.getNewId());
        DiffFormatter formatter = new DiffFormatter(System.out);
        formatter.setRepository(repository);
        formatter.format(entry);
    }/*from   www .j a  v  a  2 s  . c  om*/

    repository.close();
}

From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java

License:Open Source License

private void processDiff(Repository repository, RevWalk walk, RevCommit current, DiffOutputStream outputStream,
        Map<String, FileStats> fileStatsMap) throws IOException {
    assert (repository != null);
    assert (walk != null);
    assert (current != null);
    assert (outputStream != null);
    assert (fileStatsMap != null);

    if (processDiffs == false) {
        return;/*w  ww  .j a va  2 s . c  o m*/
    }

    try {
        DiffFormatter df = new DiffFormatter(outputStream);
        df.setRepository(repository);
        df.setDetectRenames(true);

        List<DiffEntry> entries;
        if (current.getParentCount() > 0) {
            RevCommit parent = current.getParent(0);
            ObjectId oldTree = walk.parseCommit(parent).getTree();
            ObjectId newTree = current.getTree();
            entries = df.scan(oldTree, newTree);
        } else {
            entries = df.scan(new EmptyTreeIterator(),
                    new CanonicalTreeParser(null, walk.getObjectReader(), current.getTree()));
        }

        for (DiffEntry de : entries) {
            if (stopped == true) {
                break;
            }

            int emptyLinesAddedStart = outputStream.getTotalEmptyLinesAdded();
            int emptyLinesRemovedStart = outputStream.getTotalEmptyLinesRemoved();
            int linesAddedStart = outputStream.getTotalLinesAdded();
            int linesRemovedStart = outputStream.getTotalLinesRemoved();
            int chunksStart = outputStream.getTotalChunks();
            String oldPath = null;
            String path = null;

            switch (de.getChangeType()) {
            case ADD:
                path = de.getNewPath();
                break;
            case DELETE:
                path = de.getOldPath();
                break;
            case MODIFY:
                path = de.getOldPath();
                break;
            case COPY:
                oldPath = de.getOldPath();
                path = de.getNewPath();
                break;
            case RENAME:
                oldPath = de.getOldPath();
                path = de.getNewPath();
                break;
            default:
                continue;
            }

            assert (fileStatsMap.containsKey(path) == false);
            assert (path != null);

            FileStats fileStats = new FileStats();
            fileStatsMap.put(path, fileStats);

            outputStream.resetFile();
            df.format(de);
            df.flush();

            fileStats.emptyLinesAdded = outputStream.getTotalEmptyLinesAdded() - emptyLinesAddedStart;
            fileStats.emptyLinesRemoved = outputStream.getTotalEmptyLinesRemoved() - emptyLinesRemovedStart;
            fileStats.linesAdded += outputStream.getTotalLinesAdded() - linesAddedStart;
            fileStats.linesRemoved += outputStream.getTotalLinesRemoved() - linesRemovedStart;
            fileStats.chunks += outputStream.getTotalChunks() - chunksStart;

            fileStats.type = de.getChangeType();
            fileStats.oldPath = oldPath;
        }
    } catch (IOException e) {
        throw e;
    }
}

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

License:Apache License

private String getDiffText(Repository repo, DiffEntry diff) throws IOException, UnsupportedEncodingException {
    DiffFormatter df2 = null;
    try {//from w  ww.j a  v a  2s .c  o m
        String diffText;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        df2 = new DiffFormatter(out);
        df2.setRepository(repo);
        df2.format(diff);
        diffText = out.toString("UTF-8");
        return diffText;
    } catch (Throwable e) {
        return "";
    } finally {
        if (df2 != null)
            df2.release();
    }
}

From source file:br.edu.ifpb.scm.api.loads.Loader.java

public static void showFileDiffs(Git gitRepository) {
    Repository repo = gitRepository.getRepository();

    try {//  ww w  . j a va  2s .  c  o m
        ObjectId head = ObjectId.fromString("c24af304077e4a6d1925db7cd35d0cd1ed488d6a");
        ObjectId previousHead = ObjectId.fromString("c16be41e77bb53a4b639cb864c9a6e4d0f8df7c2");
        ObjectReader reader = repo.newObjectReader();

        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, previousHead);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, head);

        List<DiffEntry> listDiffs = gitRepository.diff().setOldTree(oldTreeIter).setNewTree(newTreeIter).call();

        listDiffs.stream().forEach((DiffEntry diff) -> {

            DiffFormatter formatter = new DiffFormatter(System.out);
            formatter.setRepository(repo);
            System.out.println(diff);
            try {
                formatter.format(diff);
            } catch (IOException ex) {
                Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
    } catch (IOException | GitAPIException ex) {
        Logger.getLogger(Loader.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:co.bledo.gitmin.servlet.Review.java

License:Apache License

public Response commit(Request req) throws IOException, GitAPIException {
    String repoName = req.getParam("repo", "");
    String hash = req.getParam("hash", "");

    Git git = Git.open(new File(GitminConfig.getGitRepositoriesPath() + "/" + repoName));

    /*/*from   w  w  w  . j  a va  2  s.co  m*/
    ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
    List<DiffEntry> diffTest = git.diff().setOutputStream(baos1)
    .setOldTree(getTreeIterator(git.getRepository(), hash))
    .setNewTree(getTreeIterator(git.getRepository(), hash + "^"))
    .call();
    System.out.println(baos1.toString());
    */

    RepositoryBuilder builder = new RepositoryBuilder();
    Repository repo = builder.setGitDir(new File(GitminConfig.getGitRepositoriesPath() + "/" + repoName))
            .readEnvironment().findGitDir().build();

    RevWalk rw = new RevWalk(repo);

    ObjectId hashOid = repo.resolve(hash);

    RevCommit commit = rw.parseCommit(hashOid);
    RevCommit parent = rw.parseCommit(commit.getParent(0).getId());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DiffFormatter df = new DiffFormatter(baos);
    df.setRepository(repo);
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);
    List<DiffEntry> diffs = df.scan(parent, commit);
    List<CommitInfo> commitInfos = new ArrayList<CommitInfo>();
    for (DiffEntry diff : diffs) {

        CommitInfo nfo = new CommitInfo();

        df.format(diff);

        nfo.diff = baos.toString();
        nfo.oldContents = getFileContent(repo, parent, diff.getOldPath());
        nfo.newContents = getFileContent(repo, parent, diff.getNewPath());
        nfo.newFile = diff.getNewPath();
        nfo.oldFile = diff.getOldPath();

        commitInfos.add(nfo);
    }

    VelocityResponse resp = VelocityResponse.newInstance(req, this);
    resp.assign("nfolist", commitInfos);
    return log.exit(resp);
}

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

License:Open Source License

@Override
public Node getContentPage() {
    GridPane page = new GridPane();
    TextField oldSrc = new TextField();
    TextField newSrc = new TextField();
    CheckBox detailed = new CheckBox(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("DETAILED"));
    Button ok = new Button(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("DIFF"));
    TextArea diff = new TextArea();
    diff.setEditable(false);//w w w  .  j av a 2 s.c  o  m
    Git git = ((Git) getParent().getValue());
    GridPane.setVgrow(diff, Priority.ALWAYS);
    GridPane.setHgrow(diff, Priority.ALWAYS);
    GridPane.setHgrow(oldSrc, Priority.ALWAYS);
    GridPane.setHgrow(newSrc, Priority.ALWAYS);
    ok.setOnAction((ActionEvent e) -> {
        try (ObjectReader reader = git.getRepository().newObjectReader()) {
            List<DiffEntry> entries;
            if (oldSrc.getText().isEmpty() && newSrc.getText().isEmpty()) {
                entries = ((Git) getParent().getValue()).diff().setCached(true).call();
            } else {
                CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
                oldTreeIter.reset(reader, git.getRepository().resolve(oldSrc.getText() + "^{tree}"));
                CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
                newTreeIter.reset(reader, git.getRepository().resolve(newSrc.getText() + "^{tree}"));
                entries = ((Git) getParent().getValue()).diff().setNewTree(newTreeIter).setOldTree(oldTreeIter)
                        .call();
            }
            if (detailed.isSelected()) {
                PipedInputStream in = new PipedInputStream();
                PipedOutputStream out = new PipedOutputStream(in);
                DiffFormatter formatter = new DiffFormatter(out);
                formatter.setRepository(git.getRepository());
                formatter.format(entries);
                out.close();
                diff.setText(new BufferedReader(new InputStreamReader(in)).lines()
                        .collect(Collectors.joining("\n")));
            } else {
                diff.setText(entries.stream().map((o) -> toString(o)).collect(Collectors.joining("\n")));
            }
        } catch (Exception ex) {
            Logger.getLogger(LogTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Util.informUser(ex);
        }
    });
    page.addColumn(0, oldSrc, newSrc, detailed, ok, diff);

    page.setMaxSize(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY);
    return page;
}

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

License:Apache License

/**
 * Returns the diff between two commits for the specified file.
 *
 * @param repository/*w  w  w.j av a  2s. c  o m*/
 * @param baseCommit
 *            if base commit is null the diff is to the primary parent of
 *            the commit.
 * @param commit
 * @param path
 *            if the path is specified, the diff is restricted to that file
 *            or folder. if unspecified, the diff is for the entire commit.
 * @param comparator
 * @param outputType
 * @param handler
 *            to use for rendering binary diffs if {@code outputType} is {@link DiffOutputType#HTML HTML}.
 *            May be {@code null}, resulting in the default behavior.
 * @param tabLength
 * @return the diff
 */
public static DiffOutput getDiff(Repository repository, RevCommit baseCommit, RevCommit commit, String path,
        DiffComparator comparator, DiffOutputType outputType, final BinaryDiffHandler handler, int tabLength) {
    DiffStat stat = null;
    String diff = null;
    try {
        ByteArrayOutputStream os = null;

        DiffFormatter df;
        switch (outputType) {
        case HTML:
            df = new GitBlitDiffFormatter(commit.getName(), repository, path, handler, tabLength);
            break;
        case PLAIN:
        default:
            os = new ByteArrayOutputStream();
            df = new DiffFormatter(os);
            break;
        }
        df.setRepository(repository);
        df.setDiffComparator((comparator == null ? DiffComparator.SHOW_WHITESPACE : comparator).textComparator);
        df.setDetectRenames(true);

        RevTree commitTree = commit.getTree();
        RevTree baseTree;
        if (baseCommit == null) {
            if (commit.getParentCount() > 0) {
                final RevWalk rw = new RevWalk(repository);
                RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
                rw.dispose();
                baseTree = parent.getTree();
            } else {
                // FIXME initial commit. no parent?!
                baseTree = commitTree;
            }
        } else {
            baseTree = baseCommit.getTree();
        }

        List<DiffEntry> diffEntries = df.scan(baseTree, commitTree);
        if (path != null && path.length() > 0) {
            for (DiffEntry diffEntry : diffEntries) {
                if (diffEntry.getNewPath().equalsIgnoreCase(path)) {
                    df.format(diffEntry);
                    break;
                }
            }
        } else {
            df.format(diffEntries);
        }
        df.flush();
        if (df instanceof GitBlitDiffFormatter) {
            // workaround for complex private methods in DiffFormatter
            diff = ((GitBlitDiffFormatter) df).getHtml();
            stat = ((GitBlitDiffFormatter) df).getDiffStat();
        } else {
            diff = os.toString();
        }
    } catch (Throwable t) {
        LOGGER.error("failed to generate commit diff!", t);
    }

    return new DiffOutput(outputType, diff, stat);
}

From source file:com.mpdeimos.ct_tests.vcs.GitFileDiff.java

License:Apache License

/**
 * Creates a textual diff together with meta information.
 * TODO So far this works only in case of one parent commit.
 *
 * @param d//from w  w w .j a  v  a  2s. c  o m
 *            the StringBuilder where the textual diff is added to
 * @param db
 *            the Repo
 * @param diffFmt
 *            the DiffFormatter used to create the textual diff
        
 * @throws IOException
 */
public void outputDiff(final StringBuilder d, final Repository db, final DiffFormatter diffFmt)
        throws IOException {
    diffFmt.setRepository(db);
    diffFmt.format(diffEntry);
    return;
}

From source file:com.osbitools.ws.shared.prj.utils.GitUtils.java

License:Open Source License

public static String getDiff(Git git, String base, String name, String ext) throws WsSrvException {
    checkFile(base, name, ext).getAbsolutePath();

    // Prepare path for git save
    String fp = getLocalPath(name);

    List<DiffEntry> diff;/*from www.ja  va2s .  com*/
    try {
        diff = git.diff().setPathFilter(PathFilter.create(fp)).call();
    } catch (GitAPIException e) {
        throw new WsSrvException(260, "Unable retrieve git diff", e);
    }

    ByteArrayOutputStream res = new ByteArrayOutputStream();

    for (DiffEntry entry : diff) {
        DiffFormatter formatter = new DiffFormatter(res);
        formatter.setRepository(git.getRepository());
        try {
            formatter.format(entry);
        } catch (IOException e) {
            throw new WsSrvException(261, "Unable format diff", e);
        }
    }

    return res.toString();
}

From source file:com.tenxdev.ovcs.command.DiffCommand.java

License:Open Source License

/**
 * {@inheritDoc}/*from w  ww. j  a  va2  s .co  m*/
 */
@Override
public void execute(final String... args) throws OvcsException {
    if (args.length != 1 && args.length != 2) {
        throw new UsageException(USAGE);
    }
    String targetObject = null;
    if (args.length == 2) {
        targetObject = args[1].toUpperCase(Locale.getDefault());
        if (!targetObject.toLowerCase(Locale.getDefault()).endsWith(".sql")) {
            targetObject = targetObject + ".sql";
        }
    }
    final FileRepository fileRepository = getRepoForCurrentDir();
    try {
        writeChanges(fileRepository);
        final DiffFormatter formatter = new DiffFormatter(System.out);
        formatter.setNewPrefix("new/");
        formatter.setOldPrefix("old/");
        formatter.setRepository(fileRepository);
        if (targetObject != null) {
            formatter.setPathFilter(PathFilter.create(targetObject));
        }
        final AbstractTreeIterator commitTreeIterator = GitUtils.prepareHeadTreeParser(fileRepository);
        final FileTreeIterator workTreeIterator = new FileTreeIterator(fileRepository);
        final List<DiffEntry> diffEntries = formatter.scan(commitTreeIterator, workTreeIterator);

        for (final DiffEntry entry : diffEntries) {
            System.out.println("Entry: " + entry);
            formatter.format(entry);
        }
    } catch (final IOException e) {
        throw new OvcsException("Unable to generate diff: " + e.getMessage(), e);
    } finally {
        fileRepository.close();
    }
}