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

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

Introduction

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

Prototype

public ObjectId getEntryObjectId() 

Source Link

Document

Get the object id of the current entry.

Usage

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. ja  va 2  s . 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:com.gitblit.build.BuildGhPages.java

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * /*from w  ww  .  jav  a 2s . co m*/
 * @param repo
 * @param headId
 * @param sourceFolder
 * @param obliterate
 *            if true the source folder tree is used as the new tree for
 *            gh-pages and non-existent files are considered deleted
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, File sourceFolder, boolean obliterate)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    try {
        // Add all files to the temporary index
        Set<String> ignorePaths = new TreeSet<String>();
        List<File> files = listFiles(sourceFolder);
        for (File file : files) {
            // create an index entry for the file
            final DirCacheEntry dcEntry = new DirCacheEntry(
                    StringUtils.getRelativePath(sourceFolder.getPath(), file.getPath()));
            dcEntry.setLength(file.length());
            dcEntry.setLastModified(file.lastModified());
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // add this entry to the ignore paths set
            ignorePaths.add(dcEntry.getPathString());

            // insert object
            InputStream inputStream = new FileInputStream(file);
            try {
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, file.length(), inputStream));
            } finally {
                inputStream.close();
            }

            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }

        if (!obliterate) {
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repo);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
            treeWalk.setRecursive(true);

            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                if (!ignorePaths.contains(path)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        // create a new DirCacheEntry with data retrieved
                        // from
                        // HEAD
                        final DirCacheEntry dcEntry = new DirCacheEntry(path);
                        dcEntry.setObjectId(hTree.getEntryObjectId());
                        dcEntry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        dcBuilder.add(dcEntry);
                    }
                }
            }

            // release the treewalk
            treeWalk.release();
        }

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

From source file:com.gitblit.tickets.BranchTicketService.java

License:Apache License

/**
 * Deletes a ticket from the repository.
 *
 * @param ticket//from  w ww.j a  v a 2  s  .c  om
 * @return true if successful
 */
@Override
protected synchronized boolean deleteTicketImpl(RepositoryModel repository, TicketModel ticket,
        String deletedBy) {
    if (ticket == null) {
        throw new RuntimeException("must specify a ticket!");
    }

    boolean success = false;
    Repository db = repositoryManager.getRepository(ticket.repository);
    try {
        RefModel ticketsBranch = getTicketsBranch(db);

        if (ticketsBranch == null) {
            throw new RuntimeException(BRANCH + " does not exist!");
        }
        String ticketPath = toTicketPath(ticket.number);

        TreeWalk treeWalk = null;
        try {
            ObjectId treeId = db.resolve(BRANCH + "^{tree}");

            // Create the in-memory index of the new/updated ticket
            DirCache index = DirCache.newInCore();
            DirCacheBuilder builder = index.builder();

            // Traverse HEAD to add all other paths
            treeWalk = new TreeWalk(db);
            int hIdx = -1;
            if (treeId != null) {
                hIdx = treeWalk.addTree(treeId);
            }
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1) {
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                }
                if (!path.startsWith(ticketPath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        final DirCacheEntry entry = new DirCacheEntry(path);
                        entry.setObjectId(hTree.getEntryObjectId());
                        entry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        builder.add(entry);
                    }
                }
            }

            // finish temporary in-core index used for this commit
            builder.finish();

            success = commitIndex(db, index, deletedBy, "- " + ticket.number);

        } catch (Throwable t) {
            log.error(MessageFormat.format("Failed to delete ticket {0,number,0} from {1}", ticket.number,
                    db.getDirectory()), t);
        } finally {
            // release the treewalk
            if (treeWalk != null) {
                treeWalk.close();
            }
        }
    } finally {
        db.close();
    }
    return success;
}

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

License:Apache License

/**
 * Deletes an issue from the repository.
 * /* www .  j a  v  a  2  s  .  com*/
 * @param repository
 * @param issueId
 * @return true if successful
 */
