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

/**
 * Returns the specified commit from the repository. If the repository does
 * not exist or is empty, null is returned.
 *
 * @param repository//from w ww  .j a  va  2s.c  o m
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @return RevCommit
 */
public static RevCommit getCommit(Repository repository, String objectId) {
    if (!hasCommits(repository)) {
        return null;
    }
    RevCommit commit = null;
    RevWalk walk = null;
    try {
        // resolve object id
        ObjectId branchObject;
        if (StringUtils.isEmpty(objectId) || "HEAD".equalsIgnoreCase(objectId)) {
            branchObject = getDefaultBranch(repository);
        } else {
            branchObject = repository.resolve(objectId);
        }
        if (branchObject == null) {
            return null;
        }
        walk = new RevWalk(repository);
        RevCommit rev = walk.parseCommit(branchObject);
        commit = rev;
    } catch (Throwable t) {
        error(t, repository, "{0} failed to get commit {1}", objectId);
    } finally {
        if (walk != null) {
            walk.dispose();
        }
    }
    return commit;
}

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

License:Apache License

/**
 * Returns the list of files changed in a specified commit. If the
 * repository does not exist or is empty, an empty list is returned.
 *
 * @param repository/*from   ww w  .  j a  va  2  s. co  m*/
 * @param startCommit
 *            earliest commit
 * @param endCommit
 *            most recent commit. if null, HEAD is assumed.
 * @return list of files changed in a commit range
 */
public static List<PathChangeModel> getFilesInRange(Repository repository, String startCommit,
        String endCommit) {
    List<PathChangeModel> list = new ArrayList<PathChangeModel>();
    if (!hasCommits(repository)) {
        return list;
    }
    try {
        ObjectId startRange = repository.resolve(startCommit);
        ObjectId endRange = repository.resolve(endCommit);
        RevWalk rw = new RevWalk(repository);
        RevCommit start = rw.parseCommit(startRange);
        RevCommit end = rw.parseCommit(endRange);
        list.addAll(getFilesInRange(repository, start, end));
        rw.close();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to determine files in range {1}..{2}!", startCommit, endCommit);
    }
    return list;
}

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

License:Apache License

/**
 * Returns a list of commits since the minimum date starting from the
 * specified object id.//from  w  ww  .  j  a va  2  s.c om
 *
 * @param repository
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param minimumDate
 * @return list of commits
 */
public static List<RevCommit> getRevLog(Repository repository, String objectId, Date minimumDate) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (!hasCommits(repository)) {
        return list;
    }
    try {
        // resolve branch
        ObjectId branchObject;
        if (StringUtils.isEmpty(objectId)) {
            branchObject = getDefaultBranch(repository);
        } else {
            branchObject = repository.resolve(objectId);
        }

        RevWalk rw = new RevWalk(repository);
        rw.markStart(rw.parseCommit(branchObject));
        rw.setRevFilter(CommitTimeRevFilter.after(minimumDate));
        Iterable<RevCommit> revlog = rw;
        for (RevCommit rev : revlog) {
            list.add(rev);
        }
        rw.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to get {1} revlog for minimum date {2}", objectId, minimumDate);
    }
    return list;
}

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

License:Apache License

/**
 * Returns a list of commits for the repository or a path within the
 * repository. Caller may specify ending revision with objectId. Caller may
 * specify offset and maxCount to achieve pagination of results. If the
 * repository does not exist or is empty, an empty list is returned.
 *
 * @param repository//  ww  w  .j  a  v a  2s .c  o m
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param path
 *            if unspecified, commits for repository are returned. If
 *            specified, commits for the path are returned.
 * @param offset
 * @param maxCount
 *            if < 0, all commits are returned.
 * @return a paged list of commits
 */
public static List<RevCommit> getRevLog(Repository repository, String objectId, String path, int offset,
        int maxCount) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (maxCount == 0) {
        return list;
    }
    if (!hasCommits(repository)) {
        return list;
    }
    try {
        // resolve branch
        ObjectId startRange = null;
        ObjectId endRange;
        if (StringUtils.isEmpty(objectId)) {
            endRange = getDefaultBranch(repository);
        } else {
            if (objectId.contains("..")) {
                // range expression
                String[] parts = objectId.split("\\.\\.");
                startRange = repository.resolve(parts[0]);
                endRange = repository.resolve(parts[1]);
            } else {
                // objectid
                endRange = repository.resolve(objectId);
            }
        }
        if (endRange == null) {
            return list;
        }

        RevWalk rw = new RevWalk(repository);
        rw.markStart(rw.parseCommit(endRange));
        if (startRange != null) {
            rw.markUninteresting(rw.parseCommit(startRange));
        }
        if (!StringUtils.isEmpty(path)) {
            TreeFilter filter = AndTreeFilter.create(
                    PathFilterGroup.createFromStrings(Collections.singleton(path)), TreeFilter.ANY_DIFF);
            rw.setTreeFilter(filter);
        }
        Iterable<RevCommit> revlog = rw;
        if (offset > 0) {
            int count = 0;
            for (RevCommit rev : revlog) {
                count++;
                if (count > offset) {
                    list.add(rev);
                    if (maxCount > 0 && list.size() == maxCount) {
                        break;
                    }
                }
            }
        } else {
            for (RevCommit rev : revlog) {
                list.add(rev);
                if (maxCount > 0 && list.size() == maxCount) {
                    break;
                }
            }
        }
        rw.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to get {1} revlog for path {2}", objectId, path);
    }
    return list;
}

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

