Example usage for org.eclipse.jgit.revwalk RevWalk parseHeaders

List of usage examples for org.eclipse.jgit.revwalk RevWalk parseHeaders

Introduction

In this page you can find the example usage for org.eclipse.jgit.revwalk RevWalk parseHeaders.

Prototype

public void parseHeaders(RevObject obj) throws MissingObjectException, IOException 

Source Link

Document

Ensure the object's critical headers have been parsed.

Usage

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

License:Open Source License

/**
 * loads all involved models and diagrams for the given patchSet using the
 * given {@link Git} instance from the given git {@link Ref}.
 * //from ww w .j  a  va 2s  .  c  om
 * @param patchSet
 *            the patch set instance to store the involved models into
 * @param ref
 *            the git ref to the commit which contains the patch set.
 * @param git
 *            the git instance to use
 * @return a list containing the resource sets for the old and the new model
 *         resources.
 * @throws IOException
 */
private List<ResourceSet> loadInvolvedModelsAndDiagrams(PatchSet patchSet, Ref ref, Git git)
        throws IOException {

    String commitHash = ref.getObjectId().name();

    RevWalk revWalk = new RevWalk(git.getRepository());
    RevCommit newCommit = revWalk.parseCommit(ref.getObjectId());
    RevCommit oldCommit = newCommit.getParent(0);
    revWalk.parseHeaders(oldCommit);
    revWalk.close();

    String parentCommitHash = oldCommit.getId().name();

    URI repoURI = git.getRepository().getDirectory().toURI();
    String authority = repoURI.getAuthority();
    String path = repoURI.getPath();
    String repoPath = (authority != null ? authority + "/" : "") + (path != null ? path : "");
    if (repoPath.endsWith("/")) {
        repoPath = repoPath.substring(0, repoPath.length() - 1);
    }

    ResourceSet newResourceSet = createGitAwareResourceSet(commitHash, repoPath,
            Collections.<ResourceSet>emptyList());
    ResourceSet oldModelResourceSet = createGitAwareResourceSet(parentCommitHash, repoPath,
            Collections.<ResourceSet>emptyList());

    for (Patch patch : patchSet.getPatches()) {
        if (patch instanceof ModelPatch || patch instanceof DiagramPatch) {
            org.eclipse.emf.common.util.URI newUri = org.eclipse.emf.common.util.URI
                    .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + commitHash + "/"
                            + patch.getNewPath());

            org.eclipse.emf.common.util.URI oldUri = org.eclipse.emf.common.util.URI
                    .createURI(GitURIParser.GIT_COMMIT_SCHEME + "://" + repoPath + "/" + parentCommitHash + "/"
                            + patch.getOldPath());

            if (patch.getChangeType() != PatchChangeType.DELETE) {
                // if the patch has been deleted no new resource exists
                Resource newResource = newResourceSet.getResource(newUri, true);
                try {
                    applyResourceContent(newResource, patch, false);
                } catch (IOException e) {
                    throw new IOException(
                            MessageFormat.format("Could not load resource \"{0}\" for patch set {1}",
                                    newUri.toString(), patchSet.getId()),
                            e);
                }
            }

            if (patch.getChangeType() != PatchChangeType.ADD) {
                // if the patch has been added no old resource exists
                Resource oldResource = oldModelResourceSet.getResource(oldUri, true);
                try {
                    applyResourceContent(oldResource, patch, true);
                } catch (IOException e) {
                    throw new IOException(
                            MessageFormat.format("Could not load resource \"{0}\" for patch set {1}",
                                    oldUri.toString(), patchSet.getId()),
                            e);
                }
            }

        }
    }

    List<ResourceSet> resourceSets = new ArrayList<>(2);
    resourceSets.add(oldModelResourceSet);
    resourceSets.add(newResourceSet);
    return resourceSets;
}

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

License:Open Source License

/**
 * loads all patches of from the given list of {@link DiffEntry}s.
 * /* w ww  .ja v a 2 s.  c  o m*/
 * @param patchSet
 *            the patchSet to add the patches to.
 * @param ref
 *            the ref to the commit of the patch set.
 * @param repository
 *            the git repository instance
 * @throws RepositoryIOException
 */
