Example usage for org.eclipse.jgit.treewalk.filter OrTreeFilter create

List of usage examples for org.eclipse.jgit.treewalk.filter OrTreeFilter create

Introduction

In this page you can find the example usage for org.eclipse.jgit.treewalk.filter OrTreeFilter create.

Prototype

public static TreeFilter create(Collection<TreeFilter> list) 

Source Link

Document

Create a filter around many filters, one of which must match.

Usage

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

License:Apache License

/**
 * Returns the list of files in the repository in the specified commit that
 * match one of the specified extensions. This is a CASE-SENSITIVE search.
 * If the repository does not exist or is empty, an empty list is returned.
 *
 * @param repository//  ww w  . j  av a 2 s  .c  om
 * @param extensions
 * @param objectId
 * @return list of files in repository with a matching extension
 */
public static List<PathModel> getDocuments(Repository repository, List<String> extensions, String objectId) {
    List<PathModel> list = new ArrayList<PathModel>();
    if (!hasCommits(repository)) {
        return list;
    }
    RevCommit commit = getCommit(repository, objectId);
    final TreeWalk tw = new TreeWalk(repository);
    try {
        tw.addTree(commit.getTree());
        if (extensions != null && extensions.size() > 0) {
            List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
            for (String extension : extensions) {
                if (extension.charAt(0) == '.') {
                    suffixFilters.add(PathSuffixFilter.create(extension));
                } else {
                    // escape the . since this is a regexp filter
                    suffixFilters.add(PathSuffixFilter.create("." + extension));
                }
            }
            TreeFilter filter;
            if (suffixFilters.size() == 1) {
                filter = suffixFilters.get(0);
            } else {
                filter = OrTreeFilter.create(suffixFilters);
            }
            tw.setFilter(filter);
            tw.setRecursive(true);
        }
        while (tw.next()) {
            list.add(getPathModel(tw, null, commit));
        }
    } catch (IOException e) {
        error(e, repository, "{0} failed to get documents for commit {1}", commit.getName());
    } finally {
        tw.close();
    }
    Collections.sort(list);
    return list;
}

From source file:org.eclipse.egit.core.synchronize.GitSyncCache.java

License:Open Source License

private static TreeFilter createPathFilter(Collection<String> paths) {
    // do not use PathFilterGroup to create the filter, see bug 362430
    List<TreeFilter> filters = new ArrayList<TreeFilter>(paths.size());
    for (String path : paths) {
        if (path.length() == 0)
            return null;
        filters.add(PathFilter.create(path));
    }// w w w. j a va2  s.  c om
    if (filters.size() == 1)
        return filters.get(0);
    return OrTreeFilter.create(filters);
}

From source file:org.eclipse.egit.ui.internal.dialogs.CompareTreeView.java

License:Open Source License

