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

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

Introduction

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

Prototype

public void getObjectId(MutableObjectId out, int nth) 

Source Link

Document

Obtain the ObjectId for the current entry.

Usage

From source file:com.gitblit.servlet.RawServlet.java

License:Apache License

protected boolean streamFromRepo(HttpServletRequest request, HttpServletResponse response,
        Repository repository, RevCommit commit, String requestedPath) throws IOException {

    boolean served = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {/*  w w w.  ja  v a 2 s .  c om*/
        tw.reset();
        tw.addTree(commit.getTree());
        PathFilter f = PathFilter.create(requestedPath);
        tw.setFilter(f);
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            String filename = StringUtils.getLastPathElement(requestedPath);
            try {
                String userAgent = request.getHeader("User-Agent");
                if (userAgent != null && userAgent.indexOf("MSIE 5.5") > -1) {
                    response.setHeader("Content-Disposition",
                            "filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                } else if (userAgent != null && userAgent.indexOf("MSIE") > -1) {
                    response.setHeader("Content-Disposition",
                            "attachment; filename=\"" + URLEncoder.encode(filename, Constants.ENCODING) + "\"");
                } else {
                    response.setHeader("Content-Disposition", "attachment; filename=\""
                            + new String(filename.getBytes(Constants.ENCODING), "latin1") + "\"");
                }
            } catch (UnsupportedEncodingException e) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            }

            long len = reader.getObjectSize(id, org.eclipse.jgit.lib.Constants.OBJ_BLOB);
            setContentType(response, "application/octet-stream");
            response.setIntHeader("Content-Length", (int) len);
            ObjectLoader ldr = repository.open(id);
            ldr.copyTo(response.getOutputStream());
            served = true;
        }
    } finally {
        tw.close();
        rw.dispose();
    }

    response.flushBuffer();
    return served;
}

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

License:Apache License