private void loadPatches(PatchSet patchSet, Ref ref, Git git) throws RepositoryIOException {

    EList<Patch> patches = patchSet.getPatches();
    Repository repository = git.getRepository();

    try {

        RevWalk revWalk = new RevWalk(repository);
        RevCommit newCommit = revWalk.parseCommit(ref.getObjectId());
        RevCommit oldCommit = newCommit.getParent(0);
        revWalk.parseHeaders(oldCommit);
        ObjectReader objectReader = repository.newObjectReader();
        revWalk.close();

        CanonicalTreeParser newTreeIterator = new CanonicalTreeParser();
        newTreeIterator.reset(objectReader, newCommit.getTree().getId());
        CanonicalTreeParser oldTreeIterator = new CanonicalTreeParser();
        oldTreeIterator.reset(objectReader, oldCommit.getTree().getId());

        List<DiffEntry> diffs = git.diff().setOldTree(oldTreeIterator).setNewTree(newTreeIterator).call();

        for (DiffEntry diff : diffs) {

            String newPath = diff.getNewPath();
            String oldPath = diff.getOldPath();
            Patch patch = null;

            /*
             * only papyrus diagrams are supported for now, so models are in
             * .uml files, diagrams in .notation files
             */

            if (diff.getChangeType() != ChangeType.DELETE) {
                if (newPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (newPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            } else {
                if (oldPath.endsWith(".uml")) {
                    patch = modelReviewFactory.createModelPatch();

                } else if (oldPath.endsWith(".notation")) {
                    patch = modelReviewFactory.createDiagramPatch();
                } else {
                    patch = modelReviewFactory.createPatch();
                }
            }

            switch (diff.getChangeType()) {
            case ADD:
                patch.setChangeType(PatchChangeType.ADD);
                break;
            case COPY:
                patch.setChangeType(PatchChangeType.COPY);
                break;
            case DELETE:
                patch.setChangeType(PatchChangeType.DELETE);
                break;
            case MODIFY:
                patch.setChangeType(PatchChangeType.MODIFY);
                break;
            case RENAME:
                patch.setChangeType(PatchChangeType.RENAME);
                break;
            }

            patch.setNewPath(newPath);
            patch.setOldPath(oldPath);

            if (diff.getChangeType() != ChangeType.DELETE) {
                ObjectLoader objectLoader = repository.open(diff.getNewId().toObjectId());
                patch.setNewContent(objectLoader.getBytes());
            }
            if (diff.getChangeType() != ChangeType.ADD) {
                ObjectLoader objectLoader = repository.open(diff.getOldId().toObjectId());
                patch.setOldContent(objectLoader.getBytes());
            }
            patches.add(patch);

        }

    } catch (IOException e) {
        throw new RepositoryIOException(MessageFormat.format(
                "An IO error occured during loading the patches for patch set #{0}", patchSet.getId()), e);
    } catch (GitAPIException e) {
        throw new RepositoryIOException(
                MessageFormat.format("An JGit API error occured during loading the patches for patch set #{0}",
                        patchSet.getId()),
                e);
    }
}

From source file:com.gitblit.LuceneExecutor.java

License:Apache License

/**
 * Get the tree associated with the given commit.
 *
 * @param walk/*  www . j  a v a2  s.  c  o  m*/
 * @param commit
 * @return tree
 * @throws IOException
 */
private RevTree getTree(final RevWalk walk, final RevCommit commit) throws IOException {
    final RevTree tree = commit.getTree();
    if (tree != null) {
        return tree;
    }
    walk.parseHeaders(commit);
    return commit.getTree();
}

From source file:com.github.koraktor.mavanagaiata.git.jgit.JGitRepository.java

License:Open Source License

public GitTagDescription describe() throws GitRepositoryException {
    HashMap<RevCommit, String> tagCommits = new HashMap<RevCommit, String>();
    for (Map.Entry<String, RevTag> tag : this.getRawTags().entrySet()) {
        tagCommits.put((RevCommit) tag.getValue().getObject(), tag.getValue().getName());
    }/*w  ww .j  a v a  2s .c o m*/

    RevCommit start = this.getCommit(this.getHeadObject());
    RevWalk revWalk = this.getRevWalk();
    RevFlag seenFlag = revWalk.newFlag("SEEN");

    int distance = -1;
    GitTag nextTag = null;
    HashSet<RevCommit> commits = new HashSet<RevCommit>();
    commits.add(start);
    while (!commits.isEmpty()) {
        distance++;
        HashSet<RevCommit> nextCommits = new HashSet<RevCommit>();

        for (RevCommit currentCommit : commits) {
            try {
                revWalk.parseHeaders(currentCommit);
            } catch (IOException e) {
                throw new GitRepositoryException("Unable to parse headers of commit " + currentCommit.getName(),
                        e);
            }

            if (currentCommit.has(seenFlag)) {
                continue;
            }
            currentCommit.add(seenFlag);

            if (tagCommits.containsKey(currentCommit)) {
                nextTag = this.getTags().get(currentCommit.getId().getName());
                break;
            }

            if (currentCommit.getParents() != null) {
                nextCommits.addAll(Arrays.asList(currentCommit.getParents()));
            }
        }

        commits.clear();
        commits.addAll(nextCommits);
    }

    return new GitTagDescription(this, this.getHeadCommit(), nextTag, distance);
}

From source file:com.google.gerrit.server.edit.ChangeEditModifier.java

License:Apache License

private static ObjectId writeNewTree(TreeOperation op, RevWalk rw, ObjectInserter ins, RevCommit prevEdit,
        ObjectReader reader, String fileName, @Nullable String newFile, @Nullable final ObjectId content)
        throws IOException {
    DirCache newTree = readTree(reader, prevEdit);
    DirCacheEditor dce = newTree.editor();
    switch (op) {
    case DELETE_ENTRY:
        dce.add(new DeletePath(fileName));
        break;/*from   ww  w .jav a  2 s  . com*/

    case RENAME_ENTRY:
        rw.parseHeaders(prevEdit);
        TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), fileName, prevEdit.getTree());
        if (tw != null) {
            dce.add(new DeletePath(fileName));
            addFileToCommit(newFile, dce, tw);
        }
        break;

    case CHANGE_ENTRY:
        checkNotNull(content, "new content required");
        dce.add(new PathEdit(fileName) {
            @Override
            public void apply(DirCacheEntry ent) {
                if (ent.getRawMode() == 0) {
                    ent.setFileMode(FileMode.REGULAR_FILE);
                }
                ent.setObjectId(content);
            }
        });
        break;

    case RESTORE_ENTRY:
        if (prevEdit.getParentCount() == 0) {
            dce.add(new DeletePath(fileName));
            break;
        }

        RevCommit base = prevEdit.getParent(0);
        rw.parseHeaders(base);
        tw = TreeWalk.forPath(rw.getObjectReader(), fileName, base.getTree());
        if (tw == null) {
            dce.add(new DeletePath(fileName));
            break;
        }

        addFileToCommit(fileName, dce, tw);
        break;
    }
    dce.finish();
    return newTree.writeTree(ins);
}

