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

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

Introduction

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

Prototype

public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b) throws IOException 

Source Link

Document

Determine the differences between two trees.

Usage

From source file:am.ik.categolj3.api.git.GitStore.java

License:Apache License

void syncHead() {
    log.info("Syncing HEAD...");

    ObjectId oldHead = this.currentHead.get();
    ObjectId newHead = this.head();

    try (Repository repository = this.git.getRepository()) {
        DiffFormatter diffFormatter = new DiffFormatter(System.out);
        diffFormatter.setRepository(repository);
        RevWalk walk = new RevWalk(repository);
        try {/*from   w  ww  .  j a v a2  s .c  o  m*/
            RevCommit fromCommit = walk.parseCommit(oldHead);
            RevCommit toCommit = walk.parseCommit(newHead);
            List<DiffEntry> list = diffFormatter.scan(fromCommit.getTree(), toCommit.getTree());

            list.forEach(diff -> {
                log.info("[{}]\tnew={}\told={}", diff.getChangeType(), diff.getNewPath(), diff.getOldPath());
                if (diff.getOldPath() != null) {
                    Path path = Paths
                            .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getOldPath());
                    if (Entry.isPublic(path)) {
                        Long entryId = Entry.parseEntryId(path);
                        log.info("evict Entry({})", entryId);
                        this.entryCache.evict(entryId);
                    }
                }
                if (diff.getNewPath() != null) {
                    Path path = Paths
                            .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getNewPath());
                    this.loadEntry(path).ifPresent(entry -> {
                        log.info("put Entry({})", entry.getEntryId());
                        this.entryCache.put(entry.getEntryId(), entry);
                    });
                }
            });
        } finally {
            walk.dispose();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    this.currentHead.set(newHead);
}

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 av  a  2 s.  c  om
    }

    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:boa.datagen.scm.GitCommit.java

License:Apache License

private void getChangeFiles(final RevCommit parent, final RevCommit rc,
        final HashMap<String, String> rChangedPaths, final HashMap<String, String> rRemovedPaths,
        final HashMap<String, String> rAddedPaths) {
    final DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
    df.setRepository(repository);/*from w  ww .jav a  2  s  .c  o  m*/
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);

    try {
        final AbstractTreeIterator parentIter;
        if (parent == null)
            parentIter = new EmptyTreeIterator();
        else
            parentIter = new CanonicalTreeParser(null, repository.newObjectReader(), parent.getTree());

        for (final DiffEntry diff : df.scan(parentIter,
                new CanonicalTreeParser(null, repository.newObjectReader(), rc.getTree()))) {
            if (diff.getChangeType() == ChangeType.MODIFY || diff.getChangeType() == ChangeType.COPY
                    || diff.getChangeType() == ChangeType.RENAME) {
                if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB
                        && diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
                    String path = diff.getNewPath();
                    rChangedPaths.put(path, diff.getOldPath());
                    filePathGitObjectIds.put(path, diff.getNewId().toObjectId());
                }
            } else if (diff.getChangeType() == ChangeType.ADD) {
                if (diff.getNewMode().getObjectType() == Constants.OBJ_BLOB) {
                    String path = diff.getNewPath();
                    rAddedPaths.put(path, null);
                    filePathGitObjectIds.put(path, diff.getNewId().toObjectId());
                }
            } else if (diff.getChangeType() == ChangeType.DELETE) {
                if (diff.getOldMode().getObjectType() == Constants.OBJ_BLOB) {
                    rRemovedPaths.put(diff.getOldPath(), diff.getOldPath());
                }
            }
        }
    } catch (final IOException e) {
        if (debug)
            System.err.println("Git Error getting commit diffs: " + e.getMessage());
    }
    df.close();
}

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

License:Apache License

private List<DiffEntry> diffsForTheCommit(Repository repo, RevCommit commit)
        throws IOException, AmbiguousObjectException, IncorrectObjectTypeException {

    AnyObjectId currentCommit = repo.resolve(commit.getName());
    AnyObjectId parentCommit = commit.getParentCount() > 0 ? repo.resolve(commit.getParent(0).getName()) : null;

    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
    df.setBinaryFileThreshold(2 * 1024); // 2 mb max a file
    df.setRepository(repo);/*from  w  ww.  j  av a2 s  .  co  m*/
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);
    List<DiffEntry> diffs = null;

    if (parentCommit == null) {
        RevWalk rw = new RevWalk(repo);
        diffs = df.scan(new EmptyTreeIterator(),
                new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree()));
        rw.release();
    } else {
        diffs = df.scan(parentCommit, currentCommit);
    }

    df.release();

    return diffs;
}

From source file:br.edu.ifpb.scm.api.git.Git.java