/**
 * Zips the contents of the tree at the (optionally) specified revision and
 * the (optionally) specified basepath to the supplied outputstream.
 *
 * @param repository//from w w  w .j  a  v  a 2s .  c om
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
public static boolean zip(Repository repository, IFilestoreManager filestoreManager, String basePath,
        String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
        zos.setComment("Generated by Gitblit");
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            ObjectLoader loader = repository.open(id);

            ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString());

            FilestoreModel filestoreItem = null;

            if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) {
                filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id));
            }

            final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize();

            entry.setSize(size);
            entry.setComment(commit.getName());
            entry.setUnixMode(mode.getBits());
            entry.setTime(modified);
            zos.putArchiveEntry(entry);

            if (filestoreItem == null) {
                //Copy repository stored file
                loader.copyTo(zos);
            } else {
                //Copy filestore file
                try (FileInputStream streamIn = new FileInputStream(
                        filestoreManager.getStoragePath(filestoreItem.oid))) {
                    IOUtils.copyLarge(streamIn, zos);
                } catch (Throwable e) {
                    LOGGER.error(
                            MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e);

                    //Handle as per other errors 
                    throw e;
                }
            }

            zos.closeArchiveEntry();
        }
        zos.finish();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to zip files from commit {1}", commit.getName());
    } finally {
        tw.close();
        rw.dispose();
    }
    return success;
}

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

License:Apache License

/**
 * Compresses/archives the contents of the tree at the (optionally)
 * specified revision and the (optionally) specified basepath to the
 * supplied outputstream.//  w ww .j ava  2 s .c  om
 *
 * @param algorithm
 *            compression algorithm for tar (optional)
 * @param repository
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
private static boolean tar(String algorithm, Repository repository, IFilestoreManager filestoreManager,
        String basePath, String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }

    OutputStream cos = os;
    if (!StringUtils.isEmpty(algorithm)) {
        try {
            cos = new CompressorStreamFactory().createCompressorOutputStream(algorithm, os);
        } catch (CompressorException e1) {
            error(e1, repository, "{0} failed to open {1} stream", algorithm);
        }
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
        tos.setAddPaxHeadersForNonAsciiNames(true);
        tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }

            tw.getObjectId(id, 0);

            ObjectLoader loader = repository.open(id);
            if (FileMode.SYMLINK == mode) {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(), TarArchiveEntry.LF_SYMLINK);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                loader.copyTo(bos);
                entry.setLinkName(bos.toString());
                entry.setModTime(modified);
                tos.putArchiveEntry(entry);
                tos.closeArchiveEntry();
            } else {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString());
                entry.setMode(mode.getBits());
                entry.setModTime(modified);

                FilestoreModel filestoreItem = null;

                if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) {
                    filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id));
                }

                final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize();

                entry.setSize(size);
                tos.putArchiveEntry(entry);

                if (filestoreItem == null) {
                    //Copy repository stored file
                    loader.copyTo(tos);
                } else {
                    //Copy filestore file
                    try (FileInputStream streamIn = new FileInputStream(
                            filestoreManager.getStoragePath(filestoreItem.oid))) {

                        IOUtils.copyLarge(streamIn, tos);
                    } catch (Throwable e) {
                        LOGGER.error(
                                MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid),
                                e);

                        //Handle as per other errors 
                        throw e;
                    }
                }

                tos.closeArchiveEntry();
            }
        }
        tos.finish();
        tos.close();
        cos.close();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to {1} stream files from commit {2}", algorithm, commit.getName());
    } finally {
        tw.close();
        rw.dispose();
    }
    return success;
}

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

License:Open Source License

private static Map<String, Change> getChangedObjects(Repository repo, RevCommit parentCommit,
        RevCommit remoteCommit, TreeFilter pathFilter, final int direction) throws IOException {
    final TreeWalk tw = new TreeWalk(repo);
    addTreeFilter(tw, parentCommit);//from  w ww. j  a  v a  2  s .  co m
    addTreeFilter(tw, remoteCommit);

    tw.setRecursive(true);
    if (pathFilter == null)
        tw.setFilter(ANY_DIFF);
    else
        tw.setFilter(AndTreeFilter.create(ANY_DIFF, pathFilter));

    final int localTreeId = direction == LEFT ? 1 : 0;
    final int remoteTreeId = direction == LEFT ? 0 : 1;
    final Map<String, Change> result = new HashMap<String, GitCommitsModelCache.Change>();
    final AbbreviatedObjectId actualCommit = getAbbreviatedObjectId(parentCommit);
    final AbbreviatedObjectId remoteCommitAbb = getAbbreviatedObjectId(remoteCommit);

    MutableObjectId idBuf = new MutableObjectId();
    while (tw.next()) {
        Change change = new Change();
        change.commitId = actualCommit;
        change.remoteCommitId = remoteCommitAbb;
        change.name = tw.getNameString();
        tw.getObjectId(idBuf, localTreeId);
        change.objectId = AbbreviatedObjectId.fromObjectId(idBuf);
        tw.getObjectId(idBuf, remoteTreeId);
        change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);

        calculateAndSetChangeKind(direction, change);

        result.put(tw.getPathString(), change);
    }
    tw.release();

    return result.size() > 0 ? result : null;
}

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

License:Open Source License

/**
 * @param repo// ww w  .  j a v  a 2 s .c  om
 *            repository which should be scanned
 * @return list of changes in git staging area
 */
public static Map<String, Change> build(Repository repo) {
    TreeWalk tw = new TreeWalk(repo);
    try {
        tw.addTree(new DirCacheIterator(repo.readDirCache()));
        ObjectId headId = repo.resolve(HEAD);
        RevCommit headCommit;
        if (headId != null)
            headCommit = new RevWalk(repo).parseCommit(headId);
        else
            headCommit = null;

        AbbreviatedObjectId commitId;
        if (headCommit != null) {
            tw.addTree(headCommit.getTree());
            commitId = AbbreviatedObjectId.fromObjectId(headCommit);
        } else {
            tw.addTree(new EmptyTreeIterator());
            commitId = AbbreviatedObjectId.fromObjectId(zeroId());
        }

        tw.setRecursive(true);
        headCommit = null;

        MutableObjectId idBuf = new MutableObjectId();
        Map<String, Change> result = new HashMap<String, Change>();
        while (tw.next()) {
            if (!shouldIncludeEntry(tw))
                continue;

            Change change = new Change();
            change.name = tw.getNameString();
            change.remoteCommitId = commitId;

            tw.getObjectId(idBuf, 0);
            change.objectId = AbbreviatedObjectId.fromObjectId(idBuf);
            tw.getObjectId(idBuf, 1);
            change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);

            calculateAndSetChangeKind(RIGHT, change);

            result.put(tw.getPathString(), change);
        }
        tw.release();

        return result;
    } catch (IOException e) {
        Activator.error(e.getMessage(), e);
        return new HashMap<String, Change>(0);
    }
}

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

