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

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

Introduction

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

Prototype

public TreeWalk(ObjectReader or) 

Source Link

Document

Create a new tree walker for a given repository.

Usage

From source file:MyDiffFormatter.java

License:Eclipse Distribution License

/**
* Determine the differences between two trees.
*
* No output is created, instead only the file paths that are different are
* returned. Callers may choose to format these paths themselves, or convert
* them into {@link FileHeader} instances with a complete edit list by
*
* @param a//  w  w  w . j  av  a 2s  .c  o  m
*            the old (or previous) side.
* @param b
*            the new (or updated) side.
* @return the paths that are different.
* @throws IOException
*             trees cannot be read or file contents cannot be read.
*/
public List<DiffEntry> scan(AbstractTreeIterator a, AbstractTreeIterator b) throws IOException {
    assertHaveRepository();

    TreeWalk walk = new TreeWalk(reader);
    walk.addTree(a);
    walk.addTree(b);
    walk.setRecursive(true);

    TreeFilter filter = getDiffTreeFilterFor(a, b);
    if (pathFilter instanceof FollowFilter) {
        walk.setFilter(AndTreeFilter.create(PathFilter.create(((FollowFilter) pathFilter).getPath()), filter));
    } else {
        walk.setFilter(AndTreeFilter.create(pathFilter, filter));
    }

    source = new ContentSource.Pair(source(a), source(b));

    List<DiffEntry> files = DiffEntry.scan(walk);
    if (pathFilter instanceof FollowFilter && isAdd(files)) {
        // The file we are following was added here, find where it
        // came from so we can properly show the rename or copy,
        // then continue digging backwards.
        //
        a.reset();
        b.reset();
        walk.reset();
        walk.addTree(a);
        walk.addTree(b);
        walk.setFilter(filter);

        if (renameDetector == null)
            setDetectRenames(true);
        files = updateFollowFilter(detectRenames(DiffEntry.scan(walk)));

    } else if (renameDetector != null)
        files = detectRenames(files);

    return files;
}

From source file:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

/**
 * builds a dir cache by copying entries from an existing tree, skipping
 * files if specified./*from  w  w w.  java  2s.  c o  m*/
 *
 * @param tree
 *            the tree to copy from.
 * @param repository
 *            the repository to work upon.
 * @param dirCacheBuilder
 *            the dir builder instance used to add entries to the dir cache.
 * @param ignoredFilePaths
 *            a list of file paths to ignore during copying.
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 * @throws CorruptObjectException
 * @throws IOException
 */
private void buildDirCacheFromTree(RevTree tree, Repository repository, DirCacheBuilder dirCacheBuilder,
        List<String> ignoredFilePaths)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    // TODO improve exception handling

    TreeWalk treeWalk = new TreeWalk(repository);
    int treeId = treeWalk.addTree(tree);
    treeWalk.setRecursive(true);

    while (treeWalk.next()) {
        String path = treeWalk.getPathString();

        CanonicalTreeParser prevTreeParser = treeWalk.getTree(treeId, CanonicalTreeParser.class);
        if (prevTreeParser != null && !ignoredFilePaths.contains(path)) {
            // create a new DirCacheEntry with data from the previous commit

            final DirCacheEntry dcEntry = new DirCacheEntry(path);
            dcEntry.setObjectId(prevTreeParser.getEntryObjectId());
            dcEntry.setFileMode(prevTreeParser.getEntryFileMode());
            dirCacheBuilder.add(dcEntry);
        }
    }
    treeWalk.close();
}

From source file:au.id.soundadvice.systemdesign.versioning.jgit.GitVersionControl.java

License:Open Source License

/**
 * Find the tree that contains the required identity.
 *
 * @return The ObjectId of the tree (directory) that contains the matching
 * identity within the supplied hierarchy.
 *///from   w  w w  .j a va  2s  .  c o  m
