Example usage for org.eclipse.jgit.lib ObjectId fromString

List of usage examples for org.eclipse.jgit.lib ObjectId fromString

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId fromString.

Prototype

public static ObjectId fromString(String str) 

Source Link

Document

Convert an ObjectId from hex characters.

Usage

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

License:Apache License

private ProjectConfig parseConfig(Project.NameKey p, String idStr)
        throws IOException, ConfigInvalidException, RepositoryNotFoundException {
    ObjectId id = ObjectId.fromString(idStr);
    if (ObjectId.zeroId().equals(id)) {
        return null;
    }// www . j  a v a  2  s  . co  m
    return ProjectConfig.read(metaDataUpdateFactory.create(p), id);
}

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

License:Apache License

private static ObjectId toId(PatchSet ps) {
    try {/*from   ww  w.j av  a  2s .  co  m*/
        return ObjectId.fromString(ps.getRevision().get());
    } catch (IllegalArgumentException e) {
        log.error("Invalid revision on patch set " + ps);
        return null;
    }
}

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

License:Apache License

private boolean isMergedInto(RevWalk rw, PatchSet base, PatchSet tip) throws IOException {
    ObjectId baseId = ObjectId.fromString(base.getRevision().get());
    ObjectId tipId = ObjectId.fromString(tip.getRevision().get());
    return rw.isMergedInto(rw.parseCommit(baseId), rw.parseCommit(tipId));
}

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

License:Apache License

private boolean hasOneParent(RevWalk rw, PatchSet ps) throws IOException {
    // Prevent rebase of exotic changes (merge commit, no ancestor).
    RevCommit c = rw.parseCommit(ObjectId.fromString(ps.getRevision().get()));
    return c.getParentCount() == 1;
}

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

License:Apache License

/**
 * Find the commit onto which a patch set should be rebased.
 * <p>/* www .  ja  v  a2  s .  com*/
 * This is defined as the latest patch set of the change corresponding to
 * this commit's parent, or the destination branch tip in the case where the
 * parent's change is merged.
 *
 * @param patchSet patch set for which the new base commit should be found.
 * @param destBranch the destination branch.
 * @param git the repository.
 * @param rw the RevWalk.
 * @return the commit onto which the patch set should be rebased.
 * @throws InvalidChangeOperationException if rebase is not possible or not
 *     allowed.
 * @throws IOException if accessing the repository fails.
 * @throws OrmException if accessing the database fails.
 */
private String findBaseRevision(PatchSet patchSet, Branch.NameKey destBranch, Repository git, RevWalk rw)
        throws InvalidChangeOperationException, IOException, OrmException {
    String baseRev = null;
    RevCommit commit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));

    if (commit.getParentCount() > 1) {
        throw new InvalidChangeOperationException("Cannot rebase a change with multiple parents.");
    } else if (commit.getParentCount() == 0) {
        throw new InvalidChangeOperationException(
                "Cannot rebase a change without any parents" + " (is this the initial commit?).");
    }

    RevId parentRev = new RevId(commit.getParent(0).name());

    for (PatchSet depPatchSet : db.get().patchSets().byRevision(parentRev)) {
        Change.Id depChangeId = depPatchSet.getId().getParentKey();
        Change depChange = db.get().changes().get(depChangeId);
        if (!depChange.getDest().equals(destBranch)) {
            continue;
        }

        if (depChange.getStatus() == Status.ABANDONED) {
            throw new InvalidChangeOperationException(
                    "Cannot rebase a change with an abandoned parent: " + depChange.getKey());
        }

        if (depChange.getStatus().isOpen()) {
            if (depPatchSet.getId().equals(depChange.currentPatchSetId())) {
                throw new InvalidChangeOperationException(
                        "Change is already based on the latest patch set of the" + " dependent change.");
            }
            PatchSet latestDepPatchSet = db.get().patchSets().get(depChange.currentPatchSetId());
            baseRev = latestDepPatchSet.getRevision().get();
        }
        break;
    }

    if (baseRev == null) {
        // We are dependent on a merged PatchSet or have no PatchSet
        // dependencies at all.
        Ref destRef = git.getRefDatabase().exactRef(destBranch.get());
        if (destRef == null) {
            throw new InvalidChangeOperationException(
                    "The destination branch does not exist: " + destBranch.get());
        }
        baseRev = destRef.getObjectId().getName();
        if (baseRev.equals(parentRev.get())) {
            throw new InvalidChangeOperationException("Change is already up to date.");
        }
    }
    return baseRev;
}

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