License:Open Source License

/**
 * Converts the TreeWalk into TreeWayDiffEntry headers.
 *
 * @param walk//  w  w  w  .j a v a  2  s  .  co  m
 *            the TreeWalk to walk through. Must have exactly three trees in
 *            this order: local, base and remote and can't be recursive.
 * @return headers describing the changed file.
 * @throws IOException
 *             the repository cannot be accessed.
 * @throws IllegalArgumentException
 *             when {@code walk} doen't have exactly three trees, or when
 *             {@code walk} is recursive
 */
public static List<ThreeWayDiffEntry> scan(TreeWalk walk) throws IOException {
    if (walk.getTreeCount() != 3 && walk.getTreeCount() != 4)
        throw new IllegalArgumentException("TreeWalk need to have three or four trees"); //$NON-NLS-1$
    if (walk.isRecursive())
        throw new IllegalArgumentException("TreeWalk shouldn't be recursive."); //$NON-NLS-1$

    List<ThreeWayDiffEntry> r = new ArrayList<ThreeWayDiffEntry>();
    MutableObjectId idBuf = new MutableObjectId();
    while (walk.next()) {
        ThreeWayDiffEntry e = new ThreeWayDiffEntry();

        walk.getObjectId(idBuf, 0);
        e.localId = AbbreviatedObjectId.fromObjectId(idBuf);

        walk.getObjectId(idBuf, 1);
        e.baseId = AbbreviatedObjectId.fromObjectId(idBuf);

        walk.getObjectId(idBuf, 2);
        e.remoteId = AbbreviatedObjectId.fromObjectId(idBuf);

        boolean localSameAsBase = e.localId.equals(e.baseId);
        if (!A_ZERO.equals(e.localId) && localSameAsBase && e.baseId.equals(e.remoteId))
            continue;

        e.path = walk.getPathString();
        boolean localIsMissing = walk.getFileMode(0) == FileMode.MISSING;
        boolean baseIsMissing = walk.getFileMode(1) == FileMode.MISSING;
        boolean remoteIsMissing = walk.getFileMode(2) == FileMode.MISSING;

        if (localIsMissing || baseIsMissing || remoteIsMissing) {
            if (!localIsMissing && baseIsMissing && remoteIsMissing) {
                e.direction = Direction.OUTGOING;
                e.changeType = ChangeType.ADD;
            } else if (localIsMissing && baseIsMissing && !remoteIsMissing) {
                e.direction = Direction.INCOMING;
                e.changeType = ChangeType.ADD;
            } else if (!localIsMissing && !baseIsMissing && remoteIsMissing) {
                e.direction = Direction.INCOMING;
                e.changeType = ChangeType.DELETE;
            } else if (localIsMissing && !baseIsMissing && !remoteIsMissing) {
                e.direction = Direction.OUTGOING;
                e.changeType = ChangeType.DELETE;
            } else {
                e.direction = Direction.CONFLICTING;
                e.changeType = ChangeType.MODIFY;
            }
        } else {
            if (localSameAsBase && !e.localId.equals(e.remoteId))
                e.direction = Direction.INCOMING;
            else if (e.remoteId.equals(e.baseId) && !e.remoteId.equals(e.localId))
                e.direction = Direction.OUTGOING;
            else
                e.direction = Direction.CONFLICTING;

            e.changeType = ChangeType.MODIFY;
        }

        r.add(e);
        if (walk.isSubtree()) {
            e.isTree = true;
            walk.enterSubtree();
        }
    }

    return r;
}

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

License:Open Source License

/**
 * @param repo//from  www.ja va  2s  .  com
 *            with should be scanned
 * @return list of changes in working tree
 */
