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

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

Introduction

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

Prototype

public void setDetectRenames(boolean on) 

Source Link

Document

Enable or disable rename detection.

Usage

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 w w. j  a  va  2s  .com
    }

    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   ww  w . jav a2 s  .  com
    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);// w w  w.ja  v  a  2s.c o  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: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  2s.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.GitAnalytics.CommitInfo.java

public static List<CommitInfo> getCommits(Repository repo, Iterable<RevCommit> commits, List<Ref> tags)
        throws Exception {
    List<CommitInfo> list = new LinkedList<>();

    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
    df.setRepository(repo);//from  w  ww .j a  v  a 2s. co  m
    df.setDiffComparator(RawTextComparator.DEFAULT);
    df.setDetectRenames(true);

    RevWalk rw = new RevWalk(repo);

    for (RevCommit commit : commits) {
        List<String> curTags = new LinkedList<>();

        tags.stream().filter((tag) -> (tag.getObjectId().equals(ObjectId.fromString(commit.getName()))))
                .forEachOrdered((tag) -> {
                    curTags.add(tag.getName());
                });

        list.add(new CommitInfo(df, rw, commit, curTags));
    }

    return list;
}

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

License:Apache License

/**
 * Returns the diff between two commits for the specified file.
 *
 * @param repository//from   w ww .  j a va2s  .co 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.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   www  . ja va2  s .  c  om*/
 * @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.gerrit.server.mail.NewChangeSender.java

License:Apache License

/** Show patch set as unified difference.  */
public String getUnifiedDiff() {
    PatchList patchList;/*from  w  ww .j av a 2 s. c  o  m*/
    try {
        patchList = getPatchList();
        if (patchList.getOldId() == null) {
            // Octopus merges are not well supported for diff output by Gerrit.
            // Currently these always have a null oldId in the PatchList.
            return "";
        }
    } catch (PatchListNotAvailableException e) {
        log.error("Cannot format patch", e);
        return "";
    }

    TemporaryBuffer.Heap buf = new TemporaryBuffer.Heap(args.settings.maximumDiffSize);
    DiffFormatter fmt = new DiffFormatter(buf);
    Repository git;
    try {
        git = args.server.openRepository(change.getProject());
    } catch (IOException e) {
        log.error("Cannot open repository to format patch", e);
        return "";
    }
    try {
        fmt.setRepository(git);
        fmt.setDetectRenames(true);
        fmt.format(patchList.getOldId(), patchList.getNewId());
        return RawParseUtils.decode(buf.toByteArray());
    } catch (IOException e) {
        if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
            return "";
        }
        log.error("Cannot format patch", e);
        return "";
    } finally {
        fmt.release();
        git.close();
    }
}

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

License:Open Source License

private Object computeDiffTree(RevCommit commit) throws IOException {
    AbstractTreeIterator oldTree;/*ww  w  .ja v a  2  s .c o  m*/
    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();
    }
}

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

License:Open Source License

private void formatHtmlDiff(OutputStream out, Repository repo, RevWalk walk, AbstractTreeIterator oldTree,
        AbstractTreeIterator newTree, String path) throws IOException {
    DiffFormatter diff = new HtmlDiffFormatter(renderer, out);
    try {/*from   w  w  w . j  av a 2 s. c o m*/
        if (!path.equals("")) {
            diff.setPathFilter(PathFilter.create(path));
        }
        diff.setRepository(repo);
        diff.setDetectRenames(true);
        diff.format(oldTree, newTree);
    } finally {
        diff.release();
    }
}