Example usage for org.eclipse.jgit.diff RawTextComparator DEFAULT

List of usage examples for org.eclipse.jgit.diff RawTextComparator DEFAULT

Introduction

In this page you can find the example usage for org.eclipse.jgit.diff RawTextComparator DEFAULT.

Prototype

RawTextComparator DEFAULT

To view the source code for org.eclipse.jgit.diff RawTextComparator DEFAULT.

Click Source Link

Document

No special treatment.

Usage

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);//  www  . ja  v  a2 s .  co 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 .  jav 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 a  v a  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.diffplug.gradle.spotless.DiffMessageFormatter.java

License:Apache License

/**
 * Returns a git-style diff between the two unix strings.
 *
 * Output has no trailing newlines./*from   w  ww . ja  v a  2s.  com*/
 *
 * Boolean args determine whether whitespace or line endings will be visible.
 */
private static String diffWhitespaceLineEndings(String dirty, String clean, boolean whitespace,
        boolean lineEndings) throws IOException {
    dirty = visibleWhitespaceLineEndings(dirty, whitespace, lineEndings);
    clean = visibleWhitespaceLineEndings(clean, whitespace, lineEndings);

    RawText a = new RawText(dirty.getBytes(StandardCharsets.UTF_8));
    RawText b = new RawText(clean.getBytes(StandardCharsets.UTF_8));
    EditList edits = new EditList();
    edits.addAll(MyersDiff.INSTANCE.diff(RawTextComparator.DEFAULT, a, b));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (DiffFormatter formatter = new DiffFormatter(out)) {
        formatter.format(edits, a, b);
    }
    String formatted = out.toString(StandardCharsets.UTF_8.name());

    // we don't need the diff to show this, since we display newlines ourselves
    formatted = formatted.replace("\\ No newline at end of file\n", "");
    return NEWLINE_MATCHER.trimTrailingFrom(formatted);
}

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 ww  w  .j  a v  a  2 s  . c o 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 the two commits for the specified file or folder
 * formatted as a patch./*from   w ww .ja va  2 s.  com*/
 *
 * @param repository
 * @param baseCommit
 *            if base commit is unspecified, the patch is generated against
 *            the primary parent of the specified commit.
 * @param commit
 * @param path
 *            if path is specified, the patch is generated only for the
 *            specified file or folder. if unspecified, the patch is
 *            generated for the entire diff between the two commits.
 * @return patch as a string
 */
public static String getCommitPatch(Repository repository, RevCommit baseCommit, RevCommit commit,
        String path) {
    String diff = null;
    try {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        RawTextComparator cmp = RawTextComparator.DEFAULT;
        PatchFormatter df = new PatchFormatter(os);
        df.setRepository(repository);
        df.setDiffComparator(cmp);
        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());
                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);
        }
        diff = df.getPatch(commit);
        df.flush();
    } catch (Throwable t) {
        LOGGER.error("failed to generate commit diff!", t);
    }
    return diff;
}

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

License:Apache License

/**
 * Returns the diffstat between the two commits for the specified file or folder.
 *
 * @param repository//from   w  ww  .  j av a 2  s  . c  om
 * @param baseCommit
 *            if base commit is unspecified, the diffstat is generated against
 *            the primary parent of the specified commit.
 * @param commit
 * @param path
 *            if path is specified, the diffstat is generated only for the
 *            specified file or folder. if unspecified, the diffstat is
 *            generated for the entire diff between the two commits.
 * @return patch as a string
 */
public static DiffStat getDiffStat(Repository repository, RevCommit baseCommit, RevCommit commit, String path) {
    DiffStat stat = null;
    try {
        RawTextComparator cmp = RawTextComparator.DEFAULT;
        DiffStatFormatter df = new DiffStatFormatter(commit.getName(), repository);
        df.setRepository(repository);
        df.setDiffComparator(cmp);
        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());
                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);
        }
        stat = df.getDiffStat();
        df.flush();
    } catch (Throwable t) {
        LOGGER.error("failed to generate commit diff!", t);
    }
    return 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/* w  w  w  . jav a 2s.c  o m*/
 * @param commit
 *            if null, HEAD is assumed.
 * @param calculateDiffStat
 *            if true, each PathChangeModel will have insertions/deletions
 * @return list of files changed in a commit
 */
