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.apache.maven.scm.provider.git.jgit.command.JGitUtils.java

License:Apache License

/**
 * Get a list of commits between two revisions.
 *
 * @param repo     the repository to work on
 * @param sortings sorting//www . j a v  a 2  s  .com
 * @param fromRev  start revision
 * @param toRev    if null, falls back to head
 * @param fromDate from which date on
 * @param toDate   until which date
 * @param maxLines max number of lines
 * @return a list of commits, might be empty, but never <code>null</code>
 * @throws IOException
 * @throws MissingObjectException
 * @throws IncorrectObjectTypeException
 */
public static List<RevCommit> getRevCommits(Repository repo, RevSort[] sortings, String fromRev, String toRev,
        final Date fromDate, final Date toDate, int maxLines)
        throws IOException, MissingObjectException, IncorrectObjectTypeException {

    List<RevCommit> revs = new ArrayList<RevCommit>();
    RevWalk walk = new RevWalk(repo);

    ObjectId fromRevId = fromRev != null ? repo.resolve(fromRev) : null;
    ObjectId toRevId = toRev != null ? repo.resolve(toRev) : null;

    if (sortings == null || sortings.length == 0) {
        sortings = new RevSort[] { RevSort.TOPO, RevSort.COMMIT_TIME_DESC };
    }

    for (final RevSort s : sortings) {
        walk.sort(s, true);
    }

    if (fromDate != null && toDate != null) {
        //walk.setRevFilter( CommitTimeRevFilter.between( fromDate, toDate ) );
        walk.setRevFilter(new RevFilter() {
            @Override
            public boolean include(RevWalk walker, RevCommit cmit) throws StopWalkException,
                    MissingObjectException, IncorrectObjectTypeException, IOException {
                int cmtTime = cmit.getCommitTime();

                return (cmtTime >= (fromDate.getTime() / 1000)) && (cmtTime <= (toDate.getTime() / 1000));
            }

            @Override
            public RevFilter clone() {
                return this;
            }
        });
    } else {
        if (fromDate != null) {
            walk.setRevFilter(CommitTimeRevFilter.after(fromDate));
        }
        if (toDate != null) {
            walk.setRevFilter(CommitTimeRevFilter.before(toDate));
        }
    }

    if (fromRevId != null) {
        RevCommit c = walk.parseCommit(fromRevId);
        c.add(RevFlag.UNINTERESTING);
        RevCommit real = walk.parseCommit(c);
        walk.markUninteresting(real);
    }

    if (toRevId != null) {
        RevCommit c = walk.parseCommit(toRevId);
        c.remove(RevFlag.UNINTERESTING);
        RevCommit real = walk.parseCommit(c);
        walk.markStart(real);
    } else {
        final ObjectId head = repo.resolve(Constants.HEAD);
        if (head == null) {
            throw new RuntimeException("Cannot resolve " + Constants.HEAD);
        }
        RevCommit real = walk.parseCommit(head);
        walk.markStart(real);
    }

    int n = 0;
    for (final RevCommit c : walk) {
        n++;
        if (maxLines != -1 && n > maxLines) {
            break;
        }

        revs.add(c);
    }
    return revs;
}

From source file:org.apache.usergrid.chop.plugin.Utils.java

License:Apache License

/**
 * @param gitConfigFolder e.g. /your/project/root/.git
 *
 * @return Returns last commit's UUID, "nocommit" if there are no commits and returns null if an exception occured
 *//*w  ww.j  av a  2 s  .  co m*/
