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.nbgit.util.GitCommand.java

License:Open Source License

public static RepositoryRevision.Walk getLogMessages(String rootPath, Set<File> files, String fromRevision,
        String toRevision, boolean showMerges, OutputLogger logger) {
    File root = new File(rootPath);
    Repository repo = Git.getInstance().getRepository(root);
    RepositoryRevision.Walk walk = new RepositoryRevision.Walk(repo);

    try {//from ww w .  jav  a  2s . c  om
        if (fromRevision == null) {
            fromRevision = Constants.HEAD;
        }
        ObjectId from = repo.resolve(fromRevision);
        if (from == null) {
            return null;
        }
        walk.markStart(walk.parseCommit(from));
        ObjectId to = toRevision != null ? repo.resolve(toRevision) : null;
        if (to != null) {
            walk.markUninteresting(walk.parseCommit(to));
        }
        List<PathFilter> paths = new ArrayList<PathFilter>();
        for (File file : files) {
            String path = getRelative(root, file);

            if (!(path.length() == 0)) {
                paths.add(PathFilter.create(path));
            }
        }

        if (!paths.isEmpty()) {
            walk.setTreeFilter(PathFilterGroup.create(paths));
        }
        if (!showMerges) {
            walk.setRevFilter(RevFilter.NO_MERGES);
        }
    } catch (IOException ioe) {
        return null;
    }

    return walk;
}

From source file:org.nbgit.util.GitCommand.java

License:Open Source License

public static List<String[]> getRevisionsForFile(File root, File[] files, int limit) {
    Repository repo = Git.getInstance().getRepository(root);
    RevWalk walk = new RevWalk(repo);
    List<String[]> revs = new ArrayList<String[]>();

    try {//from   ww w  .j a v  a2s .  c  om
        ObjectId from = repo.resolve(Constants.HEAD);
        if (from == null) {
            return null;
        }
        walk.markStart(walk.parseCommit(from));

        if (files != null) {
            List<PathFilter> paths = new ArrayList<PathFilter>();
            for (File file : files) {
                String path = getRelative(root, file);

                if (!(path.length() == 0)) {
                    paths.add(PathFilter.create(path));
                }
            }

            if (!paths.isEmpty()) {
                walk.setTreeFilter(PathFilterGroup.create(paths));
            }
        }

        for (RevCommit rev : walk) {
            revs.add(new String[] { rev.getShortMessage(), rev.getId().name() });
            if (--limit <= 0) {
                break;
            }
        }

    } catch (IOException ioe) {
    }

    return revs;
}

From source file:org.nbgit.util.HtmlFormatter.java

License:Open Source License

/**
 * Applies custom format.//from w  w  w  . j a  v a2 s. c  o  m
 */