public static boolean deleteIssue(Repository repository, String issueId, String author) {
    boolean success = false;
    RefModel issuesBranch = getIssuesBranch(repository);

    if (issuesBranch == null) {
        throw new RuntimeException("gb-issues branch does not exist!");
    }

    if (StringUtils.isEmpty(issueId)) {
        throw new RuntimeException("must specify an issue id!");
    }

    String issuePath = getIssuePath(issueId);

    String message = "- " + issueId;
    try {
        ObjectId headId = repository.resolve(GB_ISSUES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the new/updated issue
            DirCache index = DirCache.newInCore();
            DirCacheBuilder dcBuilder = index.builder();
            // Traverse HEAD to add all other paths
            TreeWalk treeWalk = new TreeWalk(repository);
            int hIdx = -1;
            if (headId != null)
                hIdx = treeWalk.addTree(new RevWalk(repository).parseTree(headId));
            treeWalk.setRecursive(true);
            while (treeWalk.next()) {
                String path = treeWalk.getPathString();
                CanonicalTreeParser hTree = null;
                if (hIdx != -1)
                    hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
                if (!path.startsWith(issuePath)) {
                    // add entries from HEAD for all other paths
                    if (hTree != null) {
                        // create a new DirCacheEntry with data retrieved
                        // from HEAD
                        final DirCacheEntry dcEntry = new DirCacheEntry(path);
                        dcEntry.setObjectId(hTree.getEntryObjectId());
                        dcEntry.setFileMode(hTree.getEntryFileMode());

                        // add to temporary in-core index
                        dcBuilder.add(dcEntry);
                    }
                }
            }

            // release the treewalk
            treeWalk.release();

            // finish temporary in-core index used for this commit
            dcBuilder.finish();

            ObjectId indexTreeId = index.writeTree(odi);

            // Create a commit object
            PersonIdent ident = new PersonIdent(author, "gitblit@localhost");
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.CHARACTER_ENCODING);
            commit.setMessage(message);
            commit.setParentId(headId);
            commit.setTreeId(indexTreeId);

            // Insert the commit into the repository
            ObjectId commitId = odi.insert(commit);
            odi.flush();

            RevWalk revWalk = new RevWalk(repository);
            try {
                RevCommit revCommit = revWalk.parseCommit(commitId);
                RefUpdate ru = repository.updateRef(GB_ISSUES);
                ru.setNewObjectId(commitId);
                ru.setExpectedOldObjectId(headId);
                ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
                Result rc = ru.forceUpdate();
                switch (rc) {
                case NEW:
                case FORCED:
                case FAST_FORWARD:
                    success = true;
                    break;
                case REJECTED:
                case LOCK_FAILURE:
                    throw new ConcurrentRefUpdateException(JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
                default:
                    throw new JGitInternalException(MessageFormat.format(JGitText.get().updatingRefFailed,
                            GB_ISSUES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to delete issue {1} to {0}", issueId);
    }
    return success;
}

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

License:Apache License

/**
 * Creates an in-memory index of the issue change.
 * //from www  .j a  v a 2 s  .  c o m
 * @param repo
 * @param headId
 * @param change
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, String issuePath, Change change)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // Add any attachments to the temporary index
        if (change.hasAttachments()) {
            for (Attachment attachment : change.attachments) {
                // build a path name for the attachment and mark as ignored
                String path = issuePath + "/" + attachment.id;
                ignorePaths.add(path);

                // create an index entry for this attachment
                final DirCacheEntry dcEntry = new DirCacheEntry(path);
                dcEntry.setLength(attachment.content.length);
                dcEntry.setLastModified(change.created.getTime());
                dcEntry.setFileMode(FileMode.REGULAR_FILE);

                // insert object
                dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, attachment.content));

                // add to temporary in-core index
                dcBuilder.add(dcEntry);
            }
        }

        // Traverse HEAD to add all other paths
        TreeWalk treeWalk = new TreeWalk(repo);
        int hIdx = -1;
        if (headId != null)
            hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
        treeWalk.setRecursive(true);

        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1)
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            if (!ignorePaths.contains(path)) {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

                    // add to temporary in-core index
                    dcBuilder.add(dcEntry);
                }
            }
        }

        // release the treewalk
        treeWalk.release();

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

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

License:Apache License

/**
 * Returns all tree entries that do not match the ignore paths.
 *
 * @param db/*  w  w  w  .ja v a  2  s.  c o m*/
 * @param ignorePaths
 * @param dcBuilder
 * @throws IOException
 */
public static List<DirCacheEntry> getTreeEntries(Repository db, String branch, Collection<String> ignorePaths)
        throws IOException {
    List<DirCacheEntry> list = new ArrayList<DirCacheEntry>();
    TreeWalk tw = null;
    try {
        ObjectId treeId = db.resolve(branch + "^{tree}");
        if (treeId == null) {
            // branch does not exist yet
            return list;
        }
        tw = new TreeWalk(db);
        int hIdx = tw.addTree(treeId);
        tw.setRecursive(true);

        while (tw.next()) {
            String path = tw.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1) {
                hTree = tw.getTree(hIdx, CanonicalTreeParser.class);
            }
            if (!ignorePaths.contains(path)) {
                // add all other tree entries
                if (hTree != null) {
                    final DirCacheEntry entry = new DirCacheEntry(path);
                    entry.setObjectId(hTree.getEntryObjectId());
                    entry.setFileMode(hTree.getEntryFileMode());
                    list.add(entry);
                }
            }
        }
    } finally {
        if (tw != null) {
            tw.close();
        }
    }
    return list;
}

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

License:Apache License

/**
 * Creates an in-memory index of the push log entry.
 * /*from ww  w . ja v  a2s.  co  m*/
 * @param repo
 * @param headId
 * @param commands
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, Collection<ReceiveCommand> commands)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    long now = System.currentTimeMillis();
    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // add receive commands to the temporary index
        for (ReceiveCommand command : commands) {
            // use the ref names as the path names
            String path = command.getRefName();
            ignorePaths.add(path);

            StringBuilder change = new StringBuilder();
            change.append(command.getType().name()).append(' ');
            switch (command.getType()) {
            case CREATE:
                change.append(ObjectId.zeroId().getName());
                change.append(' ');
                change.append(command.getNewId().getName());
                break;
            case UPDATE:
            case UPDATE_NONFASTFORWARD:
                change.append(command.getOldId().getName());
                change.append(' ');
                change.append(command.getNewId().getName());
                break;
            case DELETE:
                change = null;
                break;
            }
            if (change == null) {
                // ref deleted
                continue;
            }
            String content = change.toString();

            // create an index entry for this attachment
            final DirCacheEntry dcEntry = new DirCacheEntry(path);
            dcEntry.setLength(content.length());
            dcEntry.setLastModified(now);
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // insert object
            dcEntry.setObjectId(inserter.insert(Constants.OBJ_BLOB, content.getBytes("UTF-8")));

            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }

        // Traverse HEAD to add all other paths
        TreeWalk treeWalk = new TreeWalk(repo);
        int hIdx = -1;
        if (headId != null)
            hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
        treeWalk.setRecursive(true);

        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1)
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            if (!ignorePaths.contains(path)) {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

                    // add to temporary in-core index
                    dcBuilder.add(dcEntry);
                }
            }
        }

        // release the treewalk
        treeWalk.release();

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.release();
    }
    return inCoreIndex;
}

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

