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.appraise.eclipse.core.client.git.GitNoteWriter.java

License:Open Source License

/**
 * Private ctor. Use the static factory methods.
 *//*from w w w  . j  a va  2s  .co m*/
private GitNoteWriter(String reviewHash, final Repository repo, String ref, PersonIdent author) {
    this.ref = ref;
    this.repo = repo;
    this.author = author;

    revWalk = new RevWalk(repo);
    inserter = repo.newObjectInserter();
    reader = repo.newObjectReader();

    try {
        ObjectId reviewRefObjId = repo.resolve(reviewHash);
        this.reviewCommit = revWalk.parseCommit(reviewRefObjId);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Failed to init note writer for commit " + reviewHash, e);
        throw new RuntimeException(e);
    }
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloneFunction.java

License:Open Source License

private boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }//from   w w w  .j  av a 2 s .c o m
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.devtools.build.lib.bazel.repository.GitCloner.java

License:Open Source License

private static boolean isUpToDate(GitRepositoryDescriptor descriptor) {
    // Initializing/checking status of/etc submodules cleanly is hard, so don't try for now.
    if (descriptor.initSubmodules) {
        return false;
    }//from   ww  w . j  a va2s  . c o  m
    Repository repository = null;
    try {
        repository = new FileRepositoryBuilder()
                .setGitDir(descriptor.directory.getChild(Constants.DOT_GIT).getPathFile()).setMustExist(true)
                .build();
        ObjectId head = repository.resolve(Constants.HEAD);
        ObjectId checkout = repository.resolve(descriptor.checkout);
        if (head != null && checkout != null && head.equals(checkout)) {
            Status status = Git.wrap(repository).status().call();
            if (!status.hasUncommittedChanges()) {
                // new_git_repository puts (only) BUILD and WORKSPACE, and
                // git_repository doesn't add any files.
                Set<String> untracked = status.getUntracked();
                if (untracked.isEmpty() || (untracked.size() == 2 && untracked.contains("BUILD")
                        && untracked.contains("WORKSPACE"))) {
                    return true;
                }
            }
        }
    } catch (GitAPIException | IOException e) {
        // Any exceptions here, we'll just blow it away and try cloning fresh.
        // The fresh clone avoids any weirdness due to what's there and has nicer
        // error reporting.
    } finally {
        if (repository != null) {
            repository.close();
        }
    }
    return false;
}

From source file:com.google.gerrit.acceptance.rest.change.AbstractSubmit.java

License:Apache License

private String getLatestDiff(Repository repo) throws IOException {
    ObjectId oldTreeId = repo.resolve("HEAD~1^{tree}");
    ObjectId newTreeId = repo.resolve("HEAD^{tree}");
    return getLatestDiff(repo, oldTreeId, newTreeId);
}

From source file:com.google.gerrit.httpd.rpc.project.AddBranch.java

License:Apache License

private ObjectId parseStartingRevision(final Repository repo) throws InvalidRevisionException {
    try {//from   w  w w.  jav  a 2  s . c  o  m
        final ObjectId revid = repo.resolve(startingRevision);
        if (revid == null) {
            throw new InvalidRevisionException();
        }
        return revid;
    } catch (IOException err) {
        log.error("Cannot resolve \"" + startingRevision + "\" in project \"" + projectName + "\"", err);
        throw new InvalidRevisionException();
    }
}

From source file:com.google.gerrit.plugins.GitLogCommand.java

License:Apache License