From source file:com.google.gerrit.server.patch.AutoMerger.java

License:Apache License

/**
 * Perform an auto-merge of the parents of the given merge commit.
 *
 * @return auto-merge commit or {@code null} if an auto-merge commit
 *     couldn't be created. Headers of the returned RevCommit are parsed.
 *//*  w  w w . j av  a2  s.c  o m*/
public RevCommit merge(Repository repo, RevWalk rw, final ObjectInserter ins, RevCommit merge,
        ThreeWayMergeStrategy mergeStrategy) throws IOException {
    rw.parseHeaders(merge);
    String hash = merge.name();
    String refName = RefNames.REFS_CACHE_AUTOMERGE + hash.substring(0, 2) + "/" + hash.substring(2);
    Ref ref = repo.getRefDatabase().exactRef(refName);
    if (ref != null && ref.getObjectId() != null) {
        RevObject obj = rw.parseAny(ref.getObjectId());
        if (obj instanceof RevCommit) {
            return (RevCommit) obj;
        }
        return commit(repo, rw, ins, refName, obj, merge);
    }

    ResolveMerger m = (ResolveMerger) mergeStrategy.newMerger(repo, true);
    DirCache dc = DirCache.newInCore();
    m.setDirCache(dc);
    m.setObjectInserter(new ObjectInserter.Filter() {
        @Override
        protected ObjectInserter delegate() {
            return ins;
        }

        @Override
        public void flush() {
        }

        @Override
        public void close() {
        }
    });

    boolean couldMerge;
    try {
        couldMerge = m.merge(merge.getParents());
    } catch (IOException e) {
        // It is not safe to continue further down in this method as throwing
        // an exception most likely means that the merge tree was not created
        // and m.getMergeResults() is empty. This would mean that all paths are
        // unmerged and Gerrit UI would show all paths in the patch list.
        log.warn("Error attempting automerge " + refName, e);
        return null;
    }

    ObjectId treeId;
    if (couldMerge) {
        treeId = m.getResultTreeId();

    } else {
        RevCommit ours = merge.getParent(0);
        RevCommit theirs = merge.getParent(1);
        rw.parseBody(ours);
        rw.parseBody(theirs);
        String oursMsg = ours.getShortMessage();
        String theirsMsg = theirs.getShortMessage();

        String oursName = String.format("HEAD   (%s %s)", ours.abbreviate(6).name(),
                oursMsg.substring(0, Math.min(oursMsg.length(), 60)));
        String theirsName = String.format("BRANCH (%s %s)", theirs.abbreviate(6).name(),
                theirsMsg.substring(0, Math.min(theirsMsg.length(), 60)));

        MergeFormatter fmt = new MergeFormatter();
        Map<String, MergeResult<? extends Sequence>> r = m.getMergeResults();
        Map<String, ObjectId> resolved = new HashMap<>();
        for (Map.Entry<String, MergeResult<? extends Sequence>> entry : r.entrySet()) {
            MergeResult<? extends Sequence> p = entry.getValue();
            try (TemporaryBuffer buf = new TemporaryBuffer.LocalFile(null, 10 * 1024 * 1024)) {
                fmt.formatMerge(buf, p, "BASE", oursName, theirsName, UTF_8.name());
                buf.close();

                try (InputStream in = buf.openInputStream()) {
                    resolved.put(entry.getKey(), ins.insert(Constants.OBJ_BLOB, buf.length(), in));
                }
            }
        }

        DirCacheBuilder builder = dc.builder();
        int cnt = dc.getEntryCount();
        for (int i = 0; i < cnt;) {
            DirCacheEntry entry = dc.getEntry(i);
            if (entry.getStage() == 0) {
                builder.add(entry);
                i++;
                continue;
            }

            int next = dc.nextEntry(i);
            String path = entry.getPathString();
            DirCacheEntry res = new DirCacheEntry(path);
            if (resolved.containsKey(path)) {
                // For a file with content merge conflict that we produced a result
                // above on, collapse the file down to a single stage 0 with just
                // the blob content, and a randomly selected mode (the lowest stage,
                // which should be the merge base, or ours).
                res.setFileMode(entry.getFileMode());
                res.setObjectId(resolved.get(path));

            } else if (next == i + 1) {
                // If there is exactly one stage present, shouldn't be a conflict...
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());

            } else if (next == i + 2) {
                // Two stages suggests a delete/modify conflict. Pick the higher
                // stage as the automatic result.
                entry = dc.getEntry(i + 1);
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());

            } else {
                // 3 stage conflict, no resolve above
                // Punt on the 3-stage conflict and show the base, for now.
                res.setFileMode(entry.getFileMode());
                res.setObjectId(entry.getObjectId());
            }
            builder.add(res);
            i = next;
        }
        builder.finish();
        treeId = dc.writeTree(ins);
    }
    ins.flush();

    return commit(repo, rw, ins, refName, treeId, merge);
}

