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:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Try to identify all referenced tickets between two commits
 *
 * @param commit/*from w  w  w  . j  av  a  2 s  . co m*/
 * @param parseMessage
 * @param currentTicketId, or 0 if not on a ticket branch
 * @return a collection of TicketLink, or null if commit is already linked
 */
public static List<TicketLink> identifyTicketsBetweenCommits(Repository repository, IStoredSettings settings,
        String baseSha, String tipSha) {
    List<TicketLink> links = new ArrayList<TicketLink>();
    if (repository == null) {
        return links;
    }

    RevWalk walk = new RevWalk(repository);
    walk.sort(RevSort.TOPO);
    walk.sort(RevSort.REVERSE, true);
    try {
        RevCommit tip = walk.parseCommit(repository.resolve(tipSha));
        RevCommit base = walk.parseCommit(repository.resolve(baseSha));
        walk.markStart(tip);
        walk.markUninteresting(base);
        for (;;) {
            RevCommit commit = walk.next();
            if (commit == null) {
                break;
            }
            links.addAll(JGitUtils.identifyTicketsFromCommitMessage(repository, settings, commit));
        }
    } catch (IOException e) {
        LOGGER.error("failed to identify tickets between commits.", e);
    } finally {
        walk.dispose();
    }

    return links;
}

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

License:Apache License

public static int countCommits(Repository repository, RevWalk walk, String baseId, String tipId) {
    int count = 0;
    try {/*  w ww  .  j  ava 2 s  .  c o m*/
        count = countCommits(repository, walk, repository.resolve(baseId), repository.resolve(tipId));
    } catch (IOException e) {
        LOGGER.error("failed to get commit count", e);
    }
    return count;
}

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

License:Apache License

/**
 * Returns the list of metrics for the specified commit reference, branch,
 * or tag within the repository. If includeTotal is true, the total of all
 * the metrics will be included as the first element in the returned list.
 *
 * If the dateformat is unspecified an attempt is made to determine an
 * appropriate date format by determining the time difference between the
 * first commit on the branch and the most recent commit. This assumes that
 * the commits are linear./*www .  j  av  a2 s .  com*/
 *
 * @param repository
 * @param objectId
 *            if null or empty, HEAD is assumed.
 * @param includeTotal
 * @param dateFormat
 * @param timezone
 * @return list of metrics
 */
public static List<Metric> getDateMetrics(Repository repository, String objectId, boolean includeTotal,
        String dateFormat, TimeZone timezone) {
    Metric total = new Metric("TOTAL");
    final Map<String, Metric> metricMap = new HashMap<String, Metric>();

    if (JGitUtils.hasCommits(repository)) {
        final List<RefModel> tags = JGitUtils.getTags(repository, true, -1);
        final Map<ObjectId, RefModel> tagMap = new HashMap<ObjectId, RefModel>();
        for (RefModel tag : tags) {
            tagMap.put(tag.getReferencedObjectId(), tag);
        }
        RevWalk revWalk = null;
        try {
            // resolve branch
            ObjectId branchObject;
            if (StringUtils.isEmpty(objectId)) {
                branchObject = JGitUtils.getDefaultBranch(repository);
            } else {
                branchObject = repository.resolve(objectId);
            }

            revWalk = new RevWalk(repository);
            RevCommit lastCommit = revWalk.parseCommit(branchObject);
            revWalk.markStart(lastCommit);

            DateFormat df;
            if (StringUtils.isEmpty(dateFormat)) {
                // dynamically determine date format
                RevCommit firstCommit = JGitUtils.getFirstCommit(repository, branchObject.getName());
                int diffDays = (lastCommit.getCommitTime() - firstCommit.getCommitTime()) / (60 * 60 * 24);
                total.duration = diffDays;
                if (diffDays <= 365) {
                    // Days
                    df = new SimpleDateFormat("yyyy-MM-dd");
                } else {
                    // Months
                    df = new SimpleDateFormat("yyyy-MM");
                }
            } else {
                // use specified date format
                df = new SimpleDateFormat(dateFormat);
            }
            df.setTimeZone(timezone);

            Iterable<RevCommit> revlog = revWalk;
            for (RevCommit rev : revlog) {
                Date d = JGitUtils.getAuthorDate(rev);
                String p = df.format(d);
                if (!metricMap.containsKey(p)) {
                    metricMap.put(p, new Metric(p));
                }
                Metric m = metricMap.get(p);
                m.count++;
                total.count++;
                if (tagMap.containsKey(rev.getId())) {
                    m.tag++;
                    total.tag++;
                }
            }
        } catch (Throwable t) {
            error(t, repository, "{0} failed to mine log history for date metrics of {1}", objectId);
        } finally {
            if (revWalk != null) {
                revWalk.dispose();
            }
        }
    }
    List<String> keys = new ArrayList<String>(metricMap.keySet());
    Collections.sort(keys);
    List<Metric> metrics = new ArrayList<Metric>();
    for (String key : keys) {
        metrics.add(metricMap.get(key));
    }
    if (includeTotal) {
        metrics.add(0, total);
    }
    return metrics;
}

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

