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.google.gitiles.DescribeServlet.java

License:Open Source License

private ObjectId resolve(Repository repo, GitilesView view, HttpServletRequest req, HttpServletResponse res)
        throws IOException {
    String rev = view.getPathPart();
    try {/*from   w w  w. j a v a  2s  . c  om*/
        return repo.resolve(rev);
    } catch (RevisionSyntaxException e) {
        renderTextError(req, res, SC_BAD_REQUEST,
                "Invalid revision syntax: " + RefServlet.sanitizeRefForText(rev));
        return null;
    } catch (AmbiguousObjectException e) {
        renderTextError(req, res, SC_BAD_REQUEST, String.format("Ambiguous short SHA-1 %s (%s)",
                e.getAbbreviatedObjectId(), Joiner.on(", ").join(e.getCandidates())));
        return null;
    }
}

From source file:com.googlesource.gerrit.plugins.findowners.OwnersDb.java

License:Apache License

/** Returns ObjectId of the given branch, or null. */
private static ObjectId getBranchId(Repository repo, String branch, ChangeData changeData, List<String> logs) {
    String header = "getBranchId:" + branch;
    try {/*from  www  .j  av  a 2s  .co  m*/
        ObjectId id = repo.resolve(branch);
        if (id == null && changeData != null && !Checker.isExemptFromOwnerApproval(changeData)) {
            logger.atSevere().log("cannot find branch %s for %s", branch, Config.getChangeId(changeData));
            logs.add(header + " (NOT FOUND)");
        } else {
            logs.add(header + " (FOUND)");
        }
        return id;
    } catch (Exception e) {
        logger.atSevere().withCause(e).log("cannot find branch %s for %s", branch,
                Config.getChangeId(changeData));
        logException(logs, header, e);
    }
    return null;
}

From source file:com.googlesource.gerrit.plugins.supermanifest.Utils.java

License:Apache License

public static byte[] readBlob(Repository repo, String idStr) throws IOException {
    try (ObjectReader reader = repo.newObjectReader()) {
        ObjectId id = repo.resolve(idStr);
        if (id == null) {
            throw new RevisionSyntaxException(String.format("repo %s does not have %s", repo.toString(), idStr),
                    idStr);/* w  w w  . j a v  a2  s  .  c om*/
        }
        return reader.open(id).getCachedBytes(Integer.MAX_VALUE);
    }
}

From source file:com.googlesource.gerrit.plugins.xdocs.XDocServlet.java

License:Apache License

private static ObjectId resolveRevision(Repository repo, String revision)
        throws ResourceNotFoundException, IOException {
    if (revision == null) {
        return null;
    }//from  w w w. ja  v  a2 s.com

    ObjectId revId = repo.resolve(revision);
    if (revId == null) {
        throw new ResourceNotFoundException();
    }
    return revId;
}

From source file:com.hatis.gitblit.plugin.TicketsGroovyHook.java

@Override
public void onMergePatchset(TicketModel ticket) {
    RepositoryModel repositoryModel = gitblit.getRepositoryModel(ticket.repository);
    Repository repository = gitblit.getRepository(repositoryModel.name);

    Collection<ReceiveCommand> commands = new ArrayList<>();

    Change lastMerged = null;/*from  ww w.  j  a  va2  s . c o m*/

    for (Change change : ticket.changes) {
        if (change.isMerge())
            lastMerged = change;
    }

    if (lastMerged == null) {
        LOGGER.error("Cant find last merg change");
        return;
    }

    UserModel userModel = gitblit.getUserModel(lastMerged.author);

    if (userModel == null) {
        LOGGER.error("Change author not exists");
        return;
    }

    RevWalk revWalk = null;
    try {
        revWalk = new RevWalk(repository);
        RevCommit branchTip = revWalk.lookupCommit(repository.resolve(ticket.mergeTo));
        ReceiveCommand receiveCommand = new ReceiveCommand(branchTip, branchTip,
                "refs/heads/" + ticket.mergeTo);
        commands.add(receiveCommand);
    } catch (IOException e) {
        LOGGER.error("Failed to determine merge branch", e);
    } finally {
        if (revWalk != null) {
            revWalk.release();
        }
    }

    Set<String> scripts = new LinkedHashSet<>();
    scripts.addAll(gitblit.getPostReceiveScriptsInherited(repositoryModel));
    if (!ArrayUtils.isEmpty(repositoryModel.postReceiveScripts)) {
        scripts.addAll(repositoryModel.postReceiveScripts);
    }

    runGroovy(commands, scripts, repositoryModel, userModel);
}

From source file:com.hazelcast.utils.GitUtils.java

License:Open Source License

public static RevCommit getCommit(Repository repo, RevWalk revWalk, String name) throws IOException {
    ObjectId objectId = repo.resolve(name);
    return revWalk.parseCommit(objectId);
}

From source file:com.hpe.application.automation.tools.octane.model.processors.scm.GitSCMProcessor.java

License:Open Source License