private ObjectId findMatchingIdentity(IdentityValidator identityValidator, ObjectId tree) throws IOException {
    TreeWalk treeWalk = new TreeWalk(repo.getRepository());
    try {
        treeWalk.setRecursive(false);
        treeWalk.addTree(tree);

        while (treeWalk.next()) {
            if (treeWalk.isSubtree()) {
                ObjectId candidateId = findMatchingIdentity(identityValidator, treeWalk.getObjectId(0));
                if (ObjectId.zeroId().equals(candidateId)) {
                    // Keep searching
                } else {
                    return candidateId;
                }
            } else if (identityValidator.getIdentityFileName().equals(treeWalk.getNameString())) {
                // Read the identity file
                ObjectLoader loader = repo.getRepository().open(treeWalk.getObjectId(0));
                ObjectStream stream = loader.openStream();
                InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
                if (identityValidator.isIdentityMatched(new BufferedReader(reader))) {
                    // We found it
                    return tree;
                }
            }
        }
        return ObjectId.zeroId();
    } finally {
        treeWalk.release();
    }
}

From source file:au.id.soundadvice.systemdesign.versioning.jgit.GitVersionControl.java

License:Open Source License

@Override
public Optional<BufferedReader> getBufferedReader(IdentityValidator identityValidator, String filename,
        Optional<VersionInfo> version) throws IOException {
    if (version.isPresent()) {
        Pair<String, ObjectId> diff = diffCache.get();
        if (!version.get().getId().equals(diff.getKey())) {
            // Grab the id of the commit we are trying to diff against
            ObjectId id = ObjectId.fromString(version.get().getId());
            RevWalk revWalk = new RevWalk(repo.getRepository());
            try {
                // Read the commit
                RevCommit commit = revWalk.parseCommit(id);
                ObjectId matchedDirectory = findMatchingIdentity(identityValidator, commit.getTree());
                diff = new Pair<>(version.get().getId(), matchedDirectory);
                diffCache.set(diff);/*w  w w . ja  va  2 s . c o  m*/
            } finally {
                revWalk.release();
            }
        }

        if (ObjectId.zeroId().equals(diff.getValue())) {
            // No such tree
            return Optional.empty();
        } else {
            // Find the file in this tree
            TreeWalk treeWalk = new TreeWalk(repo.getRepository());
            try {
                treeWalk.setRecursive(false);
                treeWalk.addTree(diff.getValue());

                while (treeWalk.next()) {
                    if (filename.equals(treeWalk.getNameString())) {
                        // Read the file
                        ObjectLoader loader = repo.getRepository().open(treeWalk.getObjectId(0));
                        ObjectStream stream = loader.openStream();
                        InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
                        return Optional.of(new BufferedReader(reader));
                    }
                }
                // No such file
                return Optional.empty();
            } finally {
                treeWalk.release();
            }
        }
    } else {
        Path path = identityValidator.getDirectoryPath().resolve(filename);
        if (Files.exists(path)) {
            return Optional.of(Files.newBufferedReader(path));
        } else {
            return Optional.empty();
        }
    }
}

From source file:co.bledo.gitmin.servlet.Review.java

License:Apache License

private String getFileContent(Repository repo, RevCommit commit, String path)
        throws MissingObjectException, IncorrectObjectTypeException, CorruptObjectException, IOException {
    // and using commit's tree find the path
    RevTree tree = commit.getTree();//from  w  w w . ja va  2s  .co  m
    TreeWalk treeWalk = new TreeWalk(repo);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.create(path));
    if (!treeWalk.next()) {
        return "";
    }
    ObjectId objectId = treeWalk.getObjectId(0);
    ObjectLoader loader = repo.open(objectId);

    // and then one can use either
    //InputStream in = loader.openStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);
    return out.toString();
}

From source file:com.amd.gerrit.plugins.manifestsubscription.VersionedManifests.java

License:Open Source License

