Search in sources :

Example 6 with DiffFormatter

use of org.eclipse.jgit.diff.DiffFormatter in project gitblit by gitblit.

the class JGitUtils method getFilesInRange.

/**
	 * 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
	 * @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;
}
Also used : PathChangeModel(com.gitblit.models.PathModel.PathChangeModel) ArrayList(java.util.ArrayList) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 7 with DiffFormatter

use of org.eclipse.jgit.diff.DiffFormatter in project gitblit by gitblit.

the class DiffUtils method getDiff.

/**
	 * Returns the diff between two commits for the specified file.
	 *
	 * @param repository
	 * @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);
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) RevWalk(org.eclipse.jgit.revwalk.RevWalk) RevTree(org.eclipse.jgit.revwalk.RevTree) RevCommit(org.eclipse.jgit.revwalk.RevCommit) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 8 with DiffFormatter

use of org.eclipse.jgit.diff.DiffFormatter in project gocd by gocd.

the class ConfigRepository method findDiffBetweenTwoRevisions.

String findDiffBetweenTwoRevisions(RevCommit laterCommit, RevCommit earlierCommit) throws GitAPIException {
    if (laterCommit == null || earlierCommit == null) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String output = null;
    try {
        DiffFormatter diffFormatter = new DiffFormatter(out);
        diffFormatter.setRepository(gitRepo);
        diffFormatter.format(earlierCommit.getId(), laterCommit.getId());
        output = out.toString();
        output = StringUtil.stripTillLastOccurrenceOf(output, "+++ b/cruise-config.xml");
    } catch (IOException e) {
        throw new RuntimeException("Error occurred during diff computation. Message: " + e.getMessage());
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
    }
    return output;
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ConfigFileHasChangedException(com.thoughtworks.go.config.exceptions.ConfigFileHasChangedException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) NullArgumentException(org.apache.commons.lang.NullArgumentException) ConfigMergeException(com.thoughtworks.go.config.exceptions.ConfigMergeException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException)

Example 9 with DiffFormatter

use of org.eclipse.jgit.diff.DiffFormatter in project gerrit by GerritCodeReview.

the class AbstractSubmit method getLatestDiff.

private String getLatestDiff(Repository repo, ObjectId oldTreeId, ObjectId newTreeId) throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (DiffFormatter fmt = new DiffFormatter(out)) {
        fmt.setRepository(repo);
        fmt.format(oldTreeId, newTreeId);
        fmt.flush();
        return out.toString();
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter)

Example 10 with DiffFormatter

use of org.eclipse.jgit.diff.DiffFormatter in project gerrit by GerritCodeReview.

the class GetPatch method apply.

@Override
public BinaryResult apply(RevisionResource rsrc) throws ResourceConflictException, IOException, ResourceNotFoundException {
    Project.NameKey project = rsrc.getControl().getProject().getNameKey();
    final Repository repo = repoManager.openRepository(project);
    boolean close = true;
    try {
        final RevWalk rw = new RevWalk(repo);
        try {
            final RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getPatchSet().getRevision().get()));
            RevCommit[] parents = commit.getParents();
            if (parents.length > 1) {
                throw new ResourceConflictException("Revision has more than 1 parent.");
            } else if (parents.length == 0) {
                throw new ResourceConflictException("Revision has no parent.");
            }
            final RevCommit base = parents[0];
            rw.parseBody(base);
            BinaryResult bin = new BinaryResult() {

                @Override
                public void writeTo(OutputStream out) throws IOException {
                    if (zip) {
                        ZipOutputStream zos = new ZipOutputStream(out);
                        ZipEntry e = new ZipEntry(fileName(rw, commit));
                        e.setTime(commit.getCommitTime() * 1000L);
                        zos.putNextEntry(e);
                        format(zos);
                        zos.closeEntry();
                        zos.finish();
                    } else {
                        format(out);
                    }
                }

                private void format(OutputStream out) throws IOException {
                    // Only add header if no path is specified
                    if (path == null) {
                        out.write(formatEmailHeader(commit).getBytes(UTF_8));
                    }
                    try (DiffFormatter fmt = new DiffFormatter(out)) {
                        fmt.setRepository(repo);
                        if (path != null) {
                            fmt.setPathFilter(PathFilter.create(path));
                        }
                        fmt.format(base.getTree(), commit.getTree());
                        fmt.flush();
                    }
                }

                @Override
                public void close() throws IOException {
                    rw.close();
                    repo.close();
                }
            };
            if (path != null && bin.asString().isEmpty()) {
                throw new ResourceNotFoundException(String.format(FILE_NOT_FOUND, path));
            }
            if (zip) {
                bin.disableGzip().setContentType("application/zip").setAttachmentName(fileName(rw, commit) + ".zip");
            } else {
                bin.base64().setContentType("application/mbox").setAttachmentName(download ? fileName(rw, commit) + ".base64" : null);
            }
            close = false;
            return bin;
        } finally {
            if (close) {
                rw.close();
            }
        }
    } finally {
        if (close) {
            repo.close();
        }
    }
}
Also used : OutputStream(java.io.OutputStream) ZipOutputStream(java.util.zip.ZipOutputStream) ZipEntry(java.util.zip.ZipEntry) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ZipOutputStream(java.util.zip.ZipOutputStream) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult)

Aggregations

DiffFormatter (org.eclipse.jgit.diff.DiffFormatter)13 DiffEntry (org.eclipse.jgit.diff.DiffEntry)7 RevWalk (org.eclipse.jgit.revwalk.RevWalk)6 RevCommit (org.eclipse.jgit.revwalk.RevCommit)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Repository (org.eclipse.jgit.lib.Repository)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 OutputStream (java.io.OutputStream)3 IncorrectObjectTypeException (org.eclipse.jgit.errors.IncorrectObjectTypeException)3 MissingObjectException (org.eclipse.jgit.errors.MissingObjectException)3 RevTree (org.eclipse.jgit.revwalk.RevTree)3 AbstractTreeIterator (org.eclipse.jgit.treewalk.AbstractTreeIterator)3 CanonicalTreeParser (org.eclipse.jgit.treewalk.CanonicalTreeParser)3 AndTreeFilter (org.eclipse.jgit.treewalk.filter.AndTreeFilter)3 TreeFilter (org.eclipse.jgit.treewalk.filter.TreeFilter)3 ObjectReader (org.eclipse.jgit.lib.ObjectReader)2 EmptyTreeIterator (org.eclipse.jgit.treewalk.EmptyTreeIterator)2 TreeWalk (org.eclipse.jgit.treewalk.TreeWalk)2 PathChangeModel (com.gitblit.models.PathModel.PathChangeModel)1