private String formatAnnotation(StatusInfo info, File file) {
    String statusString = ""; // NOI18N
    int status = info.getStatus();
    if (status != StatusInfo.STATUS_VERSIONED_UPTODATE) {
        statusString = info.getShortStatusText();
    }
    String revisionString = ""; // NOI18N
    String binaryString = ""; // NOI18N

    if (needRevisionForFormat) {
        if ((status & StatusInfo.STATUS_NOTVERSIONED_EXCLUDED) == 0) {
            try {
                File root = Git.getInstance().getTopmostManagedParent(file);
                Repository repo = Git.getInstance().getRepository(root);
                ObjectId branch = repo.resolve(repo.getFullBranch());
                String absPath = file.getAbsolutePath();
                String relPath = absPath.replace(root.getAbsolutePath(), "");
                RevWalk walk = new RevWalk(repo);
                RevCommit start = walk.parseCommit(branch);
                TreeFilter filter = PathFilter.create(relPath);

                walk.setTreeFilter(filter);
                walk.markStart(start);

                for (RevCommit commit : walk) {
                    revisionString = commit.getId().name();
                    break;
                }
                walk.dispose();

            } catch (IOException ex) {
                NotifyDescriptor notification = new NotifyDescriptor.Message(ex,
                        NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notifyLater(notification);
            }
        }
    }
    String stickyString = null;
    if (stickyString == null) {
        stickyString = "";
    }
    Object[] arguments = new Object[] { revisionString, statusString, stickyString, };

    String annotation = format.format(arguments, new StringBuffer(), null).toString().trim();
    if (annotation.equals(emptyFormat)) {
        return "";
    } else {
        return " " + annotation;
    }
}

From source file:org.ossmeter.platform.vcs.git.GitManager.java

License:Open Source License

/**
 * To set the startRevision to the first commit, use 'null'
 * FIXME: This should HANDLE the exception probably..
 *///  w  w w. j  a  va2s  . co  m
@Override
public VcsRepositoryDelta getDelta(VcsRepository repository, String startRevision, String endRevision)
        throws Exception {
    // Clone into local repo
    Git git = getGit((GitRepository) repository);

    VcsRepositoryDelta vcsDelta = new VcsRepositoryDelta();
    vcsDelta.setRepository(repository);

    Repository repo = git.getRepository();
    RevWalk walk = new RevWalk(repo);

    Iterable<RevCommit> logs = git.log().call();
    Iterator<RevCommit> iterator = logs.iterator();

    boolean foundStart = false;
    boolean foundEnd = false;

    List<RevCommit> commits = new ArrayList<RevCommit>();

    // Reorder the commits (currently they are latest first)
    while (iterator.hasNext()) {
        commits.add(0, walk.parseCommit(iterator.next()));
    }

    for (int i = 0; i < commits.size(); i++) {
        RevCommit commit = commits.get(i);
        RevCommit prevCommit = i - 1 < 0 ? null : commits.get(i - 1);

        if (startRevision == null || commit.getId().getName().equals(startRevision)) {
            foundStart = true;
        }
        if (commit.getId().getName().equals(endRevision)) {
            foundEnd = true;
        }

        VcsCommit vcsCommit = null;
        if (foundStart) {
            // Setup the meta data for the commit
            vcsCommit = new VcsCommit();
            vcsCommit.setRevision(commit.getId().getName());
            vcsCommit.setMessage(commit.getFullMessage());
            vcsCommit.setAuthor(commit.getAuthorIdent().getName());
            vcsCommit.setDelta(vcsDelta);
            int date = commit.getCommitTime();
            long datelong = (long) date * (long) 1000;
            vcsCommit.setJavaDate(new java.util.Date(datelong));
            vcsDelta.getCommits().add(vcsCommit);

            if (prevCommit != null) {
                // Do a diff against the succeeding commit
                ObjectId thisCommitId = repo.resolve(commit.getId().getName() + "^{tree}");
                ObjectId prevCommitId = repo.resolve(prevCommit.getId().getName() + "^{tree}");

                ObjectReader reader = repo.newObjectReader();

                CanonicalTreeParser currentTreeIter = new CanonicalTreeParser();
                currentTreeIter.reset(reader, thisCommitId);

                CanonicalTreeParser prevTreeIter = new CanonicalTreeParser();
                prevTreeIter.reset(reader, prevCommitId);

                List<DiffEntry> diffs = git.diff().setNewTree(currentTreeIter).setOldTree(prevTreeIter).call();

                for (DiffEntry diff : diffs) {
                    VcsChangeType change = convertChangeType(diff.getChangeType());
                    if (change == null)
                        continue;
                    VcsCommitItem item = new VcsCommitItem();
                    String path = diff.getNewPath();
                    if (change.equals(VcsChangeType.DELETED)) {
                        path = diff.getOldPath();
                    }
                    item.setPath(path);
                    item.setChangeType(change);
                    item.setCommit(vcsCommit);
                    vcsCommit.getItems().add(item);
                }
            } else {
                // First commit: everything is ADDED
                //                vcsCommit = new VcsCommit();
                TreeWalk treeWalk = new TreeWalk(repo);
                treeWalk.addTree(commit.getTree());
                while (treeWalk.next()) {
                    if (treeWalk.isSubtree()) {
                        treeWalk.enterSubtree();
                    } else {
                        VcsCommitItem item = new VcsCommitItem();
                        item.setPath(treeWalk.getPathString());
                        item.setChangeType(VcsChangeType.ADDED);
                        item.setCommit(vcsCommit);
                        vcsCommit.getItems().add(item);
                    }
                }
            }
        }

        if (foundEnd) {
            break;
        }
    }

    return vcsDelta;
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

/**
 * Get the commit with this commit id.//  ww w  .  j a  v a2s.c  om
 * Caveats:
 *   - If commit modifies more than maxNumberFilesInACommit, throws an exception
 *   - If one of the file diffs exceeds maxSizeOfDiff, the diffText is discarded
 *
 * @param id    The SHA1 hash that identifies a git commit.
 * @returns Commit    The corresponding Commit, or null.
 */
@Override
public Commit getCommit(String id) {
    try (Git git = openRepository()) {
        /* Using JGit, this commit will be the first entry in the log beginning at id. */
        Repository repo = git.getRepository();
        Iterable<RevCommit> jgitCommits = git.log().add(repo.resolve(id)).call();
        Iterator<RevCommit> itr = jgitCommits.iterator();

        if (!itr.hasNext())
            return null;
        RevCommit jgitCommit = itr.next();

        /* Extract metadata. */
        Developer author = new Developer(jgitCommit.getAuthorIdent().getName(),
                jgitCommit.getAuthorIdent().getEmailAddress());
        Developer committer = new Developer(jgitCommit.getCommitterIdent().getName(),
                jgitCommit.getCommitterIdent().getEmailAddress());
        TimeZone authorTimeZone = jgitCommit.getAuthorIdent().getTimeZone();
        TimeZone committerTimeZone = jgitCommit.getCommitterIdent().getTimeZone();

        String msg = collectConfig.isCollectingCommitMessages() ? jgitCommit.getFullMessage().trim() : "";
        String hash = jgitCommit.getName().toString();
        List<String> parents = Arrays.stream(jgitCommit.getParents()).map(rc -> rc.getName().toString())
                .collect(Collectors.toList());

        GregorianCalendar authorDate = new GregorianCalendar();
        authorDate.setTime(jgitCommit.getAuthorIdent().getWhen());
        authorDate.setTimeZone(jgitCommit.getAuthorIdent().getTimeZone());

        GregorianCalendar committerDate = new GregorianCalendar();
        committerDate.setTime(jgitCommit.getCommitterIdent().getWhen());
        committerDate.setTimeZone(jgitCommit.getCommitterIdent().getTimeZone());

        boolean isMerge = (jgitCommit.getParentCount() > 1);

        Set<String> branches = getBranches(git, hash);
        boolean isCommitInMainBranch = branches.contains(this.mainBranchName);

        /* Create one of our Commit's based on the jgitCommit metadata. */
        Commit commit = new Commit(hash, author, committer, authorDate, authorTimeZone, committerDate,
                committerTimeZone, msg, parents, isMerge, branches, isCommitInMainBranch);

        /* Convert each of the associated DiffEntry's to a Modification. */
        List<DiffEntry> diffsForTheCommit = diffsForTheCommit(repo, jgitCommit);
        if (diffsForTheCommit.size() > maxNumberFilesInACommit) {
            String errMsg = "Commit " + id + " touches more than " + maxNumberFilesInACommit + " files";
            log.error(errMsg);
            throw new RepoDrillerException(errMsg);
        }

        for (DiffEntry diff : diffsForTheCommit) {
            if (this.diffFiltersAccept(diff)) {
                Modification m = this.diffToModification(repo, diff);
                commit.addModification(m);
            }
        }

        return commit;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("error detailing " + id + " in " + path, e);
    }
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

private List<DiffEntry> diffsForTheCommit(Repository repo, RevCommit commit) throws IOException {

    AnyObjectId currentCommit = repo.resolve(commit.getName());
    AnyObjectId parentCommit = commit.getParentCount() > 0 ? repo.resolve(commit.getParent(0).getName()) : null;

    return this.getDiffBetweenCommits(repo, parentCommit, currentCommit);
}

From source file:org.repodriller.scm.GitRepository.java

License:Apache License

@Override
public List<Modification> getDiffBetweenCommits(String priorCommitHash, String laterCommitHash) {
    try (Git git = openRepository()) {
        Repository repo = git.getRepository();
        AnyObjectId priorCommit = repo.resolve(priorCommitHash);
        AnyObjectId laterCommit = repo.resolve(laterCommitHash);

        List<DiffEntry> diffs = this.getDiffBetweenCommits(repo, priorCommit, laterCommit);
        List<Modification> modifications = diffs.stream().map(diff -> {
            try {
                return this.diffToModification(repo, diff);
            } catch (IOException e) {
                throw new RuntimeException(
                        "error diffing " + priorCommitHash + " and " + laterCommitHash + " in " + path, e);
            }//from   w w w  .  ja v a2 s.  c  om
        }).collect(Collectors.toList());
        return modifications;
    } catch (Exception e) {
        throw new RuntimeException(
                "error diffing " + priorCommitHash + " and " + laterCommitHash + " in " + path, e);
    }
}

From source file:org.thiesen.ant.git.GitInfoExtractor.java

License:Open Source License

private static RevCommit getHead(final Repository r) throws IOException {
    final ObjectId headId = r.resolve(Constants.HEAD);
    return getCommit(r, headId);
}

From source file:org.uberfire.java.nio.fs.jgit.JGitSubdirectoryCloneTest.java

License:Apache License

private void mergeCommit(final Git origin, final String targetBranchName, final String sourceBranchName,
        final TestFile... testFiles) throws Exception {
    final Repository repo = origin.getRepository();
    final org.eclipse.jgit.api.Git git = org.eclipse.jgit.api.Git.wrap(repo);

    final ObjectId targetId = repo.resolve(targetBranchName);
    final ObjectId sourceId = repo.resolve(sourceBranchName);

    final DirCache dc = DirCache.newInCore();
    final DirCacheEditor editor = dc.editor();

    try (ObjectInserter inserter = repo.newObjectInserter()) {
        final ObjectId treeId = writeTestFilesToTree(dc, editor, inserter, testFiles);
        final ObjectId commitId = writeCommit(inserter, treeId, targetId, sourceId);
        updateBranch(targetBranchName, git, commitId);
    }/*  w ww.  j  a  va  2  s  . co m*/
}

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

License:Apache License

private void overrideBranchNames(final Repository repository, final RevWalk revWalk,
        final Map<ObjectId, ObjectId> commitMap)
        throws AmbiguousObjectException, IncorrectObjectTypeException, IOException, MissingObjectException,
        GitAPIException, RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException {
    for (String branchName : branches) {
        if (branchName.equals("HEAD")) {
            continue;
        }/*  w w w .  j  a  va2 s. c  om*/

        final ObjectId oldBranchTipId = repository.resolve(branchName);
        final ObjectId newBranchTipId = closestMappedAncestorOrSelf(commitMap,
                revWalk.parseCommit(oldBranchTipId))[0];
        final RevCommit newBranchTip = revWalk.parseCommit(newBranchTipId);
        org.eclipse.jgit.api.Git.wrap(repository).branchCreate().setName(branchName).setForce(true)
                .setStartPoint(newBranchTip).setUpstreamMode(SetupUpstreamMode.NOTRACK).call();
    }
}