License:Apache License

/**
 * Rebase the change of the given patch set on the given base commit.
 * <p>//from  w ww  .  j av  a 2  s. com
 * The rebased commit is added as new patch set to the change.
 * <p>
 * E-mail notification and triggering of hooks is only done for the creation
 * of the new patch set if {@code sendEmail} and {@code runHooks} are true,
 * respectively.
 *
 * @param git the repository.
 * @param inserter the object inserter.
 * @param change the change to rebase.
 * @param patchSetId the patch set ID to rebase.
 * @param uploader the user that creates the rebased patch set.
 * @param baseCommit the commit that should be the new base.
 * @param mergeUtil merge utilities for the destination project.
 * @param committerIdent the committer's identity.
 * @param runHooks if hooks should be run for the new patch set.
 * @param validate if commit validation should be run for the new patch set.
 * @param rw the RevWalk.
 * @return the new patch set, which is based on the given base commit.
 * @throws NoSuchChangeException if the change to which the patch set belongs
 *     does not exist or is not visible to the user.
 * @throws OrmException if accessing the database fails.
 * @throws IOException if rebase is not possible.
 * @throws InvalidChangeOperationException if rebase is not possible or not
 *     allowed.
 */
public PatchSet rebase(Repository git, RevWalk rw, ObjectInserter inserter, Change change,
        PatchSet.Id patchSetId, IdentifiedUser uploader, RevCommit baseCommit, MergeUtil mergeUtil,
        PersonIdent committerIdent, boolean runHooks, ValidatePolicy validate) throws NoSuchChangeException,
        OrmException, IOException, InvalidChangeOperationException, MergeConflictException {
    if (!change.currentPatchSetId().equals(patchSetId)) {
        throw new InvalidChangeOperationException("patch set is not current");
    }
    PatchSet originalPatchSet = db.get().patchSets().get(patchSetId);

    RevCommit rebasedCommit;
    ObjectId oldId = ObjectId.fromString(originalPatchSet.getRevision().get());
    ObjectId newId = rebaseCommit(git, inserter, rw.parseCommit(oldId), baseCommit, mergeUtil, committerIdent);

    rebasedCommit = rw.parseCommit(newId);

    ChangeControl changeControl = changeControlFactory.validateFor(change, uploader);

    PatchSetInserter patchSetInserter = patchSetInserterFactory.create(git, rw, changeControl, rebasedCommit)
            .setValidatePolicy(validate).setDraft(originalPatchSet.isDraft())
            .setUploader(uploader.getAccountId()).setSendMail(false).setRunHooks(runHooks);

    PatchSet.Id newPatchSetId = patchSetInserter.getPatchSetId();
    ChangeMessage cmsg = new ChangeMessage(
            new ChangeMessage.Key(change.getId(), ChangeUtil.messageUUID(db.get())), uploader.getAccountId(),
            TimeUtil.nowTs(), patchSetId);

    cmsg.setMessage("Patch Set " + newPatchSetId.get() + ": Patch Set " + patchSetId.get() + " was rebased");

    Change newChange = patchSetInserter.setMessage(cmsg).insert();

    return db.get().patchSets().get(newChange.currentPatchSetId());
}

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

License:Apache License