private void buildMaps(Repository repository, RevCommit baseCommit, RevCommit compareCommit,
        IProgressMonitor monitor) throws InterruptedException, IOException {
    monitor.beginTask(UIText.CompareTreeView_AnalyzingRepositoryTaskText, IProgressMonitor.UNKNOWN);
    boolean useIndex = compareVersion.equals(INDEX_VERSION);
    deletedPaths.clear();/*from w  ww.  j av  a  2 s  .  c o m*/
    equalContentPaths.clear();
    baseVersionMap.clear();
    compareVersionMap.clear();
    compareVersionPathsWithChildren.clear();
    addedPaths.clear();
    baseVersionPathsWithChildren.clear();
    boolean checkIgnored = false;
    TreeWalk tw = new TreeWalk(repository);
    try {
        int baseTreeIndex;
        if (baseCommit == null) {
            checkIgnored = true;
            baseTreeIndex = tw.addTree(
                    new AdaptableFileTreeIterator(repository, ResourcesPlugin.getWorkspace().getRoot()));
        } else
            baseTreeIndex = tw
                    .addTree(new CanonicalTreeParser(null, repository.newObjectReader(), baseCommit.getTree()));
        int compareTreeIndex;
        if (!useIndex)
            compareTreeIndex = tw.addTree(
                    new CanonicalTreeParser(null, repository.newObjectReader(), compareCommit.getTree()));
        else
            compareTreeIndex = tw.addTree(new DirCacheIterator(repository.readDirCache()));

        if (input instanceof IResource[]) {
            IResource[] resources = (IResource[]) input;
            List<TreeFilter> orFilters = new ArrayList<TreeFilter>(resources.length);

            for (IResource resource : resources) {
                String relPath = repositoryMapping.getRepoRelativePath(resource);
                if (relPath.length() > 0)
                    orFilters.add(PathFilter.create(relPath));
            }
            if (checkIgnored) {
                if (orFilters.size() > 1) {
                    TreeFilter andFilter = AndTreeFilter.create(new NotIgnoredFilter(baseTreeIndex),
                            OrTreeFilter.create(orFilters));
                    tw.setFilter(andFilter);
                } else if (orFilters.size() == 1) {
                    TreeFilter andFilter = AndTreeFilter.create(new NotIgnoredFilter(baseTreeIndex),
                            orFilters.get(0));
                    tw.setFilter(andFilter);
                } else
                    tw.setFilter(new NotIgnoredFilter(baseTreeIndex));

            } else if (orFilters.size() > 1)
                tw.setFilter(OrTreeFilter.create(orFilters));
            else if (orFilters.size() == 1)
                tw.setFilter(orFilters.get(0));
        }

        tw.setRecursive(true);

        if (monitor.isCanceled())
            throw new InterruptedException();
        while (tw.next()) {
            if (monitor.isCanceled())
                throw new InterruptedException();
            AbstractTreeIterator compareVersionIterator = tw.getTree(compareTreeIndex,
                    AbstractTreeIterator.class);
            AbstractTreeIterator baseVersionIterator = tw.getTree(baseTreeIndex, AbstractTreeIterator.class);
            if (compareVersionIterator != null && baseVersionIterator != null) {
                monitor.setTaskName(baseVersionIterator.getEntryPathString());
                IPath currentPath = new Path(baseVersionIterator.getEntryPathString());
                if (!useIndex)
                    compareVersionMap.put(currentPath, GitFileRevision.inCommit(repository, compareCommit,
                            baseVersionIterator.getEntryPathString(), tw.getObjectId(compareTreeIndex)));
                else
                    compareVersionMap.put(currentPath,
                            GitFileRevision.inIndex(repository, baseVersionIterator.getEntryPathString()));
                if (baseCommit != null)
                    baseVersionMap.put(currentPath, GitFileRevision.inCommit(repository, baseCommit,
                            baseVersionIterator.getEntryPathString(), tw.getObjectId(baseTreeIndex)));
                boolean equalContent = compareVersionIterator.getEntryObjectId()
                        .equals(baseVersionIterator.getEntryObjectId());
                if (equalContent)
                    equalContentPaths.add(currentPath);

                if (equalContent && !showEquals)
                    continue;

                while (currentPath.segmentCount() > 0) {
                    currentPath = currentPath.removeLastSegments(1);
                    if (!baseVersionPathsWithChildren.add(currentPath))
                        break;
                }

            } else if (baseVersionIterator != null && compareVersionIterator == null) {
                monitor.setTaskName(baseVersionIterator.getEntryPathString());
                // only on base side
                IPath currentPath = new Path(baseVersionIterator.getEntryPathString());
                addedPaths.add(currentPath);
                if (baseCommit != null)
                    baseVersionMap.put(currentPath, GitFileRevision.inCommit(repository, baseCommit,
                            baseVersionIterator.getEntryPathString(), tw.getObjectId(baseTreeIndex)));
                while (currentPath.segmentCount() > 0) {
                    currentPath = currentPath.removeLastSegments(1);
                    if (!baseVersionPathsWithChildren.add(currentPath))
                        break;
                }

            } else if (compareVersionIterator != null && baseVersionIterator == null) {
                monitor.setTaskName(compareVersionIterator.getEntryPathString());
                // only on compare side
                IPath currentPath = new Path(compareVersionIterator.getEntryPathString());
                deletedPaths.add(currentPath);
                List<PathNodeAdapter> children = compareVersionPathsWithChildren
                        .get(currentPath.removeLastSegments(1));
                if (children == null) {
                    children = new ArrayList<PathNodeAdapter>(1);
                    compareVersionPathsWithChildren.put(currentPath.removeLastSegments(1), children);
                }
                children.add(new PathNodeAdapter(new PathNode(currentPath, Type.FILE_DELETED)));

                if (!useIndex)
                    compareVersionMap.put(currentPath, GitFileRevision.inCommit(repository, compareCommit,
                            compareVersionIterator.getEntryPathString(), tw.getObjectId(compareTreeIndex)));
                else
                    compareVersionMap.put(currentPath,
                            GitFileRevision.inIndex(repository, compareVersionIterator.getEntryPathString()));
            }
        }
    } finally {
        tw.release();
        monitor.done();
    }
}

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