From source file:com.google.gerrit.server.patch.AutoMerger.java

License:Apache License

private RevCommit commit(Repository repo, RevWalk rw, ObjectInserter ins, String refName, ObjectId tree,
        RevCommit merge) throws IOException {
    rw.parseHeaders(merge);
    // For maximum stability, choose a single ident using the committer time of
    // the input commit, using the server name and timezone.
    PersonIdent ident = new PersonIdent(gerritIdent, merge.getCommitterIdent().getWhen(),
            gerritIdent.getTimeZone());// www .  j a v a2s.  co m
    CommitBuilder cb = new CommitBuilder();
    cb.setAuthor(ident);
    cb.setCommitter(ident);
    cb.setTreeId(tree);
    cb.setMessage("Auto-merge of " + merge.name() + '\n');
    for (RevCommit p : merge.getParents()) {
        cb.addParentId(p);
    }
    ObjectId commitId;
    commitId = ins.insert(cb);
    if (save) {
        ins.flush();

        RefUpdate ru = repo.updateRef(refName);
        ru.setNewObjectId(commitId);
        ru.disableRefLog();
        ru.forceUpdate();
    }
    return rw.parseCommit(commitId);
}

From source file:com.google.gitiles.TimeCache.java

License:Open Source License

Long getTime(final RevWalk walk, final ObjectId id) throws IOException {
    try {//from w  ww  .  ja va  2 s.c  o m
        return cache.get(id, new Callable<Long>() {
            @Override
            public Long call() throws IOException {
                RevObject o = walk.parseAny(id);
                while (o instanceof RevTag) {
                    RevTag tag = (RevTag) o;
                    PersonIdent ident = tag.getTaggerIdent();
                    if (ident != null) {
                        return ident.getWhen().getTime() / 1000;
                    }
                    o = tag.getObject();
                    walk.parseHeaders(o);
                }
                if (o.getType() == Constants.OBJ_COMMIT) {
                    return Long.valueOf(((RevCommit) o).getCommitTime());
                }
                return Long.MIN_VALUE;
            }
        });
    } catch (ExecutionException e) {
        Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
        throw new IOException(e);
    }
}