License:Apache License

/**
 * Returns a list of commits for the repository within the range specified
 * by startRangeId and endRangeId. If the repository does not exist or is
 * empty, an empty list is returned./*from  ww w . j a v a  2 s  .co m*/
 *
 * @param repository
 * @param startRangeId
 *            the first commit (not included in results)
 * @param endRangeId
 *            the end commit (included in results)
 * @return a list of commits
 */
public static List<RevCommit> getRevLog(Repository repository, String startRangeId, String endRangeId) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (!hasCommits(repository)) {
        return list;
    }
    try {
        ObjectId endRange = repository.resolve(endRangeId);
        ObjectId startRange = repository.resolve(startRangeId);

        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));
        }

        Iterable<RevCommit> revlog = rw;
        for (RevCommit rev : revlog) {
            list.add(rev);
        }
        rw.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to get revlog for {1}..{2}", startRangeId, endRangeId);
    }
    return list;
}

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

License:Apache License

/**
 * Search the commit history for a case-insensitive match to the value.
 * Search results require a specified SearchType of AUTHOR, COMMITTER, or
 * COMMIT. Results may be paginated using offset and maxCount. If the
 * repository does not exist or is empty, an empty list is returned.
 *
 * @param repository/*from w w  w . j av  a 2  s.  c o  m*/
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param value
 * @param type
 *            AUTHOR, COMMITTER, COMMIT
 * @param offset
 * @param maxCount
 *            if < 0, all matches are returned
 * @return matching list of commits
 */
public static List<RevCommit> searchRevlogs(Repository repository, String objectId, String value,
        final com.gitblit.Constants.SearchType type, int offset, int maxCount) {
    List<RevCommit> list = new ArrayList<RevCommit>();
    if (StringUtils.isEmpty(value)) {
        return list;
    }
    if (maxCount == 0) {
        return list;
    }
    if (!hasCommits(repository)) {
        return list;
    }
    final String lcValue = value.toLowerCase();
    try {
        // resolve branch
        ObjectId branchObject;
        if (StringUtils.isEmpty(objectId)) {
            branchObject = getDefaultBranch(repository);
        } else {
            branchObject = repository.resolve(objectId);
        }

        RevWalk rw = new RevWalk(repository);
        rw.setRevFilter(new RevFilter() {

            @Override
            public RevFilter clone() {
                // FindBugs complains about this method name.
                // This is part of JGit design and unrelated to Cloneable.
                return this;
            }

            @Override
            public boolean include(RevWalk walker, RevCommit commit) throws StopWalkException,
                    MissingObjectException, IncorrectObjectTypeException, IOException {
                boolean include = false;
                switch (type) {
                case AUTHOR:
                    include = (commit.getAuthorIdent().getName().toLowerCase().indexOf(lcValue) > -1)
                            || (commit.getAuthorIdent().getEmailAddress().toLowerCase().indexOf(lcValue) > -1);
                    break;
                case COMMITTER:
                    include = (commit.getCommitterIdent().getName().toLowerCase().indexOf(lcValue) > -1)
                            || (commit.getCommitterIdent().getEmailAddress().toLowerCase()
                                    .indexOf(lcValue) > -1);
                    break;
                case COMMIT:
                    include = commit.getFullMessage().toLowerCase().indexOf(lcValue) > -1;
                    break;
                }
                return include;
            }

        });
        rw.markStart(rw.parseCommit(branchObject));
        Iterable<RevCommit> revlog = rw;
        if (offset > 0) {
            int count = 0;
            for (RevCommit rev : revlog) {
                count++;
                if (count > offset) {
                    list.add(rev);
                    if (maxCount > 0 && list.size() == maxCount) {
                        break;
                    }
                }
            }
        } else {
            for (RevCommit rev : revlog) {
                list.add(rev);
                if (maxCount > 0 && list.size() == maxCount) {
                    break;
                }
            }
        }
        rw.dispose();
    } catch (Throwable t) {
        error(t, repository, "{0} failed to {1} search revlogs for {2}", type.name(), value);
    }
    return list;
}

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

License:Apache License