@Override
public CommonOriginRevision getCommonOriginRevision(final Run run) {
    //for phase 1 this is hard coded since its not possible to calculate it, and configuration from outside will complicate the feature
    //so for this phase we keep it hardcoded.
    CommonOriginRevision commonOriginRevision = new CommonOriginRevision();

    try {//from w  w  w . j av a 2s.  c  om
        final AbstractBuild abstractBuild = (AbstractBuild) run;
        FilePath workspace = ((AbstractBuild) run).getWorkspace();
        if (workspace != null) {
            commonOriginRevision = workspace.act(new FilePath.FileCallable<CommonOriginRevision>() {
                @Override
                public CommonOriginRevision invoke(File file, VirtualChannel channel)
                        throws IOException, InterruptedException {
                    CommonOriginRevision result = new CommonOriginRevision();
                    File repoDir = new File(getRemoteString(abstractBuild) + File.separator + ".git");
                    Git git = Git.open(repoDir);
                    Repository repo = git.getRepository();
                    final RevWalk walk = new RevWalk(repo);

                    ObjectId resolveForCurrentBranch = repo.resolve(Constants.HEAD);
                    RevCommit currentBranchCommit = walk.parseCommit(resolveForCurrentBranch);
                    ObjectId resolveForMaster = repo.resolve(MASTER);
                    RevCommit masterCommit = walk.parseCommit(resolveForMaster);

                    walk.reset();
                    walk.setRevFilter(RevFilter.MERGE_BASE);
                    walk.markStart(currentBranchCommit);
                    walk.markStart(masterCommit);
                    final RevCommit base = walk.next();
                    if (base == null)
                        return result;
                    final RevCommit base2 = walk.next();
                    if (base2 != null) {
                        throw new NoMergeBaseException(
                                NoMergeBaseException.MergeBaseFailureReason.MULTIPLE_MERGE_BASES_NOT_SUPPORTED,
                                MessageFormat.format(JGitText.get().multipleMergeBasesFor,
                                        currentBranchCommit.name(), masterCommit.name(), base.name(),
                                        base2.name()));
                    }
                    result.revision = base.getId().getName();
                    result.branch = getBranchName(run);
                    return result;
                }

                @Override
                public void checkRoles(RoleChecker roleChecker) throws SecurityException {
                    if (roleChecker != null) {
                        logger.info("Note : roleChecker is not empty, but no action was taken");
                    }
                }
            });
        }
        logger.info("most recent common revision resolved to " + commonOriginRevision.revision + " (branch: "
                + commonOriginRevision.branch + ")");
    } catch (Exception e) {
        logger.error("failed to resolve most recent common revision", e);
        return commonOriginRevision;
    }
    return commonOriginRevision;
}

From source file:com.jaxio.celerio.output.GITStatusCrawler.java

License:Apache License

private static RevTree getTree(Repository repository) throws IOException {
    ObjectId lastCommitId = repository.resolve(Constants.HEAD);

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

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

From source file:com.madgag.agit.BlobViewFragment.java

License:Open Source License

@Override
public Loader<BlobView> onCreateLoader(int id, Bundle b) {
    return new AsyncLoader<BlobView>(getActivity()) {
        public BlobView loadInBackground() {
            Bundle args = getArguments();
            try {
                Repository repo = new FileRepository(args.getString(GITDIR));
                ObjectId revision = repo.resolve(args.getString(UNTIL_REVS));
                RevWalk revWalk = new RevWalk(repo);
                RevCommit commit = revWalk.parseCommit(revision);
                TreeWalk treeWalk = TreeWalk.forPath(repo, args.getString(PATH), commit.getTree());
                ObjectId blobId = treeWalk.getObjectId(0);

                ObjectLoader objectLoader = revWalk.getObjectReader().open(blobId, Constants.OBJ_BLOB);
                ObjectStream binaryTestStream = objectLoader.openStream();
                boolean blobIsBinary = RawText.isBinary(binaryTestStream);
                binaryTestStream.close();
                Log.d(TAG, "blobIsBinary=" + blobIsBinary);
                return blobIsBinary ? new BinaryBlobView(objectLoader, treeWalk.getNameString())
                        : new TextBlobView(objectLoader);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }//from ww w  . j  a v  a 2 s.c  o  m
        }

    };
}

From source file:com.madgag.agit.FileListFragment.java

License:Open Source License

@Override
public Loader<List<FilePath>> onCreateLoader(int id, Bundle args) {
    return new AsyncLoader<List<FilePath>>(getActivity()) {
        public List<FilePath> loadInBackground() {

            try {
                Bundle args = getArguments();
                Repository repo = new FileRepository(args.getString(GITDIR));
                RevCommit commit = new RevWalk(repo).parseCommit(repo.resolve(args.getString(REVISION)));

                Stopwatch stopwatch = new Stopwatch().start();

                final List<FilePath> paths = newArrayList();
                TreeWalk treeWalk = new TreeWalk(repo);
                treeWalk.setRecursive(true);
                treeWalk.addTree(commit.getTree());

                while (treeWalk.next()) {
                    paths.add(new FilePath(treeWalk.getRawPath()));
                }/*from w  w  w  . j a  v a 2  s  . c  o  m*/
                Log.d(TAG, "Found " + paths.size() + " files " + stopwatch.stop());

                new Thread(new Runnable() {
                    @Override
                    public void run() { // knocks around 15-30% off time-to-display the list
                        Stopwatch stopwatch = new Stopwatch().start();
                        for (FilePath filePath : paths) {
                            filePath.getPath();
                        }
                        Log.d(TAG,
                                "Converted " + paths.size() + " path byte buffs to string " + stopwatch.stop());
                    }
                }).start();
                return paths;
            } catch (Exception e) {
                Log.w(TAG, "Bang", e);
                throw new RuntimeException(e);
            }
        }
    };
}