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

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

Introduction

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

Prototype

public void setPathFilter(TreeFilter filter) 

Source Link

Document

Set the filter to produce only specific paths.

Usage

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 {/*w  ww.j a va  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();
    }
}

From source file:com.tenxdev.ovcs.command.DiffCommand.java

License:Open Source License

/**
 * {@inheritDoc}/*  w  ww  .  ja v a2s.co  m*/
 */
@Override
public void execute(final String... args) throws OvcsException {
    if (args.length != 1 && args.length != 2) {
        throw new UsageException(USAGE);
    }
    String targetObject = null;
    if (args.length == 2) {
        targetObject = args[1].toUpperCase(Locale.getDefault());
        if (!targetObject.toLowerCase(Locale.getDefault()).endsWith(".sql")) {
            targetObject = targetObject + ".sql";
        }
    }
    final FileRepository fileRepository = getRepoForCurrentDir();
    try {
        writeChanges(fileRepository);
        final DiffFormatter formatter = new DiffFormatter(System.out);
        formatter.setNewPrefix("new/");
        formatter.setOldPrefix("old/");
        formatter.setRepository(fileRepository);
        if (targetObject != null) {
            formatter.setPathFilter(PathFilter.create(targetObject));
        }
        final AbstractTreeIterator commitTreeIterator = GitUtils.prepareHeadTreeParser(fileRepository);
        final FileTreeIterator workTreeIterator = new FileTreeIterator(fileRepository);
        final List<DiffEntry> diffEntries = formatter.scan(commitTreeIterator, workTreeIterator);

        for (final DiffEntry entry : diffEntries) {
            System.out.println("Entry: " + entry);
            formatter.format(entry);
        }
    } catch (final IOException e) {
        throw new OvcsException("Unable to generate diff: " + e.getMessage(), e);
    } finally {
        fileRepository.close();
    }
}

From source file:elegit.DiffHelper.java

License:Open Source License

private String getDiffString() throws GitAPIException, IOException {
    ObjectId head = this.repo.resolve("HEAD");
    if (head == null)
        return "";

    // The following code is largely written by Tk421 on StackOverflow
    //      (http://stackoverflow.com/q/23486483)
    // Thanks! NOTE: comments are mine.
    ByteArrayOutputStream diffOutputStream = new ByteArrayOutputStream();
    DiffFormatter formatter = new DiffFormatter(diffOutputStream);
    formatter.setRepository(this.repo);
    formatter.setPathFilter(PathFilter.create(this.pathFilter.replaceAll("\\\\", "/")));

    AbstractTreeIterator commitTreeIterator = prepareTreeParser(this.repo, head.getName());
    FileTreeIterator workTreeIterator = new FileTreeIterator(this.repo);

    // Scan gets difference between the two iterators.
    formatter.format(commitTreeIterator, workTreeIterator);

    return diffOutputStream.toString();
}

From source file:info.plichta.maven.plugins.changelog.RepositoryProcessor.java

License:Apache License

private boolean isInPath(Repository repository, RevWalk walk, RevCommit commit) throws IOException {
    if (commit.getParentCount() == 0) {
        RevTree tree = commit.getTree();
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(tree);//from   w  w w.j a  va  2 s .  c om
            treeWalk.setRecursive(true);
            treeWalk.setFilter(pathFilter);
            return treeWalk.next();
        }
    } else {
        DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
        df.setRepository(repository);
        df.setPathFilter(pathFilter);
        RevCommit parent = walk.parseCommit(commit.getParent(0).getId());
        List<DiffEntry> diffs = df.scan(parent.getTree(), commit.getTree());
        return !diffs.isEmpty();
    }
}

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

License:Open Source License