/**
 * Returns the default branch to use for a repository. Normally returns
 * whatever branch HEAD points to, but if HEAD points to nothing it returns
 * the most recently updated branch./*from  w w w  . j a v a2s  .  c  o  m*/
 *
 * @param repository
 * @return the objectid of a branch
 * @throws Exception
 */
public static ObjectId getDefaultBranch(Repository repository) throws Exception {
    ObjectId object = repository.resolve(Constants.HEAD);
    if (object == null) {
        // no HEAD
        // perhaps non-standard repository, try local branches
        List<RefModel> branchModels = getLocalBranches(repository, true, -1);
        if (branchModels.size() > 0) {
            // use most recently updated branch
            RefModel branch = null;
            Date lastDate = new Date(0);
            for (RefModel branchModel : branchModels) {
                if (branchModel.getDate().after(lastDate)) {
                    branch = branchModel;
                    lastDate = branch.getDate();
                }
            }
            object = branch.getReferencedObjectId();
        }
    }
    return object;
}

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

License:Apache License

/**
 * Returns true if the commit identified by commitId is an ancestor or the
 * the commit identified by tipId./*from ww w . ja v  a2 s .co  m*/
 *
 * @param repository
 * @param commitId
 * @param tipId
 * @return true if there is the commit is an ancestor of the tip
 */
public static boolean isMergedInto(Repository repository, String commitId, String tipId) {
    try {
        return isMergedInto(repository, repository.resolve(commitId), repository.resolve(tipId));
    } catch (Exception e) {
        LOGGER.error("Failed to determine isMergedInto", e);
    }
    return false;
}

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

License:Apache License

/**
 * Returns all tree entries that do not match the ignore paths.
 *
 * @param db/*from w ww  . j a  v a 2s  . co  m*/
 * @param ignorePaths
 * @param dcBuilder
 * @throws IOException
 */
public static List<DirCacheEntry> getTreeEntries(Repository db, String branch, Collection<String> ignorePaths)
        throws IOException {
    List<DirCacheEntry> list = new ArrayList<DirCacheEntry>();
    TreeWalk tw = null;
    try {
        ObjectId treeId = db.resolve(branch + "^{tree}");
        if (treeId == null) {
            // branch does not exist yet
            return list;
        }
        tw = new TreeWalk(db);
        int hIdx = tw.addTree(treeId);
        tw.setRecursive(true);

        while (tw.next()) {
            String path = tw.getPathString();
            CanonicalTreeParser hTree = null;
            if (hIdx != -1) {
                hTree = tw.getTree(hIdx, CanonicalTreeParser.class);
            }
            if (!ignorePaths.contains(path)) {
                // add all other tree entries
                if (hTree != null) {
                    final DirCacheEntry entry = new DirCacheEntry(path);
                    entry.setObjectId(hTree.getEntryObjectId());
                    entry.setFileMode(hTree.getEntryFileMode());
                    list.add(entry);
                }
            }
        }
    } finally {
        if (tw != null) {
            tw.close();
        }
    }
    return list;
}

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

License:Apache License

public static boolean commitIndex(Repository db, String branch, DirCache index, ObjectId parentId,
        boolean forceCommit, String author, String authorEmail, String message)
        throws IOException, ConcurrentRefUpdateException {
    boolean success = false;

    ObjectId headId = db.resolve(branch + "^{commit}");
    ObjectId baseId = parentId;/*from  w  ww. j a v  a 2s. c  o  m*/
    if (baseId == null || headId == null) {
        return false;
    }

    ObjectInserter odi = db.newObjectInserter();
    try {
        // Create the in-memory index of the new/updated ticket
        ObjectId indexTreeId = index.writeTree(odi);

        // Create a commit object
        PersonIdent ident = new PersonIdent(author, authorEmail);

        if (forceCommit == false) {
            ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
            merger.setObjectInserter(odi);
            merger.setBase(baseId);
            boolean mergeSuccess = merger.merge(indexTreeId, headId);

            if (mergeSuccess) {
                indexTreeId = merger.getResultTreeId();
            } else {
                //Manual merge required
                return false;
            }
        }

        CommitBuilder commit = new CommitBuilder();
        commit.setAuthor(ident);
        commit.setCommitter(ident);
        commit.setEncoding(com.gitblit.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(db);
        try {
            RevCommit revCommit = revWalk.parseCommit(commitId);
            RefUpdate ru = db.updateRef(branch);
            ru.setForceUpdate(forceCommit);
            ru.setNewObjectId(commitId);
            ru.setExpectedOldObjectId(headId);
            ru.setRefLogMessage("commit: " + revCommit.getShortMessage(), false);
            Result rc = ru.update();

            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, branch,
                        commitId.toString(), rc));
            }
        } finally {
            revWalk.close();
        }
    } finally {
        odi.close();
    }
    return success;
}