License:Open Source License

private TreeFilter createTreeFilter() {
    if (filterResources == null)
        return TreeFilter.ALL;

    List<TreeFilter> filters = new ArrayList<TreeFilter>();
    for (IResource resource : filterResources) {
        RepositoryMapping mapping = RepositoryMapping.getMapping(resource);
        if (mapping != null) {
            String path = mapping.getRepoRelativePath(resource);
            if (path != null && !"".equals(path)) { //$NON-NLS-1$
                if (resource.getType() == IResource.FILE)
                    filters.add(FollowFilter.create(path));
                else
                    filters.add(AndTreeFilter.create(PathFilter.create(path), TreeFilter.ANY_DIFF));
            }/* w  w w  .  ja v a 2 s .  c  om*/
        }
    }

    if (filters.isEmpty())
        return TreeFilter.ALL;
    else if (filters.size() == 1)
        return filters.get(0);
    else
        return OrTreeFilter.create(filters);
}

From source file:org.eclipse.egit.ui.internal.merge.GitCompareEditorInput.java

License:Open Source License

private IDiffContainer buildDiffContainer(RevCommit baseCommit, RevCommit compareCommit,
        IProgressMonitor monitor) throws IOException, InterruptedException {
    boolean useIndex = compareVersion.equals(CompareTreeView.INDEX_VERSION);
    boolean checkIgnored = false;

    IDiffContainer result = new DiffNode(Differencer.CONFLICTING);

    TreeWalk tw = new TreeWalk(repository);

    // filter by selected resources
    if (filterPathStrings.size() > 1) {
        List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
        for (String filterPath : filterPathStrings)
            suffixFilters.add(PathFilter.create(filterPath));
        TreeFilter otf = OrTreeFilter.create(suffixFilters);
        tw.setFilter(otf);/*  ww  w. java  2 s  .c  om*/
    } else if (filterPathStrings.size() > 0) {
        String path = filterPathStrings.get(0);
        if (path.length() != 0)
            tw.setFilter(PathFilter.create(path));
    }

    tw.setRecursive(true);

    int baseTreeIndex;
    if (baseCommit == null) {
        // compare workspace with something
        checkIgnored = true;
        baseTreeIndex = tw
                .addTree(new AdaptableFileTreeIterator(repository, ResourcesPlugin.getWorkspace().getRoot()));
    } else
        baseTreeIndex = tw
                .addTree(new CanonicalTreeParser(null, repository.newObjectReader(), baseCommit.getTree()));
    int compareTreeIndex;
    if (!useIndex)
        compareTreeIndex = tw
                .addTree(new CanonicalTreeParser(null, repository.newObjectReader(), compareCommit.getTree()));
    else
        // compare something with the index
        compareTreeIndex = tw.addTree(new DirCacheIterator(repository.readDirCache()));

    try {
        while (tw.next()) {
            if (monitor.isCanceled())
                throw new InterruptedException();
            AbstractTreeIterator compareVersionIterator = tw.getTree(compareTreeIndex,
                    AbstractTreeIterator.class);
            AbstractTreeIterator baseVersionIterator = tw.getTree(baseTreeIndex, AbstractTreeIterator.class);
            if (checkIgnored && baseVersionIterator != null
                    && ((WorkingTreeIterator) baseVersionIterator).isEntryIgnored())
                continue;

            if (compareVersionIterator != null && baseVersionIterator != null) {
                boolean equalContent = compareVersionIterator.getEntryObjectId()
                        .equals(baseVersionIterator.getEntryObjectId());
                if (equalContent)
                    continue;
            }

            String encoding = null;

            GitFileRevision compareRev = null;
            if (compareVersionIterator != null) {
                String entryPath = compareVersionIterator.getEntryPathString();
                encoding = CompareCoreUtils.getResourceEncoding(repository, entryPath);
                if (!useIndex)
                    compareRev = GitFileRevision.inCommit(repository, compareCommit, entryPath,
                            tw.getObjectId(compareTreeIndex));
                else
                    compareRev = GitFileRevision.inIndex(repository, entryPath);
            }

            GitFileRevision baseRev = null;
            if (baseVersionIterator != null) {
                String entryPath = baseVersionIterator.getEntryPathString();
                if (encoding == null) {
                    encoding = CompareCoreUtils.getResourceEncoding(repository, entryPath);
                }
                baseRev = GitFileRevision.inCommit(repository, baseCommit, entryPath,
                        tw.getObjectId(baseTreeIndex));
            }

            if (compareVersionIterator != null && baseVersionIterator != null) {
                monitor.setTaskName(baseVersionIterator.getEntryPathString());
                // content exists on both sides
                add(result, baseVersionIterator.getEntryPathString(),
                        new DiffNode(new FileRevisionTypedElement(compareRev, encoding),
                                new FileRevisionTypedElement(baseRev, encoding)));
            } else if (baseVersionIterator != null && compareVersionIterator == null) {
                monitor.setTaskName(baseVersionIterator.getEntryPathString());
                // only on base side
                add(result, baseVersionIterator.getEntryPathString(),
                        new DiffNode(Differencer.DELETION | Differencer.RIGHT, null, null,
                                new FileRevisionTypedElement(baseRev, encoding)));
            } else if (compareVersionIterator != null && baseVersionIterator == null) {
                monitor.setTaskName(compareVersionIterator.getEntryPathString());
                // only on compare side
                add(result, compareVersionIterator.getEntryPathString(),
                        new DiffNode(Differencer.ADDITION | Differencer.RIGHT, null,
                                new FileRevisionTypedElement(compareRev, encoding), null));
            }

            if (monitor.isCanceled())
                throw new InterruptedException();
        }
        return result;
    } finally {
        tw.release();
    }
}