From source file:com.googlesource.gerrit.plugins.findowners.OwnersValidator.java

License:Apache License

/**
 * Find all TreeWalk entries which differ between the commit and its parents. If a TreeWalk entry
 * is found this method calls the onVisit() method of the class TreeWalkVisitor.
 *///w w  w .  ja v a 2s.co  m
private static void visitChangedEntries(RevCommit c, RevWalk revWalk, TreeWalkVisitor visitor)
        throws IOException {
    try (TreeWalk tw = new TreeWalk(revWalk.getObjectReader())) {
        tw.setRecursive(true);
        tw.setFilter(TreeFilter.ANY_DIFF);
        tw.addTree(c.getTree());
        if (c.getParentCount() > 0) {
            for (RevCommit p : c.getParents()) {
                if (p.getTree() == null) {
                    revWalk.parseHeaders(p);
                }
                tw.addTree(p.getTree());
            }
            while (tw.next()) {
                if (isDifferentToAllParents(c, tw)) {
                    visitor.onVisit(tw);
                }
            }
        } else {
            while (tw.next()) {
                visitor.onVisit(tw);
            }
        }
    }
}

From source file:com.googlesource.gerrit.plugins.uploadvalidator.CommitUtils.java

License:Apache License

/**
 * This method spots all TreeWalk entries which differ between the passed commit and its parents.
 * If a TreeWalk entry is found this method calls the onVisit() method of the class
 * TreeWalkVisitor.//  www. j av  a 2  s  . c  om
 *
 * @param repo The repository
 * @param c The commit
 * @param visitor A TreeWalkVisitor with the desired action
 * @throws IOException
 */
public static void visitChangedEntries(Repository repo, RevCommit c, RevWalk revWalk, TreeWalkVisitor visitor)
        throws IOException {
    try (TreeWalk tw = new TreeWalk(revWalk.getObjectReader())) {
        tw.setRecursive(true);
        tw.setFilter(TreeFilter.ANY_DIFF);
        tw.addTree(c.getTree());
        if (c.getParentCount() > 0) {
            for (RevCommit p : c.getParents()) {
                if (p.getTree() == null) {
                    revWalk.parseHeaders(p);
                }
                tw.addTree(p.getTree());
            }
            while (tw.next()) {
                if (isDifferentToAllParents(c, tw)) {
                    visitor.onVisit(tw);
                }
            }
        } else {
            while (tw.next()) {
                visitor.onVisit(tw);
            }
        }
    }
}