Example usage for org.eclipse.jgit.lib Repository resolve

List of usage examples for org.eclipse.jgit.lib Repository resolve

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository resolve.

Prototype

@Nullable
public ObjectId resolve(String revstr)
        throws AmbiguousObjectException, IncorrectObjectTypeException, RevisionSyntaxException, IOException 

Source Link

Document

Parse a git revision string and return an object id.

Usage

From source file:org.uberfire.java.nio.fs.jgit.util.commands.SubdirectoryClone.java

License:Apache License

private List<RevCommit> getBranchCommits(final Repository repository, final RevWalk revWalk) {
    final List<RevCommit> branchTips = branches.stream().map(b -> {
        try {/*from  w  w  w  . ja  v  a 2s.  c o m*/
            return revWalk.parseCommit(repository.resolve(b));
        } catch (IOException ioe) {
            throw new IllegalArgumentException(
                    format("Unable to parse branch [%s] in repository [%s].", b, repository.getDirectory()));
        }
    }).collect(toList());
    return branchTips;
}

From source file:org.walkmod.git.constraints.JavaConstraintProvider.java

License:Open Source 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);
    ObjectId oid = repository.resolve(objectId);
    RevCommit commit = walk.parseCommit(oid);
    RevTree tree = walk.parseTree(commit.getTree().getId());

    CanonicalTreeParser oldTreeParser = new CanonicalTreeParser();
    ObjectReader oldReader = repository.newObjectReader();
    oldTreeParser.reset(oldReader, tree.getId());

    walk.dispose();/*w ww .  j  a  va 2  s .  c om*/
    walk.close();
    oldReader.close();
    return oldTreeParser;
}

From source file:org.walkmod.git.readers.GitFileReader.java

License:Open Source License

/**
 * Returns the list of files changed in the last commit.
 *
 * @param repository/*from w w w .j a  v  a2 s .c om*/
 * @return list of files changed in a commit
 * @throws IOException
 * @throws IncorrectObjectTypeException
 * @throws AmbiguousObjectException
 * @throws RevisionSyntaxException
 */
private static Set<String> getFilesInHEAD(Repository repository)
        throws RevisionSyntaxException, AmbiguousObjectException, IncorrectObjectTypeException, IOException {
    Set<String> list = new HashSet<String>();

    RevWalk rw = new RevWalk(repository);
    ObjectId oid = repository.resolve("HEAD");
    RevCommit commit = rw.parseCommit(oid);

    try {

        if (commit.getParentCount() == 0) {
            TreeWalk tw = new TreeWalk(repository);
            tw.reset();
            tw.setRecursive(true);
            tw.addTree(commit.getTree());
            while (tw.next()) {

                list.add(tw.getPathString());
            }
            tw.close();

        }
    } catch (Throwable t) {
        throw new RuntimeException("failed to determine files in commit!");
    } finally {
        rw.dispose();
        rw.close();
    }
    return list;
}

From source file:org.wso2.security.tools.scanner.dependency.js.reportpublisher.GitUploader.java

License:Open Source License

/**
 * Populate all the files to update, if the system should update.
 *///from w  w  w . java2  s . c o m
private boolean populateDiff() {
    try {
        gitRepo.fetch()
                .setCredentialsProvider(new UsernamePasswordCredentialsProvider(
                        new String(gitUploaderProperties.getGitUsername()),
                        new String(gitUploaderProperties.getGitPassword())))
                .call();
        Repository repo = gitRepo.getRepository();
        ObjectId fetchHead = repo.resolve("FETCH_HEAD^{tree}");
        ObjectId head = repo.resolve("HEAD^{tree}");
        ObjectReader reader = repo.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, head);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, fetchHead);
        List<DiffEntry> diffs = gitRepo.diff().setShowNameAndStatusOnly(true).setNewTree(newTreeIter)
                .setOldTree(oldTreeIter).call();
        return !diffs.isEmpty();
    } catch (GitAPIException | IOException e) {
        log.error("[JS_SEC_DAILY_SCAN]  " + "Security artifact repo pull action failed.", e);
    }
    return true;
}

From source file:pl.project13.jgit.DescribeCommand.java

License:Open Source License

RevCommit findHeadObjectId(@NotNull Repository repo) throws RuntimeException {
    try {//from   w  w  w. j a v  a 2s. co m
        ObjectId headId = repo.resolve("HEAD");

        RevWalk walk = new RevWalk(repo);
        RevCommit headCommit = walk.lookupCommit(headId);
        walk.dispose();

        log("HEAD is [", headCommit.getName(), "] ");
        return headCommit;
    } catch (IOException ex) {
        throw new RuntimeException("Unable to obtain HEAD commit!", ex);
    }
}

From source file:pl.project13.jgit.DescribeCommand.java

License:Open Source License