public static List<PathChangeModel> getFilesInCommit(Repository repository, RevCommit commit,
        boolean calculateDiffStat) {
    List<PathChangeModel> list = new ArrayList<PathChangeModel>();
    if (!hasCommits(repository)) {
        return list;
    }
    RevWalk rw = new RevWalk(repository);
    try {
        if (commit == null) {
            ObjectId object = getDefaultBranch(repository);
            commit = rw.parseCommit(object);
        }

        if (commit.getParentCount() == 0) {
            TreeWalk tw = new TreeWalk(repository);
            tw.reset();
            tw.setRecursive(true);
            tw.addTree(commit.getTree());
            while (tw.next()) {
                long size = 0;
                FilestoreModel filestoreItem = null;
                ObjectId objectId = tw.getObjectId(0);

                try {
                    if (!tw.isSubtree() && (tw.getFileMode(0) != FileMode.GITLINK)) {

                        size = tw.getObjectReader().getObjectSize(objectId, Constants.OBJ_BLOB);

                        if (isPossibleFilestoreItem(size)) {
                            filestoreItem = getFilestoreItem(tw.getObjectReader().open(objectId));
                        }
                    }
                } catch (Throwable t) {
                    error(t, null, "failed to retrieve blob size for " + tw.getPathString());
                }

                list.add(new PathChangeModel(tw.getPathString(), tw.getPathString(), filestoreItem, size,
                        tw.getRawMode(0), objectId.getName(), commit.getId().getName(), ChangeType.ADD));
            }
            tw.close();
        } else {
            RevCommit parent = rw.parseCommit(commit.getParent(0).getId());
            DiffStatFormatter df = new DiffStatFormatter(commit.getName(), repository);
            df.setRepository(repository);
            df.setDiffComparator(RawTextComparator.DEFAULT);
            df.setDetectRenames(true);
            List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
            for (DiffEntry diff : diffs) {
                // create the path change model
                PathChangeModel pcm = PathChangeModel.from(diff, commit.getName(), repository);

                if (calculateDiffStat) {
                    // update file diffstats
                    df.format(diff);
                    PathChangeModel pathStat = df.getDiffStat().getPath(pcm.path);
                    if (pathStat != null) {
                        pcm.insertions = pathStat.insertions;
                        pcm.deletions = pathStat.deletions;
                    }
                }
                list.add(pcm);
            }
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to determine files in commit!");
    } finally {
        rw.dispose();
    }
    return list;
}

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// ww w.  j  a  v a  2 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.github.checkstyle.parser.JgitUtils.java

License:Open Source License

/**
 * Generates the differences between the contents of the 2 files.
 *
 * @param baseFile//  w  w w  .ja  v a 2s.  co  m
 *            The base file to examine.
 * @param patchFile
 *            The patch file to examine.
 * @return The iterator containing the differences.
 * @throws IOException
 *             if Exceptions occur while reading the file.
 */
public static Iterator<JgitDifference> getDifferences(File baseFile, File patchFile) throws IOException {
    if (diffAlgorithm == null) {
        diffAlgorithm = DiffAlgorithm.getAlgorithm(SupportedAlgorithm.HISTOGRAM);
    }

    final RawText baseFileRaw = new RawText(baseFile);
    final RawText patchFileRaw = new RawText(patchFile);

    return new JgitDifferenceIterator(diffAlgorithm.diff(RawTextComparator.DEFAULT, baseFileRaw, patchFileRaw),
            baseFileRaw, patchFileRaw);
}