@Override
public void run() throws UnloggedFailure, Failure, Exception {
    ObjectId from = null;/*www . java2s  .  c  om*/
    ObjectId to = null;
    Repository repository = null;
    RevCommit rev = null;
    RevWalk walk = null;
    Project.NameKey project = null;
    Pair<String, String> range = null;
    ArrayList<Map<String, String>> cmts = new ArrayList<Map<String, String>>();

    // Check that a project was specified.
    if (projectName == null) {
        this.resultPrinter(this.format, GitLogReturnCode.WRONG_PROJECT_NAME, null);
        return;
    }

    // Check that we have something to parse.
    if (input == null) {
        this.resultPrinter(this.format, GitLogReturnCode.WRONG_RANGE, null);
        return;
    }

    // Remove .git if project name has it.
    if (projectName.endsWith(".git")) {
        projectName = projectName.substring(0, projectName.length() - 4);
    }

    // Check that project/repository exists.
    project = Project.NameKey.parse(projectName);
    if (!repoManager.list().contains(project)) {
        this.resultPrinter(this.format, GitLogReturnCode.WRONG_PROJECT_NAME, null);
        return;
    }

    repository = repoManager.openRepository(project);
    walk = new RevWalk(repository);

    // Parse provided input to get range of revisions.
    range = GitLogInputParser.parse(input);

    /*
     * If "from" and "to" revisions are null then it means that we got faulty
     * input and we need to notify user about it
     */
    if (range.getValue0() == null && range.getValue1() == null) {
        this.resultPrinter(this.format, GitLogReturnCode.WRONG_RANGE, null);
        return;
    }

    /*
     * If "from" value is null then it means that we have internal problem with
     * input parser because such situation should never happen
     */
    if (range.getValue0() == null) {
        this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
        return;
    }

    // Get "from" commit object.
    try {
        from = repository.resolve(range.getValue0());
    } catch (AmbiguousObjectException e) {
        // Few commits corresponds to provided reference. Return all of them
        Map<String, String> candidates = new HashMap<String, String>();
        for (Iterator<ObjectId> iter = e.getCandidates().iterator(); iter.hasNext();) {
            candidates.put("candidate", iter.next().getName());
        }
        cmts.add(candidates);
        this.resultPrinter(this.format, GitLogReturnCode.AMBIGUOUS_COMMIT_REF, cmts);
        return;
    } catch (IncorrectObjectTypeException e) {
        this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
        return;
    } catch (RevisionSyntaxException e) {
        this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
        return;
    } catch (IOException e) {
        this.resultPrinter(this.format, GitLogReturnCode.ACCESS_ERROR, null);
        return;
    }

    if (from == null) {
        this.resultPrinter(this.format, GitLogReturnCode.FIRST_REF_NOT_FOUND, null);
        return;
    }

    // Get "to" commit object if commit reference is not null.
    if (range.getValue1() != null) {
        try {
            to = repository.resolve(range.getValue1());
        } catch (AmbiguousObjectException e) {
            // Few commits corresponds to provided reference. Return all of them
            Map<String, String> candidates = new HashMap<String, String>();
            for (Iterator<ObjectId> iter = e.getCandidates().iterator(); iter.hasNext();) {
                candidates.put("candidate", iter.next().getName());
            }
            cmts.add(candidates);
            this.resultPrinter(this.format, GitLogReturnCode.AMBIGUOUS_COMMIT_REF, cmts);
            return;
        } catch (IncorrectObjectTypeException e) {
            this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
            return;
        } catch (RevisionSyntaxException e) {
            this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
            return;
        } catch (IOException e) {
            this.resultPrinter(this.format, GitLogReturnCode.ACCESS_ERROR, null);
            return;
        }
        if (to == null) {
            this.resultPrinter(this.format, GitLogReturnCode.SECOND_REF_NOT_FOUND, null);
            return;
        }
    }

    if (from == to) {
        // We asked to show only one commit.
        try {
            rev = walk.parseCommit(from);
        } catch (MissingObjectException e) {
            this.resultPrinter(this.format, GitLogReturnCode.FIRST_REF_NOT_FOUND, null);
            return;
        } catch (IncorrectObjectTypeException e) {
            this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
            return;
        } catch (IOException e) {
            this.resultPrinter(this.format, GitLogReturnCode.ACCESS_ERROR, null);
            return;
        }
        cmts.add(this.revCommitToMap(rev));
    } else if (from != null && to != null) {
        /*
         * we asked to show log between two commits we want our search to be
         * inclusive so first we want to save "to" into result
         */
        try {
            rev = walk.parseCommit(to);
        } catch (MissingObjectException e) {
            this.resultPrinter(this.format, GitLogReturnCode.SECOND_REF_NOT_FOUND, null);
            return;
        } catch (IncorrectObjectTypeException e) {
            this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
            return;
        } catch (IOException e) {
            this.resultPrinter(this.format, GitLogReturnCode.ACCESS_ERROR, null);
            return;
        }
        Map<String, String> last = this.revCommitToMap(rev);
        /*
         * Set filter for revision walk. It is important that we got "to" before
         * this moment, otherwise it will be filtered out.
         */
        try {
            rev = walk.parseCommit(from);
        } catch (MissingObjectException e) {
            this.resultPrinter(this.format, GitLogReturnCode.FIRST_REF_NOT_FOUND, null);
            return;
        } catch (IncorrectObjectTypeException e) {
            this.resultPrinter(this.format, GitLogReturnCode.INTERNAL_ERROR, null);
            return;
        } catch (IOException e) {
            this.resultPrinter(this.format, GitLogReturnCode.ACCESS_ERROR, null);
            return;
        }

        walk.markUninteresting(walk.parseCommit(to));
        for (RevCommit next : walk) {
            cmts.add(this.revCommitToMap(next));
        }
        // Insert "to" to the end of array
        cmts.add(last);
    } else if (from != null && to == null) {
        // If we asked to show log for the entire history to the root commit.
        walk.markStart(walk.parseCommit(from));
        for (RevCommit next : walk) {
            cmts.add(this.revCommitToMap(next));
        }
    }

    this.resultPrinter(this.format, GitLogReturnCode.OK, cmts);
}