@Override
protected void onLoad() throws IOException, ConfigInvalidException {
    manifests = Maps.newHashMap();/*  w  w  w  . j  a  v  a  2 s.c  o m*/

    String path;
    Manifest manifest;

    try (RevWalk rw = new RevWalk(reader); TreeWalk treewalk = new TreeWalk(reader)) {
        // This happens when someone configured a invalid branch name
        if (getRevision() == null) {
            throw new ConfigInvalidException(refName);
        }
        RevCommit r = rw.parseCommit(getRevision());
        treewalk.addTree(r.getTree());
        treewalk.setRecursive(false);
        treewalk.setFilter(PathSuffixFilter.create(".xml"));
        while (treewalk.next()) {
            if (treewalk.isSubtree()) {
                treewalk.enterSubtree();
            } else {
                path = treewalk.getPathString();
                //TODO: Should this be done more lazily?
                //TODO: difficult to do when reader is not available outside of onLoad?
                try (ByteArrayInputStream input = new ByteArrayInputStream(readFile(path))) {
                    manifest = (Manifest) manifestUnmarshaller.unmarshal(input);
                    manifests.put(path, manifest);
                } catch (JAXBException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //TODO load changed manifest
    //    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
}

From source file:com.beck.ep.team.git.GitListBuilder.java

License:BSD License

public String[] createList(Shell shell, IProject project) throws Exception {
    error = null;/*from w  ww. j ava  2  s .  co m*/
    RepositoryMapping mapping = RepositoryMapping.getMapping(project);
    if (mapping == null) {
        error = "Git Repository not found (project: " + project.getName() + ")";
        return null;
    }
    Repository rep = mapping.getRepository();
    String pjPath = project.getLocation().toFile().getAbsolutePath();
    String repPath = rep.getDirectory().getParentFile().getAbsolutePath();
    int cutPrefixLen = 0;
    int pathDiffLen = pjPath.length() - repPath.length();
    if (pathDiffLen > 0) {
        cutPrefixLen = pathDiffLen;//for repositoy is not in "parent folder of project"
    }

    RevWalk rw = new RevWalk(rep);
    TreeWalk tw = new TreeWalk(rep);

    int ignoreOpt = pref.getInt(GitModeMenuMgr.PREF_TYPE_IGNORE, GitModeMenuMgr.IGNORE_EXCLUDE);
    if (ignoreOpt == GitModeMenuMgr.IGNORE_ONLY) {
        String[] sa = listIgnored(rep, rw, tw, cutPrefixLen);
        if (cutPrefixLen > 0) {
            for (int i = 0; i < sa.length; i++) {
                if (sa[i].length() > cutPrefixLen) {
                    sa[i] = sa[i].substring(cutPrefixLen);
                }
            }
        }
        return sa;
    }

    int mode = pref.getInt(GitModeMenuMgr.PREF_TYPE_MODE, GitModeMenuMgr.MODE_BRANCH_HEAD);
    int sourceMode = pref.getInt(GitModeMenuMgr.PREF_TYPE_SOURCE, GitModeMenuMgr.MODE_WORKING_AREA);
    if (mode == sourceMode) {
        return new String[0];
    }
    int index = addTree(mode, shell, rep, rw, tw);
    if (index == -2) {
        return null;
    }
    int stageIndex = -1;
    boolean excludeUntrackOpt = false;
    if (!pref.getBoolean(GitModeMenuMgr.PREF_TYPE_UNTRACK, true)
            && sourceMode == GitModeMenuMgr.MODE_WORKING_AREA) {
        excludeUntrackOpt = true;
        if (mode == GitModeMenuMgr.MODE_STAGING) {
            stageIndex = 0;
        }
    }

    int idx2 = addTree(sourceMode, shell, rep, rw, tw);
    if (excludeUntrackOpt && stageIndex == -1) {
        addTree(GitModeMenuMgr.MODE_STAGING, shell, rep, rw, tw);
        stageIndex = 2;
    }
    // skip ignored resources
    if (ignoreOpt == GitModeMenuMgr.IGNORE_EXCLUDE && (index != -1 || idx2 != -1)) {
        int pos = (index != -1) ? index : idx2;
        NotIgnoredFilter notIgnoredFilter = new NotIgnoredFilter(pos);//index = tw.addTree(?)
        tw.setFilter(notIgnoredFilter);
    }

    tw.setRecursive(true);
    ArrayList<String> sa = new ArrayList<String>();
    while (tw.next()) {
        if (!tw.idEqual(0, 1)) {
            if (excludeUntrackOpt) {
                if (tw.getTree(stageIndex, AbstractTreeIterator.class) == null) {
                    WorkingTreeIterator t = tw.getTree(1, WorkingTreeIterator.class);
                    if (t != null && !t.isEntryIgnored()) {//file is untrack...
                        continue;
                    }
                }
            }
            String relPath = tw.getPathString();
            if (cutPrefixLen > 0 && relPath.length() > cutPrefixLen) {
                relPath = relPath.substring(cutPrefixLen);
            }
            sa.add(relPath);
        }
    }

    return sa.toArray(new String[sa.size()]);
}

From source file:com.buildautomation.jgit.api.GetFileAttributes.java

License:Apache License

private static void printFile(Repository repository, RevTree tree) throws IOException {
    // now try to find a specific file
    try (TreeWalk treeWalk = new TreeWalk(repository)) {
        treeWalk.addTree(tree);//from  w  w  w .j  ava  2  s  .  c om
        treeWalk.setRecursive(false);
        treeWalk.setFilter(PathFilter.create("README.md"));
        if (!treeWalk.next()) {
            throw new IllegalStateException("Did not find expected file 'README.md'");
        }

        // FileMode specifies the type of file, FileMode.REGULAR_FILE for normal file, FileMode.EXECUTABLE_FILE for executable bit
        // set
        FileMode fileMode = treeWalk.getFileMode(0);
        ObjectLoader loader = repository.open(treeWalk.getObjectId(0));
        System.out.println("README.md: " + getFileMode(fileMode) + ", type: " + fileMode.getObjectType()
                + ", mode: " + fileMode + " size: " + loader.getSize());
    }
}

From source file:com.buildautomation.jgit.api.GetFileAttributes.java

License:Apache License

private static void printDirectory(Repository repository, RevTree tree) throws IOException {
    // look at directory, this has FileMode.TREE
    try (TreeWalk treeWalk = new TreeWalk(repository)) {
        treeWalk.addTree(tree);//from  w  w  w.  ja va  2  s. c  om
        treeWalk.setRecursive(false);
        treeWalk.setFilter(PathFilter.create("src"));
        if (!treeWalk.next()) {
            throw new IllegalStateException("Did not find expected file 'README.md'");
        }

        // FileMode now indicates that this is a directory, i.e. FileMode.TREE.equals(fileMode) holds true
        FileMode fileMode = treeWalk.getFileMode(0);
        System.out.println("src: " + getFileMode(fileMode) + ", type: " + fileMode.getObjectType() + ", mode: "
                + fileMode);
    }
}

From source file:com.buildautomation.jgit.api.ListFilesOfCommitAndTag.java

License:Apache License

private static List<String> readElementsAt(Repository repository, String commit, String path)
        throws IOException {
    RevCommit revCommit = buildRevCommit(repository, commit);

    // and using commit's tree find the path
    RevTree tree = revCommit.getTree();//  w  w w .j  a  v  a2 s .c  o m
    //System.out.println("Having tree: " + tree + " for commit " + commit);

    List<String> items = new ArrayList<>();

    // shortcut for root-path
    if (path.isEmpty()) {
        try (TreeWalk treeWalk = new TreeWalk(repository)) {
            treeWalk.addTree(tree);
            treeWalk.setRecursive(false);
            treeWalk.setPostOrderTraversal(false);

            while (treeWalk.next()) {
                items.add(treeWalk.getPathString());
            }
        }
    } else {
        // now try to find a specific file
        try (TreeWalk treeWalk = buildTreeWalk(repository, tree, path)) {
            if ((treeWalk.getFileMode(0).getBits() & FileMode.TYPE_TREE) == 0) {
                throw new IllegalStateException("Tried to read the elements of a non-tree for commit '" + commit
                        + "' and path '" + path + "', had filemode " + treeWalk.getFileMode(0).getBits());
            }

            try (TreeWalk dirWalk = new TreeWalk(repository)) {
                dirWalk.addTree(treeWalk.getObjectId(0));
                dirWalk.setRecursive(false);
                while (dirWalk.next()) {
                    items.add(dirWalk.getPathString());
                }
            }
        }
    }

    return items;
}