License:Apache License

/**
 * Returns a list of author metrics for the specified repository.
 *
 * @param repository/*  w  w  w. j a va  2s  .  c om*/
 * @param objectId
 *            if null or empty, HEAD is assumed.
 * @param byEmailAddress
 *            group metrics by author email address otherwise by author name
 * @return list of metrics
 */
public static List<Metric> getAuthorMetrics(Repository repository, String objectId, boolean byEmailAddress) {
    final Map<String, Metric> metricMap = new HashMap<String, Metric>();
    if (JGitUtils.hasCommits(repository)) {
        try {
            RevWalk walk = new RevWalk(repository);
            // resolve branch
            ObjectId branchObject;
            if (StringUtils.isEmpty(objectId)) {
                branchObject = JGitUtils.getDefaultBranch(repository);
            } else {
                branchObject = repository.resolve(objectId);
            }
            RevCommit lastCommit = walk.parseCommit(branchObject);
            walk.markStart(lastCommit);

            Iterable<RevCommit> revlog = walk;
            for (RevCommit rev : revlog) {
                String p;
                if (byEmailAddress) {
                    p = rev.getAuthorIdent().getEmailAddress().toLowerCase();
                    if (StringUtils.isEmpty(p)) {
                        p = rev.getAuthorIdent().getName().toLowerCase();
                    }
                } else {
                    p = rev.getAuthorIdent().getName().toLowerCase();
                    if (StringUtils.isEmpty(p)) {
                        p = rev.getAuthorIdent().getEmailAddress().toLowerCase();
                    }
                }
                p = p.replace('\n', ' ').replace('\r', ' ').trim();
                if (!metricMap.containsKey(p)) {
                    metricMap.put(p, new Metric(p));
                }
                Metric m = metricMap.get(p);
                m.count++;
            }
        } catch (Throwable t) {
            error(t, repository, "{0} failed to mine log history for author metrics of {1}", objectId);
        }
    }
    List<String> keys = new ArrayList<String>(metricMap.keySet());
    Collections.sort(keys);
    List<Metric> metrics = new ArrayList<Metric>();
    for (String key : keys) {
        metrics.add(metricMap.get(key));
    }
    return metrics;
}

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

License:Apache License

/**
 * Updates a push log./*from  w w  w .j  a  v a 2s.  c o m*/
 * 
 * @param user
 * @param repository
 * @param commands
 * @return true, if the update was successful
 */
public static boolean updatePushLog(UserModel user, Repository repository,
        Collection<ReceiveCommand> commands) {
    RefModel pushlogBranch = getPushLogBranch(repository);
    if (pushlogBranch == null) {
        JGitUtils.createOrphanBranch(repository, GB_PUSHES, null);
    }

    boolean success = false;
    String message = "push";

    try {
        ObjectId headId = repository.resolve(GB_PUSHES + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the push log entry
            DirCache index = createIndex(repository, headId, commands);
            ObjectId indexTreeId = index.writeTree(odi);

            PersonIdent ident = new PersonIdent(user.getDisplayName(),
                    user.emailAddress == null ? user.username : user.emailAddress);

            // Create a commit object
            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_PUSHES);
                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_PUSHES, commitId.toString(), rc));
                }
            } finally {
                revWalk.release();
            }
        } finally {
            odi.release();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to commit pushlog entry to {0}");
    }
    return success;
}

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

License:Apache License

/**
 * Updates the reflog with the received commands.
 *
 * @param user/*  ww  w  .  j av a2 s .c  o  m*/
 * @param repository
 * @param commands
 * @return true, if the update was successful
 */
public static boolean updateRefLog(UserModel user, Repository repository, Collection<ReceiveCommand> commands) {

    // only track branches and tags
    List<ReceiveCommand> filteredCommands = new ArrayList<ReceiveCommand>();
    for (ReceiveCommand cmd : commands) {
        if (!cmd.getRefName().startsWith(Constants.R_HEADS) && !cmd.getRefName().startsWith(Constants.R_TAGS)) {
            continue;
        }
        filteredCommands.add(cmd);
    }

    if (filteredCommands.isEmpty()) {
        // nothing to log
        return true;
    }

    RefModel reflogBranch = getRefLogBranch(repository);
    if (reflogBranch == null) {
        JGitUtils.createOrphanBranch(repository, GB_REFLOG, null);
    }

    boolean success = false;
    String message = "push";

    try {
        ObjectId headId = repository.resolve(GB_REFLOG + "^{commit}");
        ObjectInserter odi = repository.newObjectInserter();
        try {
            // Create the in-memory index of the reflog log entry
            DirCache index = createIndex(repository, headId, commands);
            ObjectId indexTreeId = index.writeTree(odi);

            PersonIdent ident;
            if (UserModel.ANONYMOUS.equals(user)) {
                // anonymous push
                ident = new PersonIdent(user.username + "/" + user.username, user.username);
            } else {
                // construct real pushing account
                ident = new PersonIdent(MessageFormat.format("{0}/{1}", user.getDisplayName(), user.username),
                        user.emailAddress == null ? user.username : user.emailAddress);
            }

            // Create a commit object
            CommitBuilder commit = new CommitBuilder();
            commit.setAuthor(ident);
            commit.setCommitter(ident);
            commit.setEncoding(Constants.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_REFLOG);
                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_REFLOG, commitId.toString(), rc));
                }
            } finally {
                revWalk.close();
            }
        } finally {
            odi.close();
        }
    } catch (Throwable t) {
        error(t, repository, "Failed to commit reflog entry to {0}");
    }
    return success;
}