@Override
public final void writeTo(OutputStream out) throws IOException {
    DiffFormatter formatter = new DiffFormatter(new BufferedOutputStream(out));
    formatter.setRepository(repository);
    List<String> rawFileFilter = request.getFileFilter();
    TreeFilter pathFilter = (rawFileFilter != null && rawFileFilter.size() > 0)
            ? PathFilterGroup.createFromStrings(rawFileFilter)
            : TreeFilter.ALL;//ww w.  j av a  2 s .  c o  m
    formatter.setPathFilter(AndTreeFilter.create(TreeFilter.ANY_DIFF, pathFilter));

    try {
        String commitA = request.getCommitA();
        String commitB = request.getCommitB();
        boolean cached = request.isCached();

        List<DiffEntry> diff;
        if (commitA == null && commitB == null && !cached) {
            diff = indexToWorkingTree(formatter);
        } else if (commitA != null && commitB == null && !cached) {
            diff = commitToWorkingTree(commitA, formatter);
        } else if (commitB == null) {
            diff = commitToIndex(commitA, formatter);
        } else {
            diff = commitToCommit(commitA, commitB, formatter);
        }

        DiffType type = request.getType();
        if (type == DiffType.NAME_ONLY) {
            writeNames(diff, out);
        } else if (type == DiffType.NAME_STATUS) {
            writeNamesAndStatus(diff, out);
        } else {
            writeRawDiff(diff, formatter);
        }
    } finally {
        formatter.close();
        repository.close();
    }
}

From source file:org.eclipse.egit.core.op.CreatePatchOperation.java

License:Open Source License

public void execute(IProgressMonitor monitor) throws CoreException {
    EclipseGitProgressTransformer gitMonitor;
    if (monitor == null)
        gitMonitor = new EclipseGitProgressTransformer(new NullProgressMonitor());
    else/*from ww w  . j  a  v a2s .  c o m*/
        gitMonitor = new EclipseGitProgressTransformer(monitor);

    final StringBuilder sb = new StringBuilder();
    final DiffFormatter diffFmt = new DiffFormatter(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();
        }
    }) {
        private IProject project;

        @Override
        public void format(DiffEntry ent) throws IOException, CorruptObjectException, MissingObjectException {
            // for "workspace patches" add project header each time project changes
            if (DiffHeaderFormat.WORKSPACE == headerFormat) {
                IProject p = getProject(ent);
                if (!p.equals(project)) {
                    project = p;
                    getOutputStream().write(encodeASCII("#P " + project.getName() + "\n")); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }
            super.format(ent);
        }
    };

    diffFmt.setProgressMonitor(gitMonitor);
    diffFmt.setContext(contextLines);

    if (headerFormat != null && headerFormat != DiffHeaderFormat.NONE)
        writeGitPatchHeader(sb);

    diffFmt.setRepository(repository);
    diffFmt.setPathFilter(pathFilter);

    try {
        if (commit != null) {
            RevCommit[] parents = commit.getParents();
            if (parents.length > 1)
                throw new IllegalStateException(CoreText.CreatePatchOperation_cannotCreatePatchForMergeCommit);
            if (parents.length == 0)
                throw new IllegalStateException(CoreText.CreatePatchOperation_cannotCreatePatchForFirstCommit);

            List<DiffEntry> diffs = diffFmt.scan(parents[0].getId(), commit.getId());
            for (DiffEntry ent : diffs) {
                String path;
                if (ChangeType.DELETE.equals(ent.getChangeType()))
                    path = ent.getOldPath();
                else
                    path = ent.getNewPath();
                currentEncoding = CompareCoreUtils.getResourceEncoding(repository, path);
                diffFmt.format(ent);
            }
        } else
            diffFmt.format(new DirCacheIterator(repository.readDirCache()), new FileTreeIterator(repository));
    } catch (IOException e) {
        Activator.logError(CoreText.CreatePatchOperation_patchFileCouldNotBeWritten, e);
    }

    if (DiffHeaderFormat.WORKSPACE == headerFormat)
        updateWorkspacePatchPrefixes(sb, diffFmt);

    // trim newline
    if (sb.charAt(sb.length() - 1) == '\n')
        sb.setLength(sb.length() - 1);

    patchContent = sb.toString();
}

From source file:org.eclipse.orion.server.gerritfs.DiffCommand.java

License:Eclipse Distribution License

/**
 * Executes the {@code Diff} command with all the options and parameters collected by the setter methods (e.g. {@link #setCached(boolean)} of this class.
 * Each instance of this class should only be used for one invocation of the command. Don't call this method twice on an instance.
 *
 * @return a DiffEntry for each path which is different
 *///from  w  ww . j  av a 2 s. co m