From source file:com.google.gerrit.server.change.RebaseChange.java

License:Apache License

/**
 * Rebase the change of the given patch set.
 * <p>/*  w w w  .  java2 s . c  om*/
 * If the patch set has no dependency to an open change, then the change is
 * rebased on the tip of the destination branch.
 * <p>
 * If the patch set depends on an open change, it is rebased on the latest
 * patch set of this change.
 * <p>
 * The rebased commit is added as new patch set to the change.
 * <p>
 * E-mail notification and triggering of hooks happens for the creation of the
 * new patch set.
 *
 * @param git the repository.
 * @param rw the RevWalk.
 * @param rsrc revision to rebase.
 * @param newBaseRev the commit that should be the new base.
 * @throws NoSuchChangeException if the change to which the patch set belongs
 *     does not exist or is not visible to the user.
 * @throws EmailException if sending the e-mail to notify about the new patch
 *     set fails.
 * @throws OrmException if accessing the database fails.
 * @throws IOException if accessing the repository fails.
 * @throws InvalidChangeOperationException if rebase is not possible or not
 *     allowed.
 */
public void rebase(Repository git, RevWalk rw, RevisionResource rsrc, String newBaseRev)
        throws NoSuchChangeException, EmailException, OrmException, IOException, ResourceConflictException,
        InvalidChangeOperationException {
    Change change = rsrc.getChange();
    PatchSet patchSet = rsrc.getPatchSet();
    IdentifiedUser uploader = (IdentifiedUser) rsrc.getControl().getCurrentUser();

    try (ObjectInserter inserter = git.newObjectInserter()) {
        String baseRev = newBaseRev;
        if (baseRev == null) {
            baseRev = findBaseRevision(patchSet, change.getDest(), git, rw);
        }

        ObjectId baseObjectId = git.resolve(baseRev);
        if (baseObjectId == null) {
            throw new InvalidChangeOperationException("Cannot rebase: Failed to resolve baseRev: " + baseRev);
        }

        RevCommit baseCommit = rw.parseCommit(baseObjectId);
        PersonIdent committerIdent = uploader.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone);

        rebase(git, rw, inserter, change, patchSet.getId(), uploader, baseCommit,
                mergeUtilFactory.create(rsrc.getControl().getProjectControl().getProjectState(), true),
                committerIdent, true, ValidatePolicy.GERRIT);
    } catch (MergeConflictException e) {
        throw new ResourceConflictException(e.getMessage());
    }
}

From source file:com.google.gerrit.server.changedetail.RebaseChange.java

License:Apache License