public static String getLastCommitUuid(String gitConfigFolder) throws MojoExecutionException {
    try {
        Repository repo = new RepositoryBuilder().setGitDir(new File(gitConfigFolder)).readEnvironment()
                .findGitDir().build();
        RevWalk walk = new RevWalk(repo);
        ObjectId head = repo.resolve("HEAD");
        if (head != null) {
            RevCommit lastCommit = walk.parseCommit(head);
            return lastCommit.getId().getName();
        } else {
            return "nocommit";
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error trying to get the last git commit uuid", e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public VersionTO[] getContentVersionHistory(String site, String path) {
    List<VersionTO> versionHistory = new ArrayList<VersionTO>();

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site,
                StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : GitRepositories.SANDBOX);

        try {/*from  ww  w . ja  v a2  s. c  om*/
            ObjectId head = repo.resolve(Constants.HEAD);
            String gitPath = helper.getGitPath(path);
            try (Git git = new Git(repo)) {
                Iterable<RevCommit> commits = git.log().add(head).addPath(gitPath).call();
                Iterator<RevCommit> iterator = commits.iterator();
                while (iterator.hasNext()) {
                    RevCommit revCommit = iterator.next();
                    VersionTO versionTO = new VersionTO();
                    versionTO.setVersionNumber(revCommit.getName());
                    versionTO.setLastModifier(revCommit.getAuthorIdent().getName());
                    versionTO.setLastModifiedDate(new Date(revCommit.getCommitTime() * 1000));
                    versionTO.setComment(revCommit.getFullMessage());
                    versionHistory.add(versionTO);
                }

                git.close();
            } catch (IOException e) {
                logger.error("error while getting history for content item " + path);
            }
        } catch (IOException | GitAPIException e) {
            logger.error("Failed to create Git repo for site: " + site + " path: " + path, e);
        }
    }

    VersionTO[] toRet = new VersionTO[versionHistory.size()];
    return versionHistory.toArray(toRet);
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public List<RepoOperationTO> getOperations(String site, String commitIdFrom, String commitIdTo) {
    List<RepoOperationTO> operations = new ArrayList<>();

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        try {/* w  w  w .j av  a  2  s.co  m*/
            // Get the sandbox repo, and then get a reference to the commitId we received and another for head
            Repository repo = helper.getRepository(site, SANDBOX);
            ObjectId objCommitIdFrom = repo.resolve(commitIdFrom);
            ObjectId objCommitIdTo = repo.resolve(commitIdTo);

            // If the commitIdFrom is the same as commitIdTo, there is nothing to calculate, otherwise, let's do it
            if (!objCommitIdFrom.equals(objCommitIdTo)) {
                // Compare HEAD with commitId we're given
                // Get list of commits between commitId and HEAD in chronological order
                try (Git git = new Git(repo)) {
                    // Get the log of all the commits between commitId and head
                    Iterable<RevCommit> commits = git.log().addRange(objCommitIdFrom, objCommitIdTo).call();

                    // Loop through through the commits and diff one from the next util head
                    ObjectId prevCommitId = objCommitIdFrom;
                    ObjectId nextCommitId = objCommitIdFrom;

                    Iterator<RevCommit> iterator = commits.iterator();
                    while (iterator.hasNext()) {
                        RevCommit commit = iterator.next();
                        nextCommitId = commit.getId();

                        RevTree prevTree = helper.getTreeForCommit(repo, prevCommitId.getName());
                        RevTree nextTree = helper.getTreeForCommit(repo, nextCommitId.getName());

                        try (ObjectReader reader = repo.newObjectReader()) {
                            CanonicalTreeParser prevCommitTreeParser = new CanonicalTreeParser();
                            CanonicalTreeParser nextCommitTreeParser = new CanonicalTreeParser();
                            prevCommitTreeParser.reset(reader, prevTree.getId());
                            nextCommitTreeParser.reset(reader, nextTree.getId());

                            // Diff the two commit Ids
                            List<DiffEntry> diffEntries = git.diff().setOldTree(prevCommitTreeParser)
                                    .setNewTree(nextCommitTreeParser).call();

                            // Now that we have a diff, let's itemize the file changes, pack them into a TO
                            // and add them to the list of RepoOperations to return to the caller
                            // also include date/time of commit by taking number of seconds and multiply by 1000 and
                            // convert to java date before sending over
                            operations.addAll(
                                    processDiffEntry(diffEntries, new Date(commit.getCommitTime() * 1000)));
                            prevCommitId = nextCommitId;
                        }
                    }
                } catch (GitAPIException e) {
                    logger.error("Error getting operations for site " + site + " from commit ID: "
                            + commitIdFrom + " to commit ID: " + commitIdTo, e);
                }
            }
        } catch (IOException e) {
            logger.error("Error getting operations for site " + site + " from commit ID: " + commitIdFrom
                    + " to commit ID: " + commitIdTo, e);
        }
    }

    return operations;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String getRepoLastCommitId(final String site) {
    String toReturn = StringUtils.EMPTY;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site, SANDBOX);
        try {//from   w w  w  .java2 s .  c  o  m
            ObjectId commitId = repo.resolve(Constants.HEAD);
            toReturn = commitId.getName();
        } catch (IOException e) {
            logger.error("Error getting last commit ID for site " + site, e);
        }
    }

    return toReturn;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

License:Open Source License