License:Apache License

/**
 * Creates an in-memory index of the reflog entry.
 *
 * @param repo/* ww w  . ja v  a2 s .  co m*/
 * @param headId
 * @param commands
 * @return an in-memory index
 * @throws IOException
 */
private static DirCache createIndex(Repository repo, ObjectId headId, Collection<ReceiveCommand> commands)
        throws IOException {

    DirCache inCoreIndex = DirCache.newInCore();
    DirCacheBuilder dcBuilder = inCoreIndex.builder();
    ObjectInserter inserter = repo.newObjectInserter();

    long now = System.currentTimeMillis();
    Set<String> ignorePaths = new TreeSet<String>();
    try {
        // add receive commands to the temporary index
        for (ReceiveCommand command : commands) {
            // use the ref names as the path names
            String path = command.getRefName();
            ignorePaths.add(path);

            StringBuilder change = new StringBuilder();
            change.append(command.getType().name()).append(' ');
            switch (command.getType()) {
            case CREATE:
                change.append(ObjectId.zeroId().getName());
                change.append(' ');
                change.append(command.getNewId().getName());
                break;
            case UPDATE:
            case UPDATE_NONFASTFORWARD:
                change.append(command.getOldId().getName());
                change.append(' ');
                change.append(command.getNewId().getName());
                break;
            case DELETE:
                change = null;
                break;
            }
            if (change == null) {
                // ref deleted
                continue;
            }
            String content = change.toString();

            // create an index entry for this attachment
            final DirCacheEntry dcEntry = new DirCacheEntry(path);
            dcEntry.setLength(content.length());
            dcEntry.setLastModified(now);
            dcEntry.setFileMode(FileMode.REGULAR_FILE);

            // insert object
            dcEntry.setObjectId(
                    inserter.insert(org.eclipse.jgit.lib.Constants.OBJ_BLOB, content.getBytes("UTF-8")));

            // add to temporary in-core index
            dcBuilder.add(dcEntry);
        }

        // Traverse HEAD to add all other paths
        TreeWalk treeWalk = new TreeWalk(repo);
        int hIdx = -1;
        if (headId != null)
            hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
        treeWalk.setRecursive(true);

        while (treeWalk.next()) {
            String path = treeWalk.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1)
                hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
            if (!ignorePaths.contains(path)) {
                // add entries from HEAD for all other paths
                if (hTree != null) {
                    // create a new DirCacheEntry with data retrieved from
                    // HEAD
                    final DirCacheEntry dcEntry = new DirCacheEntry(path);
                    dcEntry.setObjectId(hTree.getEntryObjectId());
                    dcEntry.setFileMode(hTree.getEntryFileMode());

                    // add to temporary in-core index
                    dcBuilder.add(dcEntry);
                }
            }
        }

        // release the treewalk
        treeWalk.close();

        // finish temporary in-core index used for this commit
        dcBuilder.finish();
    } finally {
        inserter.close();
    }
    return inCoreIndex;
}

