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

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

Introduction

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

Prototype

@NonNull
public RevCommit parseCommit(AnyObjectId id)
        throws MissingObjectException, IncorrectObjectTypeException, IOException 

Source Link

Document

Locate a reference to a commit and immediately parse its content.

Usage

From source file:RefNode.java

License:Open Source License

public static void createNode(RevWalk walk, Ref ref, boolean recur) throws IOException {
    String key = ref.getName();//from ww  w .  ja  v  a2  s. co  m
    ObjectId id = ref.getObjectId();
    Node node;

    if (!nodeMap.containsKey(key)) {
        // create new ref node
        node = new RefNode(key);

        // determine color
        if (key.contains("/heads/")) {
            node.setBackground(new Color(240, 255, 240));
            node.setForeground(new Color(0, 127, 0));
        } else if (key.contains("/tags/")) {
            node.setBackground(new Color(255, 255, 240));
            node.setForeground(new Color(127, 127, 0));
        } else if (key.contains("/remotes/")) {
            node.setBackground(new Color(240, 240, 240));
            node.setForeground(new Color(0, 0, 0));
        } else {
            node.setBackground(new Color(255, 240, 240));
            node.setForeground(new Color(127, 0, 0));
        }

        if (recur) {
            // add parent node
            RevCommit commit = walk.parseCommit(id);
            node.addParent(Node.createNode(walk, commit, recur));
        }
    }
}

From source file:Node.java

License:Open Source License

public static Node createNode(RevWalk walk, ObjectId id, boolean recur) throws IOException {
    String key = id.getName();/*from  ww  w.j a  v a 2s .  c  om*/
    RevCommit commit;
    Node node;

    if (nodeMap.containsKey(key)) {
        // commit node was already mapped
        node = nodeMap.get(key);
    } else {
        // create new commit node
        commit = walk.parseCommit(id);
        node = new Node(key, commit.getAuthorIdent().getEmailAddress(), commit.getCommitTime(),
                commit.getFullMessage(), commit.getShortMessage());
        node.setBackground(new Color(240, 240, 255));
        node.setForeground(new Color(0, 0, 127));

        if (recur) {
            // add parent nodes
            for (ObjectId parentCommit : commit.getParents())
                node.addParent(Node.createNode(walk, parentCommit, recur));
        }
    }

    return node;
}

From source file:ShowFileDiff.java

License:Apache License

private static AbstractTreeIterator prepareTreeParser(Repository repository, String objectId)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {
    // from the commit we can build the tree which allows us to construct the TreeParser
    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(ObjectId.fromString(objectId));
    RevTree tree = walk.parseTree(commit.getTree().getId());

    CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    ObjectReader oldReader = repository.newObjectReader();
    try {//  ww  w .  j a va2 s . c o  m
        oldTreeParser.reset(oldReader, tree.getId());
    } finally {
        oldReader.release();
    }

    walk.dispose();

    return oldTreeParser;
}

From source file:actors.PostReceiveActor.java

License:Apache License