@Override
public String getRepoFirstCommitId(final String site) {
    String toReturn = StringUtils.EMPTY;

    synchronized (helper.getRepository(site, StringUtils.isEmpty(site) ? GitRepositories.GLOBAL : SANDBOX)) {
        Repository repo = helper.getRepository(site, SANDBOX);
        try (RevWalk rw = new RevWalk(repo)) {
            ObjectId head = repo.resolve(Constants.HEAD);
            RevCommit root = rw.parseCommit(head);
            rw.sort(RevSort.REVERSE);//  w  w w  .  j  a  v  a 2s.  c om
            rw.markStart(root);
            ObjectId first = rw.next();
            toReturn = first.getName();
            logger.error("FIRST COMMIT ID !!!: " + toReturn);
        } catch (IOException e) {
            logger.error("Error getting first commit ID for site " + site, e);
        }
    }

    return toReturn;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

License:Open Source License

public RevTree getTreeForLastCommit(Repository repository)
        throws AmbiguousObjectException, IncorrectObjectTypeException, IOException, MissingObjectException {
    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

    // a RevWalk allows to walk over commits based on some filtering
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(lastCommitId);

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }/* w  w w  .  j a va2s  .  c o m*/
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepositoryHelper.java

License:Open Source License

public RevTree getTreeForCommit(Repository repository, String commitId) throws IOException {
    ObjectId commitObjectId = repository.resolve(commitId);

    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(commitObjectId);

        // and using commit's tree find the path
        RevTree tree = commit.getTree();
        return tree;
    }//w w w .  ja v  a 2  s.  c  o m
}

From source file:org.dstadler.jgit.api.JGitPrintContent.java

License:BSD License

public static void main(String[] args) throws Exception {
    File gitWorkDir = new File("C:\\Users\\kishore\\git\\JavaRepos\\.git");
    Git git = Git.open(gitWorkDir);/*from  w w  w  . j ava2s . co m*/
    Repository repo = git.getRepository();

    ObjectId lastCommitId = repo.resolve(Constants.HEAD);

    RevWalk revWalk = new RevWalk(repo);
    RevCommit commit = revWalk.parseCommit(lastCommitId);

    RevTree tree = commit.getTree();

    TreeWalk treeWalk = new TreeWalk(repo);
    treeWalk.addTree(tree);
    treeWalk.setRecursive(true);
    treeWalk.setFilter(PathFilter.ALL);
    if (!treeWalk.next()) {
        System.out.println("Nothing found!");
        return;
    }

    ObjectId objectId = treeWalk.getObjectId(0);
    System.err.println(treeWalk.getPathString());
    System.err.println(objectId.getName());

    ObjectLoader loader = repo.open(objectId);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    loader.copyTo(out);
    System.out.println("file1.txt:\n" + out.toString());
}

From source file:org.eclipse.egit.bc.BeyondCompareWithRefActionHandler.java

License:Open Source License

public Object execute(ExecutionEvent event) throws ExecutionException {
    final Repository repo = getRepository(true, event);
    // assert all resources map to the same repository
    if (repo == null)
        return null;
    final IResource[] resources = getSelectedResources(event);

    CompareTargetSelectionDialog dlg = new CompareTargetSelectionDialog(getShell(event), repo,
            resources.length == 1 ? resources[0].getFullPath().lastSegment() : null);
    if (dlg.open() == Window.OK) {

        if (resources.length == 1 && resources[0] instanceof IFile) {
            final IFile baseFile = (IFile) resources[0];

            try {
                RepositoryMapping mapping = RepositoryMapping.getMapping(resources[0]);
                String repoRelativeBasePath = mapping.getRepoRelativePath(baseFile);
                String refName = dlg.getRefName();
                ObjectId commitId = repo.resolve(refName);

                Repository localRepo = mapping.getRepository();
                RevWalk rw = new RevWalk(localRepo);
                RevCommit commit = rw.parseCommit(commitId);
                rw.release();/*from   w ww . j  a va 2s . co m*/

                String rightFilePath = BeyondCompareUtil.getCompareFilePath(repoRelativeBasePath, commit,
                        localRepo);
                String leftFilePath = baseFile.getLocation().toFile().getAbsolutePath();
                BeyondCompareUtil.execBeyondCompare(leftFilePath, rightFilePath);

            } catch (IOException e) {
                Activator.handleError(UIText.CompareWithIndexActionHandler_onError, e, true);
                return null;
            }

        } else {
            CompareTreeView view;
            try {
                view = (CompareTreeView) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
                        .showView(CompareTreeView.ID);
                view.setInput(resources, dlg.getRefName());
            } catch (PartInitException e) {
                Activator.handleError(e.getMessage(), e, true);
            }
        }
    }
    return null;
}