From source file:org.eclipse.emf.compare.egit.ui.internal.merge.ModelGitMergeEditorInput.java

License:Open Source License

private IDiffContainer buildDiffContainer(Repository repository, RevCommit headCommit, RevCommit ancestorCommit,
        List<String> filterPaths, RevWalk rw, IProgressMonitor monitor)
        throws IOException, InterruptedException {

    monitor.setTaskName(UIText.GitMergeEditorInput_CalculatingDiffTaskName);
    IDiffContainer result = new DiffNode(Differencer.CONFLICTING);

    TreeWalk tw = new TreeWalk(repository);
    try {//  w  w w .  j a  v  a 2s. c  o  m
        int dirCacheIndex = tw.addTree(new DirCacheIterator(repository.readDirCache()));
        int fileTreeIndex = tw.addTree(new FileTreeIterator(repository));
        int repositoryTreeIndex = tw.addTree(rw.parseTree(repository.resolve(Constants.HEAD)));

        // skip ignored resources
        NotIgnoredFilter notIgnoredFilter = new NotIgnoredFilter(fileTreeIndex);
        // filter by selected resources
        if (filterPaths.size() > 1) {
            List<TreeFilter> suffixFilters = new ArrayList<TreeFilter>();
            for (String filterPath : filterPaths) {
                suffixFilters.add(PathFilter.create(filterPath));
            }
            TreeFilter otf = OrTreeFilter.create(suffixFilters);
            tw.setFilter(AndTreeFilter.create(otf, notIgnoredFilter));
        } else if (filterPaths.size() > 0) {
            String path = filterPaths.get(0);
            if (path.length() == 0) {
                tw.setFilter(notIgnoredFilter);
            } else {
                tw.setFilter(AndTreeFilter.create(PathFilter.create(path), notIgnoredFilter));
            }
        } else {
            tw.setFilter(notIgnoredFilter);
        }

        tw.setRecursive(true);

        while (tw.next()) {
            if (monitor.isCanceled()) {
                throw new InterruptedException();
            }
            String gitPath = tw.getPathString();
            monitor.setTaskName(gitPath);

            FileTreeIterator fit = tw.getTree(fileTreeIndex, FileTreeIterator.class);
            if (fit == null) {
                continue;
            }

            DirCacheIterator dit = tw.getTree(dirCacheIndex, DirCacheIterator.class);

            final DirCacheEntry dirCacheEntry = dit == null ? null : dit.getDirCacheEntry();

            boolean conflicting = dirCacheEntry != null && dirCacheEntry.getStage() > 0;

            AbstractTreeIterator rt = tw.getTree(repositoryTreeIndex, AbstractTreeIterator.class);

            // compare local file against HEAD to see if it was modified
            boolean modified = rt != null && !fit.getEntryObjectId().equals(rt.getEntryObjectId());

            // if this is neither conflicting nor changed, we skip it
            if (!conflicting && !modified) {
                continue;
            }

            ITypedElement right;
            if (conflicting) {
                GitFileRevision revision = GitFileRevision.inIndex(repository, gitPath, DirCacheEntry.STAGE_3);
                String encoding = CompareCoreUtils.getResourceEncoding(repository, gitPath);
                right = new FileRevisionTypedElement(revision, encoding);
            } else {
                right = CompareUtils.getFileRevisionTypedElement(gitPath, headCommit, repository);
            }

            // can this really happen?
            if (right instanceof EmptyTypedElement) {
                continue;
            }

            IFileRevision rev;
            // if the file is not conflicting (as it was auto-merged)
            // we will show the auto-merged (local) version

            Path repositoryPath = new Path(repository.getWorkTree().getAbsolutePath());
            IPath location = repositoryPath.append(fit.getEntryPathString());
            IFile file = ResourceUtil.getFileForLocation(location, false);
            if (!conflicting || useWorkspace) {
                if (file != null) {
                    rev = new LocalFileRevision(file);
                } else {
                    rev = new WorkingTreeFileRevision(location.toFile());
                }
            } else {
                rev = GitFileRevision.inIndex(repository, gitPath, DirCacheEntry.STAGE_2);
            }

            IRunnableContext runnableContext = getContainer();
            if (runnableContext == null) {
                runnableContext = PlatformUI.getWorkbench().getProgressService();
            }

            EditableRevision leftEditable;
            if (file != null) {
                leftEditable = new ResourceEditableRevision(rev, file, runnableContext);
            } else {
                leftEditable = new LocationEditableRevision(rev, location, runnableContext);
            }
            // make sure we don't need a round trip later
            try {
                leftEditable.cacheContents(monitor);
            } catch (CoreException e) {
                throw new IOException(e.getMessage());
            }

            int kind = Differencer.NO_CHANGE;
            if (conflicting) {
                kind = Differencer.CONFLICTING;
            } else if (modified) {
                kind = Differencer.PSEUDO_CONFLICT;
            }

            IDiffContainer fileParent = getFileParent(result, repositoryPath, file, location);

            ITypedElement anc;
            if (ancestorCommit != null) {
                anc = CompareUtils.getFileRevisionTypedElement(gitPath, ancestorCommit, repository);
            } else {
                anc = null;
            }
            // we get an ugly black icon if we have an EmptyTypedElement
            // instead of null
            if (anc instanceof EmptyTypedElement) {
                anc = null;
            }
            // create the node as child
            new DiffNode(fileParent, kind, anc, leftEditable, right);
        }
        return result;
    } finally {
        tw.close();
    }
}

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