/**
 * Rebases the change of the given patch set.
 *
 * It is verified that the current user is allowed to do the rebase.
 *
 * If the patch set has no dependency to an open change, then the change is
 * rebased on the tip of the destination branch.
 *
 * If the patch set depends on an open change, it is rebased on the latest
 * patch set of this change./*from  w w w.  j  a v a  2s  .co  m*/
 *
 * The rebased commit is added as new patch set to the change.
 *
 * E-mail notification and triggering of hooks happens for the creation of the
 * new patch set.
 *
 * @param change the change to perform the rebase for
 * @param patchSetId the id of the patch set
 * @param uploader the user that creates the rebased patch set
 * @param newBaseRev the commit that should be the new base
 * @throws NoSuchChangeException thrown if the change to which the patch set
 *         belongs does not exist or is not visible to the user
 * @throws EmailException thrown if sending the e-mail to notify about the new
 *         patch set fails
 * @throws OrmException thrown in case accessing the database fails
 * @throws IOException thrown if rebase is not possible or not needed
 * @throws InvalidChangeOperationException thrown if rebase is not allowed
 */
public void rebase(Change change, PatchSet.Id patchSetId, final IdentifiedUser uploader,
        final String newBaseRev) throws NoSuchChangeException, EmailException, OrmException, IOException,
        InvalidChangeOperationException {
    final Change.Id changeId = patchSetId.getParentKey();
    final ChangeControl changeControl = changeControlFactory.validateFor(change, uploader);
    if (!changeControl.canRebase()) {
        throw new InvalidChangeOperationException(
                "Cannot rebase: New patch sets are not allowed to be added to change: " + changeId.toString());
    }
    Repository git = null;
    RevWalk rw = null;
    ObjectInserter inserter = null;
    try {
        git = gitManager.openRepository(change.getProject());
        rw = new RevWalk(git);
        inserter = git.newObjectInserter();

        String baseRev = newBaseRev;
        if (baseRev == null) {
            baseRev = findBaseRevision(patchSetId, db.get(), change.getDest(), git, null, null, null);
        }
        ObjectId baseObjectId = git.resolve(baseRev);
        if (baseObjectId == null) {
            throw new InvalidChangeOperationException("Cannot rebase: Failed to resolve baseRev: " + baseRev);
        }
        final RevCommit baseCommit = rw.parseCommit(baseObjectId);

        PersonIdent committerIdent = uploader.newCommitterIdent(TimeUtil.nowTs(), serverTimeZone);

        rebase(git, rw, inserter, patchSetId, change, uploader, baseCommit,
                mergeUtilFactory.create(changeControl.getProjectControl().getProjectState(), true),
                committerIdent, true, ValidatePolicy.GERRIT);
    } catch (MergeConflictException e) {
        throw new IOException(e.getMessage());
    } finally {
        if (inserter != null) {
            inserter.release();
        }
        if (rw != null) {
            rw.release();
        }
        if (git != null) {
            git.close();
        }
    }
}

From source file:com.google.gerrit.server.project.CreateBranch.java

License:Apache License

private ObjectId parseBaseRevision(Repository repo, Project.NameKey projectName, String baseRevision)
        throws InvalidRevisionException {
    try {/*  w  w w  .  j a  va  2s .  co  m*/
        final ObjectId revid = repo.resolve(baseRevision);
        if (revid == null) {
            throw new InvalidRevisionException();
        }
        return revid;
    } catch (IOException err) {
        log.error("Cannot resolve \"" + baseRevision + "\" in project \"" + projectName.get() + "\"", err);
        throw new InvalidRevisionException();
    } catch (RevisionSyntaxException err) {
        log.error("Invalid revision syntax \"" + baseRevision + "\"", err);
        throw new InvalidRevisionException();
    }
}

From source file:com.google.gerrit.server.project.RefUtil.java

License:Apache License

public static ObjectId parseBaseRevision(Repository repo, Project.NameKey projectName, String baseRevision)
        throws InvalidRevisionException {
    try {//  w ww . j  ava 2 s  . c  om
        ObjectId revid = repo.resolve(baseRevision);
        if (revid == null) {
            throw new InvalidRevisionException();
        }
        return revid;
    } catch (IOException err) {
        log.error("Cannot resolve \"" + baseRevision + "\" in project \"" + projectName.get() + "\"", err);
        throw new InvalidRevisionException();
    } catch (RevisionSyntaxException err) {
        log.error("Invalid revision syntax \"" + baseRevision + "\"", err);
        throw new InvalidRevisionException();
    }
}