From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

/**
 * adds a new path with the specified stage to the index builder
 *
 * @param path//  w  w  w.  j av a  2 s  .  co m
 * @param p
 * @param stage
 * @param lastMod
 * @param len
 * @return the entry which was added to the index
 */
private DirCacheEntry add(byte[] path, CanonicalTreeParser p, int stage, long lastMod, long len) {
    if (p != null && !p.getEntryFileMode().equals(FileMode.TREE)) {
        DirCacheEntry e = new DirCacheEntry(path, stage);
        e.setFileMode(p.getEntryFileMode());
        e.setObjectId(p.getEntryObjectId());
        e.setLastModified(lastMod);
        e.setLength(len);
        this.builder.add(e);
        return e;
    }
    return null;
}

From source file:com.itemis.maven.plugins.unleash.scm.providers.merge.UnleashGitMerger.java

License:Eclipse Distribution License

private MergeResult<RawText> contentMerge(CanonicalTreeParser base, CanonicalTreeParser ours,
        CanonicalTreeParser theirs) throws IOException {
    InputStream localIn = getInputStream(ours.getEntryObjectId());
    InputStream remoteIn = getInputStream(theirs.getEntryObjectId());
    InputStream baseIn = getInputStream(base.getEntryObjectId());
    ByteArrayOutputStream resultOut = new ByteArrayOutputStream();

    this.mergeClient.merge(localIn, remoteIn, baseIn, resultOut);
    RawText resultText = new RawText(resultOut.toByteArray());

    List<RawText> sequences = new ArrayList<RawText>(1);
    sequences.add(resultText);/*from   w  w w . j a  v  a2  s  .  co  m*/
    MergeResult<RawText> result = new MergeResult<RawText>(sequences);
    result.add(0, 0, resultText.size(), ConflictState.NO_CONFLICT);

    return result;
}