@Override
public List<DiffEntry> call() throws GitAPIException {
    final DiffFormatter diffFmt;
    if (out != null && !showNameAndStatusOnly)
        diffFmt = new DiffFormatter(new BufferedOutputStream(out));
    else
        diffFmt = new DiffFormatter(NullOutputStream.INSTANCE);
    if (ignoreWS)
        diffFmt.setDiffComparator(RawTextComparator.WS_IGNORE_ALL);
    diffFmt.setRepository(repo);
    diffFmt.setProgressMonitor(monitor);
    try {
        if (cached) {
            if (oldTree == null) {
                ObjectId head = repo.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
                if (head == null)
                    throw new NoHeadException(JGitText.get().cannotReadTree);
                CanonicalTreeParser p = new CanonicalTreeParser();
                ObjectReader reader = repo.newObjectReader();
                try {
                    p.reset(reader, head);
                } finally {
                    reader.release();
                }
                oldTree = p;
            }
            newTree = new DirCacheIterator(repo.readDirCache());
        } else {
            if (oldTree == null)
                oldTree = new DirCacheIterator(repo.readDirCache());
            if (newTree == null)
                newTree = new FileTreeIterator(repo);
        }

        diffFmt.setPathFilter(pathFilter);

        List<DiffEntry> result = diffFmt.scan(oldTree, newTree);
        if (showNameAndStatusOnly)
            return result;
        else {
            if (contextLines >= 0)
                diffFmt.setContext(contextLines);
            if (destinationPrefix != null)
                diffFmt.setNewPrefix(destinationPrefix);
            if (sourcePrefix != null)
                diffFmt.setOldPrefix(sourcePrefix);
            diffFmt.format(result);
            diffFmt.flush();
            return result;
        }
    } catch (IOException e) {
        throw new JGitInternalException(e.getMessage(), e);
    } finally {
        diffFmt.release();
    }
}

From source file:org.gitistics.visitor.commit.TreeWalkVisitorStandard.java

License:Open Source License

public void visit(RevCommit commit) {
    if (commit.getParentCount() == 0)
        return;//from ww  w . ja va2  s  .c  o  m

    DiffFormatter formatter = new DiffFormatter(DisabledOutputStream.INSTANCE);
    formatter.setRepository(repository);
    formatter.setDiffComparator(RawTextComparator.DEFAULT);
    formatter.setDetectRenames(true);

    formatter.setPathFilter(new RawPathFilter(getRawBytes(commit)));
    try {
        FileChanges changes = new FileChanges(commit);
        for (RevCommit parent : commit.getParents()) {
            List<DiffEntry> entries = diffCommitWithParent(formatter, commit, parent);
            for (DiffEntry e : entries) {
                String path = getPath(e);
                try {
                    log.debug("processing {}", path);
                    FileChange change = changes.getChange(path);
                    if (change == null) {
                        change = new FileChange();
                        change.setPath(path);
                        changes.addChange(path, change);
                    }
                    change.setCommit(commit);
                    FileEdits edits = getEdits(formatter, commit, e);
                    edits.setParent(parent);
                    change.addEdit(edits);
                } catch (Throwable t) {
                    log.error("unable to process {} for commit {}", path, commit.getId().getName());
                }
            }
        }
        callback(changes);
    } finally {
        formatter.release();
    }
}

From source file:org.nuxeo.lang.ext.LangExtAssistantRoot.java

License:Open Source License

private String getRepoDiff(String languageKey) throws NoWorkTreeException, CorruptObjectException, IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    String filePath = CLASSES_FOLDER_PATH + "messages_" + languageKey + ".properties";

    DiffFormatter df = new DiffFormatter(out);
    df.setRepository(localRepo);/*from   w  ww  .j  a v a 2  s.c om*/
    df.setPathFilter(PathFilterGroup.createFromStrings(filePath));
    DirCacheIterator oldTree = new DirCacheIterator(localRepo.readDirCache());

    FileTreeIterator newTree = new FileTreeIterator(localRepo);

    df.format(oldTree, newTree);
    df.flush();
    df.release();
    String diff = out.toString("utf-8");
    return diff;
}

From source file:org.obiba.git.command.DiffCommand.java

License:Open Source License

private Iterable<DiffEntry> compareDiffTrees(Repository repository,
        DiffCurrentPreviousTreeParsersFactory parsersFactory) throws IOException {

    DiffFormatter diffFormatter = new DiffFormatter(null);
    diffFormatter.setRepository(repository);
    diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
    diffFormatter.setDetectRenames(true);
    if (!Strings.isNullOrEmpty(path)) {
        diffFormatter.setPathFilter(PathFilter.create(path));
    }// w  w  w. j ava 2  s.  c  o  m
    return diffFormatter.scan(parsersFactory.getPreviousCommitParser(),
            parsersFactory.getCurrentCommitParser());
}