License:Open Source License

private DiffCommand getDiff(HttpServletRequest request, HttpServletResponse response, Repository db,
        String scope, String pattern, OutputStream out) throws Exception {
    boolean ignoreWS = Boolean.parseBoolean(request.getParameter("ignoreWS")); //$NON-NLS-1$
    // Git git = new Git(db);
    DiffCommand diff = new DiffCommand(db);
    diff.setOutputStream(out);//from  w  ww .j  a  va 2s .co m
    diff.setIgnoreWhiteSpace(ignoreWS);
    AbstractTreeIterator oldTree;
    AbstractTreeIterator newTree = null;// = new
    // FileTreeIterator(currentTree.getT);
    if (scope.contains("..")) { //$NON-NLS-1$
        String[] commits = scope.split("\\.\\."); //$NON-NLS-1$
        if (commits.length != 2) {
            // String msg = NLS.bind("Failed to generate diff for {0}",
            // scope);
            // statusHandler.handleRequest(request, response, new
            // ServerStatus(IStatus.ERROR,
            // HttpServletResponse.SC_BAD_REQUEST, msg, null));
            return null;
        }

        oldTree = getTreeIterator(db, java.net.URLDecoder.decode(commits[0], "UTF-8"));
        newTree = getTreeIterator(db, java.net.URLDecoder.decode(commits[1], "UTF-8"));
    } else {
        oldTree = getTreeIterator(db, scope);
    }

    String[] paths = request.getParameterValues(GitDiff.KEY_PATH);
    TreeFilter filter = null;
    TreeFilter pathFilter = null;
    if (paths != null) {
        if (paths.length > 1) {
            Set<TreeFilter> pathFilters = new HashSet<TreeFilter>(paths.length);
            for (String path : paths) {
                pathFilters.add(PathFilter.create(path));
            }
            pathFilter = OrTreeFilter.create(pathFilters);
        } else if (paths.length == 1) {
            pathFilter = PathFilter.create(paths[0]);
        }
    }
    if (pattern != null) {
        PathFilter patternFilter = PathFilter.create(pattern);
        if (pathFilter != null)
            filter = AndTreeFilter.create(patternFilter, pathFilter);
        else
            filter = patternFilter;
    } else {
        filter = pathFilter;
    }
    if (filter != null)
        diff.setPathFilter(filter);

    diff.setOldTree(oldTree);
    if (newTree != null)
        diff.setNewTree(newTree);
    return diff;
}

From source file:org.gitective.core.PathFilterUtils.java

License:Open Source License

private static TreeFilter orDiff(final TreeFilter[] filters) {
    final TreeFilter filter;
    if (filters.length > 1)
        filter = OrTreeFilter.create(filters);
    else//w ww. ja  v a2s.c o m
        filter = filters[0];
    return AndTreeFilter.create(filter, ANY_DIFF);
}

From source file:playRepository.BareRepository.java

License:Apache License

private static ObjectId getFirstFoundREADMEfileObjectId(Repository repository) throws IOException {
    TreeWalk treeWalk = new TreeWalk(repository);
    RevTree revTree = getRevTreeFromRef(repository, repository.getRef(HEAD));
    if (revTree == null) {
        return ObjectId.zeroId();
    }//w w  w  . j  av  a  2  s  .c om
    treeWalk.addTree(revTree);
    treeWalk.setRecursive(false);
    treeWalk.setFilter(OrTreeFilter.create(READMEFileNameFilter()));

    if (!treeWalk.next()) {
        play.Logger.info("No tree or no README file found at " + repository.getDirectory());
    }
    return treeWalk.getObjectId(0);
}