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

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flush the underlying output stream of this formatter.

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;//  www  .j ava  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: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  a 2s .  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:io.fabric8.collector.git.elasticsearch.CommitDTO.java

License:Apache License

public CommitDTO(Git git, NamespaceName projectNamespaceName, RevCommit commit, String repoUrl, String branch) {
    this.namespace = projectNamespaceName.getNamespace();
    this.app = projectNamespaceName.getName();
    this.repoUrl = repoUrl;
    this.branch = branch;
    this.sha = commit.getId().getName();

    this.author = PersonIdentDTO.newInstance(commit.getAuthorIdent());
    this.committer = PersonIdentDTO.newInstance(commit.getCommitterIdent());
    this.fullMessage = commit.getFullMessage();
    this.name = commit.getName();
    this.commitTime = GitHelpers.getCommitDate(commit);
    this.shortMessage = commit.getShortMessage();

    // TODO how to figure out the number of lines added/removed from DiffEntry + HunkHeader?
    // lets try find out the lines added / updated / deleted for this commit
    try {//  w ww  .j  av  a2 s. co m
        Repository r = git.getRepository();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        DiffFormatter formatter = createDiffFormatter(r, buffer);

        RevCommit baseCommit = null;
        RevTree commitTree = commit.getTree();
        RevTree baseTree;
        if (baseCommit == null) {
            if (commit.getParentCount() > 0) {
                final RevWalk rw = new RevWalk(r);
                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 = formatter.scan(baseTree, commitTree);
        for (DiffEntry diffEntry : diffEntries) {
            formatter.format(diffEntry);

            /*
                            FileHeader fileHeader = formatter.toFileHeader(diffEntry);
                            List<? extends HunkHeader> hunks = fileHeader.getHunks();
                            for (HunkHeader hunk : hunks) {
            // linesAdded += hunk.getOldImage().getLinesAdded();
            // linesRemoved += hunk.getOldImage().getLinesDeleted();
                            }
            */
        }
        // TODO should we store the diff? thats maybe too big?
        formatter.flush();
        String diff = buffer.toString();
        if (diff != null) {
            String[] lines = diff.split("\n");
            for (String line : lines) {
                if (line.length() == 0 || line.startsWith("diff ") || line.startsWith("index ")
                        || line.startsWith("--- ") || line.startsWith("+++ ")) {
                    continue;
                }
                if (line.startsWith("+")) {
                    linesAdded++;
                } else if (line.startsWith("-")) {
                    linesRemoved++;
                }
            }
        }

    } catch (IOException e) {
        LOG.warn("Failed to extract lines changed for " + projectNamespaceName + " branch: " + branch
                + " commit: " + sha + ". " + e, e);
    }
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected String doDiff(Git git, String objectId, String baseObjectId, String pathOrBlobPath)
        throws IOException {
    Repository r = git.getRepository();// ww  w . jav a  2s  .c  om
    String blobPath = trimLeadingSlash(pathOrBlobPath);

    RevCommit commit;
    if (Strings.isNotBlank(objectId)) {
        commit = CommitUtils.getCommit(r, objectId);
    } else {
        commit = CommitUtils.getHead(r);
    }
    RevCommit baseCommit = null;
    if (Strings.isNotBlank(baseObjectId) && !Objects.equals(baseObjectId, objectId)) {
        baseCommit = CommitUtils.getCommit(r, baseObjectId);
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    DiffFormatter formatter = createDiffFormatter(r, buffer);

    RevTree commitTree = commit.getTree();
    RevTree baseTree;
    if (baseCommit == null) {
        if (commit.getParentCount() > 0) {
            final RevWalk rw = new RevWalk(r);
            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 = formatter.scan(baseTree, commitTree);
    if (blobPath != null && blobPath.length() > 0) {
        for (DiffEntry diffEntry : diffEntries) {
            if (diffEntry.getNewPath().equalsIgnoreCase(blobPath)) {
                formatter.format(diffEntry);
                break;
            }
        }
    } else {
        formatter.format(diffEntries);
    }
    formatter.flush();
    return buffer.toString();
}

From source file:io.fabric8.forge.rest.git.RepositoryResource.java

License:Apache License

protected CommitDetail doCommitDetail(Git git, String commitId) throws IOException {
    RevCommit baseCommit = doGetCommit(git, commitId);
    if (baseCommit == null) {
        return null;
    } else {/*from  w w w  . j a  v  a 2 s.c o  m*/
        List<DiffInfo> diffs = new ArrayList<>();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        Repository r = git.getRepository();
        DiffFormatter formatter = createDiffFormatter(r, buffer);

        //git.diff().setNewTree()
        RevTree commitTree = baseCommit.getTree();
        RevTree baseTree = null;
        ObjectId parentId = null;
        if (baseCommit.getParentCount() > 0) {
            final RevWalk rw = new RevWalk(r);
            parentId = baseCommit.getParent(0).getId();
            RevCommit parent = rw.parseCommit(parentId);
            baseTree = parent.getTree();
            rw.dispose();

        } else {
            // FIXME initial commit. no parent?!
            baseTree = commitTree;
        }
        if (baseTree == null) {
            baseTree = baseCommit.getTree();
        }

        List<DiffEntry> diffEntries = formatter.scan(baseTree, commitTree);
        if (diffEntries.isEmpty()) {
            // lets try get the previous commit
            String previousCommit = commitId + "~1";
            ObjectId resolve = r.resolve(previousCommit);
            RevTree newTree = null;
            if (resolve != null) {
                final RevWalk rw = new RevWalk(r);
                RevCommit parent = rw.parseCommit(resolve);
                newTree = parent.getTree();
                rw.dispose();
            }
            if (baseTree == null || newTree == null || !Objects.equals(baseTree.getId(), newTree.getId())) {
                diffEntries = formatter.scan(newTree, commitTree);
            }
        }
        for (DiffEntry diffEntry : diffEntries) {
            formatter.format(diffEntry);
            formatter.flush();
            String diff = buffer.toString();
            buffer.reset();
            DiffInfo diffInfo = createDiffInfo(diffEntry, diff);
            diffs.add(diffInfo);
        }
        CommitInfo commitInfo = createCommitInfo(baseCommit);
        return new CommitDetail(commitInfo, diffs);
    }

}

From source file:io.hawt.git.GitFacadeSupport.java

License:Apache License

protected String doDiff(Git git, String objectId, String baseObjectId, String pathOrBlobPath) {
    Repository r = git.getRepository();/*from   ww w  .j  av  a2  s. c o  m*/
    String blobPath = trimLeadingSlash(pathOrBlobPath);
    /*
            RevCommit commit = JGitUtils.getCommit(r, objectId);
            
            ObjectId current;
            if (isNotBlank(objectId)) {
    current = BlobUtils.getId(r, objectId, blobPath);
            } else {
    current = CommitUtils.getHead(r).getId();
            }
            ObjectId previous;
            if (isNotBlank(baseObjectId)) {
    previous = BlobUtils.getId(r, baseObjectId, blobPath);
            } else {
    RevCommit revCommit = CommitUtils.getCommit(r, current);
    RevCommit[] parents = revCommit.getParents();
    if (parents.length == 0) {
        throw new IllegalArgumentException("No parent commits!");
    } else {
        previous = parents[0];
    }
            }
            Collection<Edit> changes = BlobUtils.diff(r, previous, current);
            
            // no idea how to format Collection<Edit> :)
            
    */

    RevCommit commit;
    if (Strings.isNotBlank(objectId)) {
        commit = CommitUtils.getCommit(r, objectId);
    } else {
        commit = CommitUtils.getHead(r);
    }
    RevCommit baseCommit = null;
    if (Strings.isNotBlank(baseObjectId)) {
        baseCommit = CommitUtils.getCommit(r, baseObjectId);
    }

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    RawTextComparator cmp = RawTextComparator.DEFAULT;
    DiffFormatter formatter = new DiffFormatter(buffer);
    formatter.setRepository(r);
    formatter.setDiffComparator(cmp);
    formatter.setDetectRenames(true);

    RevTree commitTree = commit.getTree();
    RevTree baseTree;
    try {
        if (baseCommit == null) {
            if (commit.getParentCount() > 0) {
                final RevWalk rw = new RevWalk(r);
                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 = formatter.scan(baseTree, commitTree);
        if (blobPath != null && blobPath.length() > 0) {
            for (DiffEntry diffEntry : diffEntries) {
                if (diffEntry.getNewPath().equalsIgnoreCase(blobPath)) {
                    formatter.format(diffEntry);
                    break;
                }
            }
        } else {
            formatter.format(diffEntries);
        }
        formatter.flush();
        return buffer.toString();
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
}

From source file:org.eclipse.che.git.impl.jgit.JGitDiffPage.java

License:Open Source License

private void writeRawDiff(List<DiffEntry> diff, DiffFormatter formatter) throws IOException {
    formatter.format(diff);/*from  w ww . j  a  v  a 2 s .c om*/
    formatter.flush();
}

From source file:org.eclipse.egit.ui.internal.history.CommitInfoBuilder.java

License:Open Source License

private void buildDiffs(final StringBuilder d, final List<StyleRange> styles, IProgressMonitor monitor,
        boolean trace) throws OperationCanceledException, IOException {

    // the encoding for the currently processed file
    final String[] currentEncoding = new String[1];

    if (trace)//from w  w w  . j av  a2  s  .  c o m
        GitTraceLocation.getTrace().traceEntry(GitTraceLocation.HISTORYVIEW.getLocation());
    if (commit.getParentCount() > 1) {
        d.append(UIText.CommitMessageViewer_CanNotRenderDiffMessage);
        return;
    }

    try {
        monitor.beginTask(UIText.CommitMessageViewer_BuildDiffListTaskName, currentDiffs.size());
        BufferedOutputStream bos = new SafeBufferedOutputStream(new ByteArrayOutputStream() {
            @Override
            public synchronized void write(byte[] b, int off, int len) {
                super.write(b, off, len);
                if (currentEncoding[0] == null)
                    d.append(toString());
                else
                    try {
                        d.append(toString(currentEncoding[0]));
                    } catch (UnsupportedEncodingException e) {
                        d.append(toString());
                    }
                reset();
            }

        });
        final DiffFormatter diffFmt = new MessageViewerFormatter(bos, styles, d, hunkheaderColor,
                linesAddedColor, linesRemovedColor);

        for (FileDiff currentDiff : currentDiffs) {
            if (monitor.isCanceled())
                throw new OperationCanceledException();
            if (currentDiff.getBlobs().length == 2) {
                String path = currentDiff.getPath();
                monitor.setTaskName(NLS.bind(UIText.CommitMessageViewer_BuildDiffTaskName, path));
                currentEncoding[0] = CompareCoreUtils.getResourceEncoding(db, path);
                d.append(formatPathLine(path)).append(LF);
                currentDiff.outputDiff(d, db, diffFmt, true);
                diffFmt.flush();
            }
            monitor.worked(1);
        }

    } finally {
        monitor.done();
        if (trace)
            GitTraceLocation.getTrace().traceExit(GitTraceLocation.HISTORYVIEW.getLocation());
    }
}

From source file:org.eclipse.egit.ui.internal.history.CommitMessageViewer.java

License:Open Source License

private void addDiff(final StringBuilder d, final ArrayList<StyleRange> styles) {
    final DiffFormatter diffFmt = new DiffFormatter(new BufferedOutputStream(new ByteArrayOutputStream() {

        @Override/*from  w w  w  . jav  a2s.c o m*/
        public synchronized void write(byte[] b, int off, int len) {
            super.write(b, off, len);
            if (currentEncoding == null)
                d.append(toString());

            else
                try {
                    d.append(toString(currentEncoding));
                } catch (UnsupportedEncodingException e) {
                    d.append(toString());
                }
            reset();
        }

    })) {
        @Override
        protected void writeHunkHeader(int aCur, int aEnd, int bCur, int bEnd) throws IOException {
            flush();
            int start = d.length();
            super.writeHunkHeader(aCur, aEnd, bCur, bEnd);
            flush();
            int end = d.length();
            styles.add(new StyleRange(start, end - start, sys_hunkHeaderColor, null));
        }

        @Override
        protected void writeAddedLine(RawText b, int bCur) throws IOException {
            flush();
            int start = d.length();
            super.writeAddedLine(b, bCur);
            flush();
            int end = d.length();
            styles.add(new StyleRange(start, end - start, sys_linesAddedColor, null));
        }

        @Override
        protected void writeRemovedLine(RawText b, int bCur) throws IOException {
            flush();
            int start = d.length();
            super.writeRemovedLine(b, bCur);
            flush();
            int end = d.length();
            styles.add(new StyleRange(start, end - start, sys_linesRemovedColor, null));
        }
    };

    if (commit.getParentCount() > 1)
        return;
    try {
        FileDiff[] diffs = FileDiff.compute(walker, commit);

        for (FileDiff diff : diffs) {
            if (diff.getBlobs().length == 2) {
                String path = diff.getPath();
                currentEncoding = CompareUtils.getResourceEncoding(db, path);
                d.append(formatPathLine(path)).append("\n"); //$NON-NLS-1$
                diff.outputDiff(d, db, diffFmt, true);
                diffFmt.flush();
            }
        }
    } catch (IOException e) {
        Activator.handleError(NLS.bind(UIText.CommitMessageViewer_errorGettingFileDifference, commit.getId()),
                e, false);
    }
}

From source file:org.eclipse.egit.ui.internal.history.GitCreatePatchWizard.java

License:Open Source License

@Override
public boolean performFinish() {
    final boolean isGit = optionsPage.gitFormat.getSelection();
    final boolean isFile = locationPage.fsRadio.getSelection();
    final String fileName = locationPage.fsPathText.getText();

    try {//from  w w w  . j  a  v  a2s.  c  o m
        getContainer().run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                final StringBuilder sb = new StringBuilder();
                final DiffFormatter diffFmt = new DiffFormatter(
                        new BufferedOutputStream(new ByteArrayOutputStream() {

                            @Override
                            public synchronized void write(byte[] b, int off, int len) {
                                super.write(b, off, len);
                                if (currentEncoding == null)
                                    sb.append(toString());
                                else
                                    try {
                                        sb.append(toString(currentEncoding));
                                    } catch (UnsupportedEncodingException e) {
                                        sb.append(toString());
                                    }
                                reset();
                            }

                        }));

                if (isGit)
                    writeGitPatchHeader(sb);
                try {
                    FileDiff[] diffs = FileDiff.compute(walker, commit);
                    for (FileDiff diff : diffs) {
                        currentEncoding = CompareUtils.getResourceEncoding(db, diff.getPath());
                        diff.outputDiff(sb, db, diffFmt, isGit);
                        diffFmt.flush();
                    }

                    if (isFile) {
                        Writer output = new BufferedWriter(new FileWriter(fileName));
                        try {
                            // FileWriter always assumes default encoding is
                            // OK!
                            output.write(sb.toString());
                        } finally {
                            output.close();
                        }
                    } else {
                        copyToClipboard(sb.toString());
                    }
                } catch (IOException e) {
                    Activator.logError("Patch file could not be written", e); //$NON-NLS-1$
                }
            }
        });
    } catch (InvocationTargetException e) {
        ((WizardPage) getContainer().getCurrentPage()).setErrorMessage(
                e.getMessage() == null ? e.getMessage() : UIText.GitCreatePatchWizard_InternalError);
        Activator.logError("Patch file was not written", e); //$NON-NLS-1$
        return false;
    } catch (InterruptedException e) {
        Activator.logError("Patch file was not written", e); //$NON-NLS-1$
        return false;
    }
    return true;
}