Example usage for org.eclipse.jgit.treewalk CanonicalTreeParser CanonicalTreeParser

List of usage examples for org.eclipse.jgit.treewalk CanonicalTreeParser CanonicalTreeParser

Introduction

In this page you can find the example usage for org.eclipse.jgit.treewalk CanonicalTreeParser CanonicalTreeParser.

Prototype

public CanonicalTreeParser(final byte[] prefix, final ObjectReader reader, final AnyObjectId treeId)
        throws IncorrectObjectTypeException, IOException 

Source Link

Document

Create a new parser for a tree appearing in a subset of a repository.

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;/*from   w w  w .j a  v  a  2 s .  c om*/
    }

    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: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);/*w  w w . jav  a 2 s  .  c om*/
    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);/* w  ww .  j  av a2  s  .com*/
    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:de.br0tbox.gitfx.ui.controllers.SingleProjectController.java

License:Apache License

private void showHistoryForCommit(final GitFxCommit selectedCommit) {
    Preconditions.checkNotNull(selectedCommit, "selectedCommit");
    final Git git = projectModel.getFxProject().getGit();
    final Repository repository = git.getRepository();
    ObjectId resolve;//ww  w.  ja  v  a 2s.c o  m
    try {
        resolve = repository.resolve(selectedCommit.getHash());
        final RevWalk revWalk = new RevWalk(repository);
        final RevCommit commit = revWalk.parseCommit(resolve);
        RevCommit parent = null;
        if (commit.getParents().length > 0 && commit.getParent(0) != null) {
            parent = revWalk.parseCommit(commit.getParent(0).getId());
        }

        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final DiffFormatter df = new DiffFormatter(out);
        df.setRepository(repository);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);
        List<DiffEntry> diffs = null;
        if (parent != null) {
            diffs = df.scan(parent.getTree(), commit.getTree());
        } else {
            diffs = df.scan(new EmptyTreeIterator(),
                    new CanonicalTreeParser(null, revWalk.getObjectReader(), commit.getTree()));
        }
        final ObservableList items = commitList.getItems();
        items.clear();
        for (final DiffEntry diff : diffs) {
            df.format(diff);
            final String changes = out.toString("UTF-8");
            changesView.setText(changes);
            if (ChangeType.DELETE.equals(diff.getChangeType())) {
                items.add(diff.getChangeType().toString().subSequence(0, 1) + " " + diff.getOldPath());
            } else {
                items.add(diff.getChangeType().toString().subSequence(0, 1) + " " + diff.getNewPath());
            }
        }
        revWalk.release();
        df.release();
    } catch (final IOException e) {
        LOGGER.error("Error while showing changes for commit " + selectedCommit.getHash(), e);
    }
}

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 w  w.java  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.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);/*from  w w  w. ja  v  a2  s .c o m*/
    } 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.kuali.student.git.importer.ConvertOldBranchesToTagsMain.java

License:Educational Community License

private static boolean commitContainsChangesToParent(Git git, Repository repo, AnyObjectId commitTreeId,
        AnyObjectId parentTreeId) throws MissingObjectException, IncorrectObjectTypeException,
        CorruptObjectException, IOException, GitAPIException {
    DiffCommand diffCommand = git.diff();

    TreeWalk parentWalk = new TreeWalk(repo);

    parentWalk.addTree(parentTreeId);//from ww  w .j  av a  2s.c  om

    parentWalk.setRecursive(true);

    TreeWalk commitWalk = new TreeWalk(repo);

    commitWalk.addTree(commitTreeId);

    commitWalk.setRecursive(true);

    CanonicalTreeParser commitTreeParser = new CanonicalTreeParser(null, commitWalk.getObjectReader(),
            commitTreeId);

    CanonicalTreeParser parentTreeParser = new CanonicalTreeParser(null, parentWalk.getObjectReader(),
            parentTreeId);

    diffCommand.setOldTree(parentTreeParser);
    diffCommand.setNewTree(commitTreeParser);

    List<DiffEntry> entries = diffCommand.call();

    if (entries.size() > 0)
        return true;
    else
        return false;
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

private List<DiffEntry> getDiffBetweenCommits(Repository repo, AnyObjectId parentCommit,
        AnyObjectId currentCommit) {//from w  w w  .j av a2  s .  c om
    try (DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE)) {

        df.setBinaryFileThreshold(2 * 1024); // 2 mb max a file
        df.setRepository(repo);
        df.setDiffComparator(RawTextComparator.DEFAULT);
        df.setDetectRenames(true);

        setContext(df);

        List<DiffEntry> diffs = null;
        if (parentCommit == null) {
            try (RevWalk rw = new RevWalk(repo)) {
                RevCommit commit = rw.parseCommit(currentCommit);
                diffs = df.scan(new EmptyTreeIterator(),
                        new CanonicalTreeParser(null, rw.getObjectReader(), commit.getTree()));
            }
        } else {
            diffs = df.scan(parentCommit, currentCommit);
        }
        return diffs;
    } catch (IOException e) {
        throw new RuntimeException(
                "error diffing " + parentCommit.getName() + " and " + currentCommit.getName() + " in " + path,
                e);
    }
}

From source file:playRepository.BareCommit.java

License:Apache License

private CanonicalTreeParser getCanonicalTreeParser(Repository repository) throws IOException {
    RevWalk revWalk = new RevWalk(repository);
    RevCommit commit = revWalk.parseCommit(this.headObjectId);
    return new CanonicalTreeParser(new byte[] {}, revWalk.getObjectReader(), commit.getTree().getId());
}

From source file:svnserver.repository.git.GitRepository.java

License:GNU General Public License

private boolean isTreeEmpty(RevTree tree) throws IOException {
    return new CanonicalTreeParser(GitRepository.emptyBytes, repository.newObjectReader(), tree).eof();
}