private List<DiffEntry> getDiff(String commit, boolean flag) throws IOException {
    ObjectReader reader = git.getRepository().newObjectReader();
    CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
    ObjectId oldTree = git.getRepository().resolve(commit + "^{tree}"); // equals newCommit.getTree()
    oldTreeIter.reset(reader, oldTree);/*from  w  ww  .  j av  a 2  s.  c o  m*/
    ObjectId newTree = null;
    if (flag) {
        newTree = git.getRepository().resolve(commit + HEAD); // equals oldCommit.getTree()
    } else {
        newTree = git.getRepository().resolve(commit + HEAD_NEIGHBOR); // equals oldCommit.getTree()
    }

    DiffFormatter formatter = new DiffFormatter(System.out);
    formatter.setRepository(git.getRepository());
    List<DiffEntry> scan = formatter.scan(oldTree, newTree);

    return scan;
}

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  av a  2  s. c  o 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.GitAnalytics.CommitInfo.java

private CommitInfo(DiffFormatter df, RevWalk rw, RevCommit commit, List<String> tags) throws Exception {
    System.out.print("Processing Commit: " + I + "\r");
    I++;/*from w w  w . j a v a 2s .  c  o m*/
    mCommit = commit;
    mTags = tags;
    mAuthor = mCommit.getAuthorIdent();
    mLinesChanged = new int[3];

    RevTree parent = null;
    try {
        parent = rw.parseCommit(commit.getParent(0).getId()).getTree();
    } catch (Exception e) {
    }
    //int filesChanged = diffs.size();
    mLinesChanged[0] = mLinesChanged[1] = mLinesChanged[2] = 0;
    for (DiffEntry diff : df.scan(parent, commit.getTree())) {
        for (Edit edit : df.toFileHeader(diff).toEditList()) {
            int del = edit.getEndA() - edit.getBeginA();
            int add = edit.getEndB() - edit.getBeginB();

            if (edit.getType() == Type.REPLACE) {
                mLinesChanged[1] += Math.abs(add - del);
            }

            mLinesChanged[2] += add;
            mLinesChanged[0] += del;
        }
    }
}

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

License:Apache License

/**
 * Returns the diff between two commits for the specified file.
 *
 * @param repository/*  w  ww  . j  a v a2s . c  om*/
 * @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.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Returns the list of files changed in a specified commit. If the
 * repository does not exist or is empty, an empty list is returned.
 *
 * @param repository//from   w  w w .ja  va2  s . c  o  m
 * @param startCommit
 *            earliest commit
 * @param endCommit
 *            most recent commit. if null, HEAD is assumed.
 * @return list of files changed in a commit range
 */
public static List<PathChangeModel> getFilesInRange(Repository repository, RevCommit startCommit,
        RevCommit endCommit) {
    List<PathChangeModel> list = new ArrayList<PathChangeModel>();
    if (!hasCommits(repository)) {
        return list;
    }
    try {
        DiffFormatter df = new DiffFormatter(null);
        df.setRepository(repository);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);

        List<DiffEntry> diffEntries = df.scan(startCommit.getTree(), endCommit.getTree());
        for (DiffEntry diff : diffEntries) {
            PathChangeModel pcm = PathChangeModel.from(diff, endCommit.getName(), repository);
            list.add(pcm);
        }
        Collections.sort(list);
    } catch (Throwable t) {
        error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit);
    }
    return list;
}

From source file:com.google.gitiles.CommitSoyData.java

License:Open Source License

private Object computeDiffTree(RevCommit commit) throws IOException {
    AbstractTreeIterator oldTree;/*from  w  w  w .j  a v a  2  s.com*/
    GitilesView.Builder diffUrl = GitilesView.diff().copyFrom(view).setTreePath("");
    switch (commit.getParentCount()) {
    case 0:
        oldTree = new EmptyTreeIterator();
        diffUrl.setOldRevision(Revision.NULL);
        break;
    case 1:
        oldTree = getTreeIterator(walk, commit.getParent(0));
        diffUrl.setOldRevision(view.getRevision().getName() + "^", commit.getParent(0));
        break;
    default:
        // TODO(dborowitz): handle merges
        return NullData.INSTANCE;
    }
    AbstractTreeIterator newTree = getTreeIterator(walk, commit);

    DiffFormatter diff = new DiffFormatter(NullOutputStream.INSTANCE);
    try {
        diff.setRepository(repo);
        diff.setDetectRenames(true);

        List<Object> result = Lists.newArrayList();
        for (DiffEntry e : diff.scan(oldTree, newTree)) {
            Map<String, Object> entry = Maps.newHashMapWithExpectedSize(5);
            entry.put("path", e.getNewPath());
            entry.put("url", GitilesView.path().copyFrom(view).setTreePath(e.getNewPath()).toUrl());
            entry.put("diffUrl", diffUrl.setAnchor("F" + result.size()).toUrl());
            entry.put("changeType", e.getChangeType().toString());
            if (e.getChangeType() == ChangeType.COPY || e.getChangeType() == ChangeType.RENAME) {
                entry.put("oldPath", e.getOldPath());
            }
            result.add(entry);
        }
        return result;
    } finally {
        diff.release();
    }
}