public static Map<String, Change> build(Repository repo) {
    TreeWalk tw = new TreeWalk(repo);
    try {
        int fileNth = tw.addTree(new FileTreeIterator(repo));
        int cacheNth = tw.addTree(new DirCacheIterator(repo.readDirCache()));
        tw.setFilter(new IndexDiffFilter(cacheNth, fileNth));
        tw.setRecursive(true);

        Map<String, Change> result = new HashMap<String, Change>();
        MutableObjectId idBuf = new MutableObjectId();
        while (tw.next()) {
            Change change = new Change();
            change.name = tw.getNameString();
            tw.getObjectId(idBuf, 0);
            change.objectId = AbbreviatedObjectId.fromObjectId(idBuf);
            tw.getObjectId(idBuf, 1);
            change.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);
            calculateAndSetChangeKind(RIGHT, change);

            result.put(tw.getPathString(), change);
        }
        tw.release();

        return result;
    } catch (IOException e) {
        Activator.error(e.getMessage(), e);
        return new HashMap<String, GitCommitsModelCache.Change>(0);
    }
}

From source file:org.gitective.core.filter.commit.CommitDiffFilter.java

License:Open Source License

@Override
public boolean include(final RevWalk walker, final RevCommit commit) throws IOException {
    final TreeWalk walk = createTreeWalk(walker, commit);
    final List<DiffEntry> diffs;
    final int treeCount = walk.getTreeCount();
    switch (treeCount) {
    case 0:/*from  ww  w.j  av a  2  s.co  m*/
    case 1:
        diffs = Collections.emptyList();
        break;
    case 2:
        diffs = DiffEntry.scan(walk);
        break;
    default:
        diffs = new ArrayList<DiffEntry>();
        final MutableObjectId currentId = new MutableObjectId();
        final int currentTree = treeCount - 1;
        while (walk.next()) {
            final int currentMode = walk.getRawMode(currentTree);
            int parentMode = 0;
            boolean same = false;
            for (int i = 0; i < currentTree; i++) {
                final int mode = walk.getRawMode(i);
                same = mode == currentMode && walk.idEqual(currentTree, i);
                if (same)
                    break;
                parentMode |= mode;
            }
            if (same)
                continue;

            final LocalDiffEntry diff = new LocalDiffEntry(walk.getPathString());
            diff.setOldMode(FileMode.fromBits(parentMode));
            diff.setNewMode(FileMode.fromBits(currentMode));
            walk.getObjectId(currentId, currentTree);
            diff.setNewId(AbbreviatedObjectId.fromObjectId(currentId));
            if (parentMode == 0 && currentMode != 0)
                diff.setChangeType(ChangeType.ADD);
            else if (parentMode != 0 && currentMode == 0)
                diff.setChangeType(ChangeType.DELETE);
            else
                diff.setChangeType(ChangeType.MODIFY);
            diffs.add(diff);
        }
    }
    if (detectRenames) {
        renameDetector.reset();
        renameDetector.addAll(diffs);
        return include(walker, commit, renameDetector.compute(walker.getObjectReader(), INSTANCE)) ? true
                : include(false);
    } else
        return include(walker, commit, diffs) ? true : include(false);
}

From source file:org.gitective.core.filter.commit.DuplicateTreeFilter.java

License:Open Source License

public boolean include(final RevWalk walker, final RevCommit commit) throws IOException {
    final TreeWalk walk = TreeUtils.diffWithParents(walker, commit);
    final MutableObjectId id = new MutableObjectId();
    final ObjectId zero = ObjectId.zeroId();
    final DuplicateContainer dupes = new DuplicateContainer(commit);
    while (walk.next()) {
        if (!walk.isSubtree())
            continue;
        final String path = walk.getPathString();
        for (int i = 0; i < walk.getTreeCount(); i++) {
            walk.getObjectId(id, i);
            if (!zero.equals(id))
                dupes.include(id.toObjectId(), path);
        }/*from w ww .java2s .  c  o  m*/
        walk.enterSubtree();
    }
    if (dupes.validate())
        duplicates.put(commit, dupes);
    return true;
}

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

License:Open Source License

private static boolean visit(final Repository repository, final TreeWalk walk, final MutableObjectId id,
        final String path, final ITreeVisitor visitor) throws IOException {
    while (walk.next()) {
        if (walk.isPostChildren())
            break;

        if (walk.isSubtree()) {
            final String subTreePath = walk.getPathString();
            walk.enterSubtree();// ww  w  . j a  v a  2 s.c om
            if (!visit(repository, walk, id, subTreePath, visitor))
                return false;
        }

        walk.getObjectId(id, 0);
        if (!visitor.accept(walk.getFileMode(0), path, walk.getNameString(), id))
            return false;
    }
    return true;
}