private Map<ObjectId, List<String>> findTagObjectIds(@NotNull Repository repo, boolean tagsFlag) {
    Map<ObjectId, List<DatedRevTag>> commitIdsToTags = newHashMap();

    RevWalk walk = new RevWalk(repo);
    try {//from www  .j a v  a  2 s .c  o m
        walk.markStart(walk.parseCommit(repo.resolve("HEAD")));

        List<Ref> tagRefs = Git.wrap(repo).tagList().call();
        String matchPattern = createMatchPattern();
        Pattern regex = Pattern.compile(matchPattern);
        log("Tag refs [", tagRefs, "]");

        for (Ref tagRef : tagRefs) {
            walk.reset();
            String name = tagRef.getName();
            if (!regex.matcher(name).matches()) {
                log("Skipping tagRef with name [", name, "] as it doesn't match [", matchPattern, "]");
                continue;
            }
            ObjectId resolvedCommitId = repo.resolve(name);

            // todo that's a bit of a hack...
            try {
                final RevTag revTag = walk.parseTag(resolvedCommitId);
                ObjectId taggedCommitId = revTag.getObject().getId();
                log("Resolved tag [", revTag.getTagName(), "] [", revTag.getTaggerIdent(), "], points at [",
                        taggedCommitId, "] ");

                // sometimes a tag, may point to another tag, so we need to unpack it
                while (isTagId(taggedCommitId)) {
                    taggedCommitId = walk.parseTag(taggedCommitId).getObject().getId();
                }

                if (commitIdsToTags.containsKey(taggedCommitId)) {
                    commitIdsToTags.get(taggedCommitId).add(new DatedRevTag(revTag));
                } else {
                    commitIdsToTags.put(taggedCommitId, newArrayList(new DatedRevTag(revTag)));
                }

            } catch (IncorrectObjectTypeException ex) {
                // it's an lightweight tag! (yeah, really)
                if (tagsFlag) {
                    // --tags means "include lightweight tags"
                    log("Including lightweight tag [", name, "]");

                    DatedRevTag datedRevTag = new DatedRevTag(resolvedCommitId, name);

                    if (commitIdsToTags.containsKey(resolvedCommitId)) {
                        commitIdsToTags.get(resolvedCommitId).add(datedRevTag);
                    } else {
                        commitIdsToTags.put(resolvedCommitId, newArrayList(datedRevTag));
                    }
                }
            } catch (Exception ignored) {
                error("Failed while parsing [", tagRef, "] -- ", Throwables.getStackTraceAsString(ignored));
            }
        }

        for (Map.Entry<ObjectId, List<DatedRevTag>> entry : commitIdsToTags.entrySet()) {
            log("key [", entry.getKey(), "], tags => [", entry.getValue(), "] ");
        }

        Map<ObjectId, List<String>> commitIdsToTagNames = transformRevTagsMapToDateSortedTagNames(
                commitIdsToTags);

        log("Created map: [", commitIdsToTagNames, "] ");

        return commitIdsToTagNames;
    } catch (Exception e) {
        log("Unable to locate tags\n[", Throwables.getStackTraceAsString(e), "]");
    } finally {
        walk.release();
    }

    return Collections.emptyMap();
}

From source file:pl.project13.jgit.JGitCommon.java

License:Open Source License