protected Collection<? extends RevCommit> parseCommitsFrom(ReceiveCommand command, Project project) {
    Repository repository = GitRepository.buildGitRepository(project);
    List<RevCommit> list = new ArrayList<>();

    try {//from w w  w  .  j  a  va2s.  c  om
        ObjectId endRange = command.getNewId();
        ObjectId startRange = command.getOldId();

        RevWalk rw = new RevWalk(repository);
        rw.markStart(rw.parseCommit(endRange));
        if (startRange.equals(ObjectId.zeroId())) {
            // maybe this is a tag or an orphan branch
            list.add(rw.parseCommit(endRange));
            rw.dispose();
            return list;
        } else {
            rw.markUninteresting(rw.parseCommit(startRange));
        }

        for (RevCommit rev : rw) {
            list.add(rev);
        }
        rw.dispose();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return list;
}

From source file:am.ik.categolj3.api.git.GitStore.java

License:Apache License

void syncHead() {
    log.info("Syncing HEAD...");

    ObjectId oldHead = this.currentHead.get();
    ObjectId newHead = this.head();

    try (Repository repository = this.git.getRepository()) {
        DiffFormatter diffFormatter = new DiffFormatter(System.out);
        diffFormatter.setRepository(repository);
        RevWalk walk = new RevWalk(repository);
        try {//from   w w w.j a  v a 2s  . c  o m
            RevCommit fromCommit = walk.parseCommit(oldHead);
            RevCommit toCommit = walk.parseCommit(newHead);
            List<DiffEntry> list = diffFormatter.scan(fromCommit.getTree(), toCommit.getTree());

            list.forEach(diff -> {
                log.info("[{}]\tnew={}\told={}", diff.getChangeType(), diff.getNewPath(), diff.getOldPath());
                if (diff.getOldPath() != null) {
                    Path path = Paths
                            .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getOldPath());
                    if (Entry.isPublic(path)) {
                        Long entryId = Entry.parseEntryId(path);
                        log.info("evict Entry({})", entryId);
                        this.entryCache.evict(entryId);
                    }
                }
                if (diff.getNewPath() != null) {
                    Path path = Paths
                            .get(gitProperties.getBaseDir().getAbsolutePath() + "/" + diff.getNewPath());
                    this.loadEntry(path).ifPresent(entry -> {
                        log.info("put Entry({})", entry.getEntryId());
                        this.entryCache.put(entry.getEntryId(), entry);
                    });
                }
            });
        } finally {
            walk.dispose();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

    this.currentHead.set(newHead);
}

From source file:at.ac.tuwien.inso.subcat.miner.GitMiner.java

License:Open Source License

private void _run() throws IOException, MinerException, SQLException {
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository = builder.setGitDir(new File(settings.srcLocalPath, ".git")).readEnvironment()
            .findGitDir().build();//from   w  w  w  .ja  va2s . c  o  m

    /*
    Map<String,Ref> refs = repository.getAllRefs();
    for (Map.Entry<String, Ref> ref : refs.entrySet ()) {
       System.out.println (ref.getKey ());
    }
    */

    Ref head = repository.getRef(startRef);
    if (head == null) {
        throw new MinerException("Unknown reference: '" + startRef + "'");
    }

    RevWalk walk = new RevWalk(repository);
    RevCommit commit = walk.parseCommit(head.getObjectId());
    walk.markStart(commit);
    walk.sort(RevSort.REVERSE);

    // count commit: (fast)
    int commitCount = 0;
    Iterator<RevCommit> iter = walk.iterator();
    while (iter.hasNext()) {
        iter.next();
        commitCount++;
    }

    emitTasksTotal(commitCount);

    // process commits: (slow)
    walk.reset();
    walk.markStart(commit);
    walk.sort(RevSort.REVERSE);

    Map<String, ManagedFile> fileCache = new HashMap<String, ManagedFile>();

    for (RevCommit rev : walk) {
        if (stopped == true) {
            break;
        }

        processCommit(repository, walk, rev, fileCache);
    }

    walk.dispose();
    repository.close();
}

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;//  w  w  w .  j  a va2s  . 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:at.bitandart.zoubek.mervin.gerrit.GerritReviewRepositoryService.java

License:Open Source License

@SuppressWarnings("restriction")
@Override//from   w  ww.j a va2  s  .  c o m
public List<IReviewDescriptor> getReviews(URI uri) throws InvalidReviewRepositoryException {

    List<IReviewDescriptor> changeIds = new LinkedList<>();

    try {
        // connect to the local git repository
        Git git = Git.open(new File(uri));

        try {
            // Assume that origin refers to the remote gerrit repository
            // list all remote refs from origin
            Collection<Ref> remoteRefs = git.lsRemote().setTimeout(60).call();

            Pattern changeRefPattern = Pattern.compile(CHANGE_REF_PATTERN);

            // search for change refs
            for (Ref ref : remoteRefs) {

                Matcher matcher = changeRefPattern.matcher(ref.getName());
                if (matcher.matches()) {
                    String changePk = matcher.group(CHANGE_REF_PATTERN_GROUP_CHANGE_PK);
                    String changeId = "<unknown>";
                    GerritReviewDescriptor reviewDescriptor;
                    try {
                        reviewDescriptor = new GerritReviewDescriptor(Integer.parseInt(changePk), changeId);
                    } catch (NumberFormatException nfe) {
                        // FIXME ignore it or throw an exception?
                        break;
                    }

                    if (!changeIds.contains(reviewDescriptor)) {
                        changeIds.add(reviewDescriptor);

                        /*
                         * the change id is present in all commit messages,
                         * so we extract it from the commit message of the
                         * current ref
                         */
                        FetchResult fetchResult = git.fetch().setRefSpecs(new RefSpec(ref.getName())).call();

                        Ref localRef = fetchResult.getAdvertisedRef(ref.getName());
                        RevWalk revWalk = new RevWalk(git.getRepository());
                        RevCommit commit = revWalk.parseCommit(localRef.getObjectId());
                        String[] paragraphs = commit.getFullMessage().split("\n");
                        String lastParagraph = paragraphs[paragraphs.length - 1];
                        Pattern pattern = Pattern.compile(".*Change-Id: (I[^ \n]*).*");
                        Matcher changeIdMatcher = pattern.matcher(lastParagraph);

                        if (changeIdMatcher.matches()) {
                            changeId = changeIdMatcher.group(1);
                            reviewDescriptor.setChangeId(changeId);
                            ;
                        } else {
                            logger.warn(MessageFormat.format(
                                    "Could not find the change id for Gerrit change with primary key {0}",
                                    changePk));
                        }
                        revWalk.close();
                    }
                }
            }

        } catch (GitAPIException e) {
            throw new RepositoryIOException("Error during loading all remote changes", e);
        }

    } catch (IOException e) {
        throw new InvalidReviewRepositoryException("Could not open local git repository", e);
    }
    return changeIds;
}

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   w  w w  .  java  2  s . 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.
 * /*from ww  w.  ja  va  2s . co  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);
    }
}