@Override
public void updateRepo(RepoContext ctx) throws MergeConflictException, InvalidChangeOperationException,
        RestApiException, IOException, OrmException, NoSuchChangeException {
    // Ok that originalPatchSet was not read in a transaction, since we just
    // need its revision.
    RevId oldRev = originalPatchSet.getRevision();

    RevWalk rw = ctx.getRevWalk();/* w w  w. j  a v  a  2 s  . com*/
    RevCommit original = rw.parseCommit(ObjectId.fromString(oldRev.get()));
    rw.parseBody(original);
    RevCommit baseCommit;
    if (baseCommitish != null) {
        baseCommit = rw.parseCommit(ctx.getRepository().resolve(baseCommitish));
    } else {
        baseCommit = rw.parseCommit(rebaseUtil.findBaseRevision(originalPatchSet, ctl.getChange().getDest(),
                ctx.getRepository(), ctx.getRevWalk()));
    }

    rebasedCommit = rebaseCommit(ctx, original, baseCommit);

    RevId baseRevId = new RevId(
            (baseCommitish != null) ? baseCommitish : ObjectId.toString(baseCommit.getId()));
    Base base = rebaseUtil.parseBase(new RevisionResource(new ChangeResource(ctl), originalPatchSet),
            baseRevId.get());

    rebasedPatchSetId = ChangeUtil.nextPatchSetId(ctx.getRepository(), ctl.getChange().currentPatchSetId());
    patchSetInserter = patchSetInserterFactory.create(ctl.getRefControl(), rebasedPatchSetId, rebasedCommit)
            .setDraft(originalPatchSet.isDraft()).setSendMail(false).setRunHooks(runHooks)
            .setCopyApprovals(copyApprovals).setMessage("Patch Set " + rebasedPatchSetId.get() + ": Patch Set "
                    + originalPatchSet.getId().get() + " was rebased");

    if (base != null) {
        patchSetInserter.setGroups(base.patchSet().getGroups());
    }
    if (validate != null) {
        patchSetInserter.setValidatePolicy(validate);
    }
    patchSetInserter.updateRepo(ctx);
}

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

License:Apache License

/**
 * Find the commit onto which a patch set should be rebased.
 * <p>//from   w w w  .j  a  v  a  2  s. c om
 * This is defined as the latest patch set of the change corresponding to
 * this commit's parent, or the destination branch tip in the case where the
 * parent's change is merged.
 *
 * @param patchSet patch set for which the new base commit should be found.
 * @param destBranch the destination branch.
 * @param git the repository.
 * @param rw the RevWalk.
 * @return the commit onto which the patch set should be rebased.
 * @throws RestApiException if rebase is not possible.
 * @throws IOException if accessing the repository fails.
 * @throws OrmException if accessing the database fails.
 */
ObjectId findBaseRevision(PatchSet patchSet, Branch.NameKey destBranch, Repository git, RevWalk rw)
        throws RestApiException, IOException, OrmException {
    String baseRev = null;
    RevCommit commit = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));

    if (commit.getParentCount() > 1) {
        throw new UnprocessableEntityException("Cannot rebase a change with multiple parents.");
    } else if (commit.getParentCount() == 0) {
        throw new UnprocessableEntityException(
                "Cannot rebase a change without any parents" + " (is this the initial commit?).");
    }

    RevId parentRev = new RevId(commit.getParent(0).name());

    CHANGES: for (ChangeData cd : queryProvider.get().byBranchCommit(destBranch, parentRev.get())) {
        for (PatchSet depPatchSet : cd.patchSets()) {
            if (!depPatchSet.getRevision().equals(parentRev)) {
                continue;
            }
            Change depChange = cd.change();
            if (depChange.getStatus() == Status.ABANDONED) {
                throw new ResourceConflictException(
                        "Cannot rebase a change with an abandoned parent: " + depChange.getKey());
            }

            if (depChange.getStatus().isOpen()) {
                if (depPatchSet.getId().equals(depChange.currentPatchSetId())) {
                    throw new ResourceConflictException(
                            "Change is already based on the latest patch set of the" + " dependent change.");
                }
                baseRev = cd.currentPatchSet().getRevision().get();
            }
            break CHANGES;
        }
    }

    if (baseRev == null) {
        // We are dependent on a merged PatchSet or have no PatchSet
        // dependencies at all.
        Ref destRef = git.getRefDatabase().exactRef(destBranch.get());
        if (destRef == null) {
            throw new UnprocessableEntityException(
                    "The destination branch does not exist: " + destBranch.get());
        }
        baseRev = destRef.getObjectId().getName();
        if (baseRev.equals(parentRev.get())) {
            throw new ResourceConflictException("Change is already up to date.");
        }
    }
    return ObjectId.fromString(baseRev);
}

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