From source file:com.github.checkstyle.github.NotesBuilder.java

License:Open Source License

/**
 * Returns actual SHA-1 object by commit reference.
 * @param repo git repository./*  w  w  w  . ja v  a2  s . co  m*/
 * @param ref string representation of commit reference.
 * @return actual SHA-1 object.
 * @throws IOException if an I/O error occurs.
 */
private static ObjectId getActualRefObjectId(Repository repo, String ref) throws IOException {
    final ObjectId actualObjectId;
    final Ref referenceObj = repo.findRef(ref);
    if (referenceObj == null) {
        actualObjectId = repo.resolve(ref);
    } else {
        final Ref repoPeeled = repo.peel(referenceObj);
        actualObjectId = Optional.ofNullable(repoPeeled.getPeeledObjectId()).orElse(referenceObj.getObjectId());
    }
    return actualObjectId;
}

From source file:com.github.checkstyle.NotesBuilder.java

License:Open Source License

/**
 * Returns actual SHA-1 object by commit reference.
 * @param repo git repository./*from  www .  j  a  v a 2s  .c o m*/
 * @param ref string representation of commit reference.
 * @return actual SHA-1 object.
 * @throws IOException if an I/O error occurs.
 */
private static ObjectId getActualRefObjectId(Repository repo, String ref) throws IOException {
    final ObjectId actualObjectId;
    final Ref referenceObj = repo.getRef(ref);
    if (referenceObj == null) {
        actualObjectId = repo.resolve(ref);
    } else {
        final Ref repoPeeled = repo.peel(referenceObj);
        actualObjectId = Optional.ofNullable(repoPeeled.getPeeledObjectId()).orElse(referenceObj.getObjectId());
    }
    return actualObjectId;
}

From source file:com.github.checkstyle.regression.internal.CommitValidationTest.java

License:Open Source License

private static RevCommitsPair resolveRevCommitsPair(Repository repo) {
    RevCommitsPair revCommitIteratorPair;

    try (RevWalk revWalk = new RevWalk(repo)) {
        final Iterator<RevCommit> first;
        final Iterator<RevCommit> second;
        final ObjectId headId = repo.resolve(Constants.HEAD);
        final RevCommit headCommit = revWalk.parseCommit(headId);

        if (isMergeCommit(headCommit)) {
            final RevCommit firstParent = headCommit.getParent(0);
            final RevCommit secondParent = headCommit.getParent(1);

            try (Git git = new Git(repo)) {
                first = git.log().add(firstParent).call().iterator();
                second = git.log().add(secondParent).call().iterator();
            }/*from  ww  w .j a v  a2  s .c o  m*/
        } else {
            try (Git git = new Git(repo)) {
                first = git.log().call().iterator();
            }
            second = Collections.emptyIterator();
        }

        revCommitIteratorPair = new RevCommitsPair(new OmitMergeCommitsIterator(first),
                new OmitMergeCommitsIterator(second));
    } catch (GitAPIException | IOException ex) {
        revCommitIteratorPair = new RevCommitsPair();
    }

    return revCommitIteratorPair;
}

From source file:com.github.pascalgn.maven.properties.GitProperties.java

License:Apache License

private void addProperties(Map<String, String> map) throws IOException {
    Repository repository = new FileRepositoryBuilder().setWorkTree(new File(".")).readEnvironment()
            .findGitDir().setMustExist(true).build();
    logger.debug("Using git repository: " + repository.getDirectory());

    ObjectId head = repository.resolve("HEAD");
    if (head == null) {
        throw new IllegalStateException("No such revision: HEAD");
    }//w w  w. j a  va 2  s  . c o  m

    String branch = nullToEmpty(repository.getBranch());
    map.put("git.branch", branch);

    String commitId = head.name();
    map.put("git.commit.id", commitId);

    String commitIdAbbrev = repository.newObjectReader().abbreviate(head).name();
    map.put("git.commit.id.abbrev", commitIdAbbrev);

    RevWalk walk = new RevWalk(repository);
    walk.setRetainBody(false);
    RevCommit headCommit = walk.parseCommit(head);
    int count = RevWalkUtils.count(walk, headCommit, null);
    map.put("git.count", Integer.toString(count));

    String color = commitId.substring(0, 6);
    map.put("git.commit.color.value", color);
    map.put("git.commit.color.name", ColorHelper.getColorName(color));
    map.put("git.commit.color.lightness", Integer.toString(ColorHelper.getLightness(color)));
    map.put("git.commit.color.foreground", ColorHelper.getForeground(color));

    map.put("git.build.datetime.simple", getFormattedDate());
}