protected Map<ObjectId, List<DatedRevTag>> getCommitIdsToTags(@NotNull Repository repo,
        boolean includeLightweightTags, String matchPattern) {
    Map<ObjectId, List<DatedRevTag>> commitIdsToTags = new HashMap<>();

    try (RevWalk walk = new RevWalk(repo)) {
        walk.markStart(walk.parseCommit(repo.resolve("HEAD")));

        List<Ref> tagRefs = Git.wrap(repo).tagList().call();
        Pattern regex = Pattern.compile(matchPattern);
        log.info("Tag refs [{}]", tagRefs);

        for (Ref tagRef : tagRefs) {
            walk.reset();//from w  w  w  .j a v a  2 s .  c  o m
            String name = tagRef.getName();
            if (!regex.matcher(name).matches()) {
                log.info("Skipping tagRef with name [{}] as it doesn't match [{}]", name, matchPattern);
                continue;
            }
            ObjectId resolvedCommitId = repo.resolve(name);

            // TODO that's a bit of a hack...
            try {
                final RevTag revTag = walk.parseTag(resolvedCommitId);
                ObjectId taggedCommitId = revTag.getObject().getId();
                log.info("Resolved tag [{}] [{}], points at [{}] ", revTag.getTagName(),
                        revTag.getTaggerIdent(), taggedCommitId);

                // sometimes a tag, may point to another tag, so we need to unpack it
                while (isTagId(taggedCommitId)) {
                    taggedCommitId = walk.parseTag(taggedCommitId).getObject().getId();
                }

                if (commitIdsToTags.containsKey(taggedCommitId)) {
                    commitIdsToTags.get(taggedCommitId).add(new DatedRevTag(revTag));
                } else {
                    commitIdsToTags.put(taggedCommitId,
                            new ArrayList<>(Collections.singletonList(new DatedRevTag(revTag))));
                }

            } catch (IncorrectObjectTypeException ex) {
                // it's an lightweight tag! (yeah, really)
                if (includeLightweightTags) {
                    // --tags means "include lightweight tags"
                    log.info("Including lightweight tag [{}]", name);

                    DatedRevTag datedRevTag = new DatedRevTag(resolvedCommitId, name);

                    if (commitIdsToTags.containsKey(resolvedCommitId)) {
                        commitIdsToTags.get(resolvedCommitId).add(datedRevTag);
                    } else {
                        commitIdsToTags.put(resolvedCommitId,
                                new ArrayList<>(Collections.singletonList(datedRevTag)));
                    }
                }
            } catch (Exception ignored) {
                log.info("Failed while parsing [{}] -- ", tagRef, ignored);
            }
        }

        for (Map.Entry<ObjectId, List<DatedRevTag>> entry : commitIdsToTags.entrySet()) {
            log.info("key [{}], tags => [{}] ", entry.getKey(), entry.getValue());
        }
        return commitIdsToTags;
    } catch (Exception e) {
        log.info("Unable to locate tags", e);
    }
    return Collections.emptyMap();
}

From source file:playRepository.GitRepository.java

License:Apache License

static public List<FileDiff> getDiff(Repository repository, String rev) throws IOException {
    return getDiff(repository, repository.resolve(rev));
}

From source file:playRepository.GitRepository.java

License:Apache License

/**
 * Finds authors who have made changes by comparing the differences in the
 * revisions.//from  ww  w.  ja  va  2 s  .  c o m
 *
 * This method retrieves authors by mapping author names to email addresses
 * of the people who last modified the line.
 *
 * @param repository
 * @param revA
 * @param revB
 * @return
 * @throws IOException
 * @throws GitAPIException
 */
public static Set<User> getRelatedAuthors(Repository repository, String revA, String revB)
        throws IOException, GitAPIException, LimitExceededException {
    Set<User> authors = new HashSet<>();
    RevWalk revWalk = null;

    try {
        revWalk = new RevWalk(repository);
        RevCommit commitA = revWalk.parseCommit(repository.resolve(revA));
        RevCommit commitB = revWalk.parseCommit(repository.resolve(revB));
        List<DiffEntry> diffs = getDiffEntries(repository, commitA, commitB);

        if (diffs.size() > BLAME_FILE_LIMIT) {
            String msg = String.format(
                    "Reject to get related authors " + "from changes because of performance issue: The "
                            + "changes include %d files and it exceeds our limit " + "of '%d' files.",
                    diffs.size(), BLAME_FILE_LIMIT);
            throw new LimitExceededException(msg);
        }

        for (DiffEntry diff : diffs) {
            if (isTypeMatching(diff.getChangeType(), MODIFY, DELETE)) {
                authors.addAll(getAuthorsFromDiffEntry(repository, diff, commitA));
            }
            if (isTypeMatching(diff.getChangeType(), RENAME)) {
                authors.add(getAuthorFromFirstCommit(repository, diff.getOldPath(), commitA));
            }
        }
    } finally {
        if (revWalk != null) {
            revWalk.dispose();
        }
    }

    authors.remove(User.anonymous);
    return authors;
}

From source file:playRepository.GitRepository.java

License:Apache License

public static boolean canDeleteFromBranch(PullRequest pullRequest) {
    List<Ref> refs;/*from   w  ww. j a  va2  s .c o m*/
    Repository fromRepo = null; // repository that sent the pull request
    String currentBranch;
    try {
        fromRepo = buildGitRepository(pullRequest.fromProject);
        currentBranch = fromRepo.getFullBranch();
        refs = new Git(fromRepo).branchList().call();

        for (Ref branchRef : refs) {
            String branchName = branchRef.getName();
            if (branchName.equals(pullRequest.fromBranch) && !branchName.equals(currentBranch)) {
                RevWalk revWalk = new RevWalk(fromRepo);
                RevCommit commit = revWalk.parseCommit(fromRepo.resolve(branchName));
                String commitName = commit.name(); // fromBranch's head commit name
                revWalk.release();

                // check whether the target repository has the commit witch is the fromBranch's head commit.
                Repository toRepo = buildGitRepository(pullRequest.toProject);
                ObjectId toBranch = toRepo.resolve(commitName);
                if (toBranch != null) {
                    return true;
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (fromRepo != null) {
            fromRepo.close();
        }
    }

    return false;
}