License:Apache License

private Map<String, PatchSetData> collectById(List<ChangeData> in) throws OrmException, IOException {
    Project.NameKey project = in.get(0).change().getProject();
    Map<String, PatchSetData> result = Maps.newHashMapWithExpectedSize(in.size() * 3);
    try (Repository repo = repoManager.openRepository(project); RevWalk rw = new RevWalk(repo)) {
        rw.setRetainBody(true);/*ww w. j  av a2 s. c o m*/
        for (ChangeData cd : in) {
            checkArgument(cd.change().getProject().equals(project),
                    "Expected change %s in project %s, found %s", cd.getId(), project,
                    cd.change().getProject());
            for (PatchSet ps : cd.patchSets()) {
                String id = ps.getRevision().get();
                RevCommit c = rw.parseCommit(ObjectId.fromString(id));
                PatchSetData psd = PatchSetData.create(cd, ps, c);
                result.put(id, psd);
            }
        }
    }
    return result;
}

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

License:Apache License

@Override
public UiAction.Description getDescription(RevisionResource resource) {
    PatchSet.Id current = resource.getChange().currentPatchSetId();
    String topic = resource.getChange().getTopic();
    boolean visible = !resource.getPatchSet().isDraft() && resource.getChange().getStatus().isOpen()
            && resource.getPatchSet().getId().equals(current) && resource.getControl().canSubmit();
    ReviewDb db = dbProvider.get();/*  ww w  . j av  a  2s .c  om*/
    ChangeData cd = changeDataFactory.create(db, resource.getControl());

    try {
        MergeOp.checkSubmitRule(cd);
    } catch (ResourceConflictException e) {
        visible = false;
    } catch (OrmException e) {
        log.error("Error checking if change is submittable", e);
        throw new OrmRuntimeException("Could not determine problems for the change", e);
    }

    if (!visible) {
        return new UiAction.Description().setLabel("").setTitle("").setVisible(false);
    }

    Boolean enabled;
    try {
        enabled = cd.isMergeable();
    } catch (OrmException e) {
        throw new OrmRuntimeException("Could not determine mergeability", e);
    }

    ChangeSet cs;
    try {
        cs = mergeSuperSet.completeChangeSet(db, cd.change());
    } catch (OrmException | IOException e) {
        throw new OrmRuntimeException("Could not determine complete set of " + "changes to be submitted", e);
    }

    int topicSize = 0;
    if (!Strings.isNullOrEmpty(topic)) {
        topicSize = getChangesByTopic(topic).size();
    }
    boolean treatWithTopic = submitWholeTopic && !Strings.isNullOrEmpty(topic) && topicSize > 1;

    String submitProblems = problemsForSubmittingChangeset(cs, resource.getUser());
    if (submitProblems != null) {
        return new UiAction.Description()
                .setLabel(treatWithTopic ? submitTopicLabel : (cs.size() > 1) ? labelWithParents : label)
                .setTitle(submitProblems).setVisible(true).setEnabled(false);
    }

    if (treatWithTopic) {
        Map<String, String> params = ImmutableMap.of("topicSize", String.valueOf(topicSize), "submitSize",
                String.valueOf(cs.size()));
        return new UiAction.Description().setLabel(submitTopicLabel)
                .setTitle(Strings.emptyToNull(submitTopicTooltip.replace(params))).setVisible(true)
                .setEnabled(Boolean.TRUE.equals(enabled));
    } else {
        RevId revId = resource.getPatchSet().getRevision();
        Map<String, String> params = ImmutableMap.of("patchSet",
                String.valueOf(resource.getPatchSet().getPatchSetId()), "branch",
                resource.getChange().getDest().getShortName(), "commit",
                ObjectId.fromString(revId.get()).abbreviate(7).name(), "submitSize", String.valueOf(cs.size()));
        ParameterizedString tp = cs.size() > 1 ? titlePatternWithAncestors : titlePattern;
        return new UiAction.Description().setLabel(cs.size() > 1 ? labelWithParents : label)
                .setTitle(Strings.emptyToNull(tp.replace(params))).setVisible(true)
                .setEnabled(Boolean.TRUE.equals(enabled));
    }
}