Search in sources :

Example 6 with CodeReviewRevWalk

use of com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk in project gerrit by GerritCodeReview.

the class MergeUtil method createCherryPickFromCommit.

public CodeReviewCommit createCherryPickFromCommit(ObjectInserter inserter, Config repoConfig, RevCommit mergeTip, RevCommit originalCommit, PersonIdent cherryPickCommitterIdent, String commitMsg, CodeReviewRevWalk rw, int parentIndex, boolean ignoreIdenticalTree, boolean allowConflicts) throws IOException, MergeIdenticalTreeException, MergeConflictException, MethodNotAllowedException, InvalidMergeStrategyException {
    ThreeWayMerger m = newThreeWayMerger(inserter, repoConfig);
    m.setBase(originalCommit.getParent(parentIndex));
    DirCache dc = DirCache.newInCore();
    if (allowConflicts && m instanceof ResolveMerger) {
        // The DirCache must be set on ResolveMerger before calling
        // ResolveMerger#merge(AnyObjectId...) otherwise the entries in DirCache don't get populated.
        ((ResolveMerger) m).setDirCache(dc);
    }
    ObjectId tree;
    ImmutableSet<String> filesWithGitConflicts;
    if (m.merge(mergeTip, originalCommit)) {
        filesWithGitConflicts = null;
        tree = m.getResultTreeId();
        if (tree.equals(mergeTip.getTree()) && !ignoreIdenticalTree) {
            throw new MergeIdenticalTreeException("identical tree");
        }
    } else {
        if (!allowConflicts) {
            throw new MergeConflictException(String.format("merge conflict while merging commits %s and %s", mergeTip.toObjectId(), originalCommit.toObjectId()));
        }
        if (!useContentMerge) {
            // conflict markers.
            throw new MethodNotAllowedException("Cherry-pick with allow conflicts requires that content merge is enabled.");
        }
        // For merging with conflict markers we need a ResolveMerger, double-check that we have one.
        checkState(m instanceof ResolveMerger, "allow conflicts is not supported");
        Map<String, MergeResult<? extends Sequence>> mergeResults = ((ResolveMerger) m).getMergeResults();
        filesWithGitConflicts = mergeResults.entrySet().stream().filter(e -> e.getValue().containsConflicts()).map(Map.Entry::getKey).collect(toImmutableSet());
        tree = mergeWithConflicts(rw, inserter, dc, "HEAD", mergeTip, "CHANGE", originalCommit, mergeResults);
    }
    CommitBuilder cherryPickCommit = new CommitBuilder();
    cherryPickCommit.setTreeId(tree);
    cherryPickCommit.setParentId(mergeTip);
    cherryPickCommit.setAuthor(originalCommit.getAuthorIdent());
    cherryPickCommit.setCommitter(cherryPickCommitterIdent);
    cherryPickCommit.setMessage(commitMsg);
    matchAuthorToCommitterDate(project, cherryPickCommit);
    CodeReviewCommit commit = rw.parseCommit(inserter.insert(cherryPickCommit));
    commit.setFilesWithGitConflicts(filesWithGitConflicts);
    return commit;
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevisionSyntaxException(org.eclipse.jgit.errors.RevisionSyntaxException) Comparator.naturalOrder(java.util.Comparator.naturalOrder) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) ThreeWayMergeStrategy(org.eclipse.jgit.merge.ThreeWayMergeStrategy) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Merger(org.eclipse.jgit.merge.Merger) Assisted(com.google.inject.assistedinject.Assisted) FooterKey(org.eclipse.jgit.revwalk.FooterKey) RevWalk(org.eclipse.jgit.revwalk.RevWalk) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) Config(org.eclipse.jgit.lib.Config) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) InvalidMergeStrategyException(com.google.gerrit.exceptions.InvalidMergeStrategyException) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) FooterLine(org.eclipse.jgit.revwalk.FooterLine) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) AssistedInject(com.google.inject.assistedinject.AssistedInject) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) ImmutableSortedSet.toImmutableSortedSet(com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet) ImmutableSet(com.google.common.collect.ImmutableSet) Sequence(org.eclipse.jgit.diff.Sequence) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Collection(java.util.Collection) LargeObjectException(org.eclipse.jgit.errors.LargeObjectException) Account(com.google.gerrit.entities.Account) Set(java.util.Set) RevSort(org.eclipse.jgit.revwalk.RevSort) Constants(org.eclipse.jgit.lib.Constants) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) BranchNameKey(com.google.gerrit.entities.BranchNameKey) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) MergeIdenticalTreeException(com.google.gerrit.server.submit.MergeIdenticalTreeException) MergeStrategy(org.eclipse.jgit.merge.MergeStrategy) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) BooleanProjectConfig(com.google.gerrit.entities.BooleanProjectConfig) DirCache(org.eclipse.jgit.dircache.DirCache) Optional(java.util.Optional) FluentLogger(com.google.common.flogger.FluentLogger) AmbiguousObjectException(org.eclipse.jgit.errors.AmbiguousObjectException) Iterables(com.google.common.collect.Iterables) LabelId(com.google.gerrit.entities.LabelId) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) CommitMergeStatus(com.google.gerrit.server.submit.CommitMergeStatus) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) RevFlag(org.eclipse.jgit.revwalk.RevFlag) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) HashMap(java.util.HashMap) DirCacheBuilder(org.eclipse.jgit.dircache.DirCacheBuilder) MergeBaseFailureReason(org.eclipse.jgit.errors.NoMergeBaseException.MergeBaseFailureReason) ChangeAlreadyMergedException(com.google.gerrit.server.submit.ChangeAlreadyMergedException) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) MergeWithConflictsNotSupportedException(com.google.gerrit.exceptions.MergeWithConflictsNotSupportedException) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) ChangeUtil(com.google.gerrit.server.ChangeUtil) NoMergeBaseException(org.eclipse.jgit.errors.NoMergeBaseException) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) Iterator(java.util.Iterator) ObjectIds.abbreviateName(com.google.gerrit.git.ObjectIds.abbreviateName) UTF_8(java.nio.charset.StandardCharsets.UTF_8) StorageException(com.google.gerrit.exceptions.StorageException) ProjectState(com.google.gerrit.server.project.ProjectState) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeResult(org.eclipse.jgit.merge.MergeResult) MergeSorter(com.google.gerrit.server.submit.MergeSorter) MergeFormatter(org.eclipse.jgit.merge.MergeFormatter) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) FooterConstants(com.google.gerrit.common.FooterConstants) Collections(java.util.Collections) Repository(org.eclipse.jgit.lib.Repository) InputStream(java.io.InputStream) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeResult(org.eclipse.jgit.merge.MergeResult) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) Sequence(org.eclipse.jgit.diff.Sequence) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) MergeIdenticalTreeException(com.google.gerrit.server.submit.MergeIdenticalTreeException) DirCache(org.eclipse.jgit.dircache.DirCache) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry)

Example 7 with CodeReviewRevWalk

use of com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk in project gerrit by GerritCodeReview.

the class CherryPickChange method cherryPick.

/**
 * This function can be called directly to cherry-pick a change (or commit if sourceChange is
 * null) with a few other parameters that are especially useful for cherry-picking a commit that
 * is the revert-of another change.
 *
 * @param sourceChange Change to cherry pick. Can be null, and then the function will only cherry
 *     pick a commit.
 * @param project Project name
 * @param sourceCommit Id of the commit to be cherry picked.
 * @param input Input object for different configurations of cherry pick.
 * @param dest Destination branch for the cherry pick.
 * @param timestamp the current timestamp.
 * @param revertedChange The id of the change that is reverted. This is used for the "revertOf"
 *     field to mark the created cherry pick change as "revertOf" the original change that was
 *     reverted.
 * @param changeIdForNewChange The Change-Id that the new change of the cherry pick will have.
 * @param idForNewChange The ID that the new change of the cherry pick will have. If provided and
 *     the cherry-pick doesn't result in creating a new change, then
 *     InvalidChangeOperationException is thrown.
 * @return Result object that describes the cherry pick.
 * @throws IOException Unable to open repository or read from the database.
 * @throws InvalidChangeOperationException Parent or branch don't exist, or two changes with same
 *     key exist in the branch. Also thrown when idForNewChange is not null but cherry-pick only
 *     creates a new patchset rather than a new change.
 * @throws UpdateException Problem updating the database using batchUpdateFactory.
 * @throws RestApiException Error such as invalid SHA1
 * @throws ConfigInvalidException Can't find account to notify.
 * @throws NoSuchProjectException Can't find project state.
 */
public Result cherryPick(@Nullable Change sourceChange, Project.NameKey project, ObjectId sourceCommit, CherryPickInput input, BranchNameKey dest, Instant timestamp, @Nullable Change.Id revertedChange, @Nullable ObjectId changeIdForNewChange, @Nullable Change.Id idForNewChange, @Nullable Boolean workInProgress) throws IOException, InvalidChangeOperationException, UpdateException, RestApiException, ConfigInvalidException, NoSuchProjectException {
    IdentifiedUser identifiedUser = user.get();
    try (Repository git = gitManager.openRepository(project);
        // before patch sets are updated.
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        CodeReviewRevWalk revWalk = CodeReviewCommit.newRevWalk(reader)) {
        Ref destRef = git.getRefDatabase().exactRef(dest.branch());
        if (destRef == null) {
            throw new InvalidChangeOperationException(String.format("Branch %s does not exist.", dest.branch()));
        }
        RevCommit baseCommit = getBaseCommit(destRef, project.get(), revWalk, input.base);
        CodeReviewCommit commitToCherryPick = revWalk.parseCommit(sourceCommit);
        if (input.parent <= 0 || input.parent > commitToCherryPick.getParentCount()) {
            throw new InvalidChangeOperationException(String.format("Cherry Pick: Parent %s does not exist. Please specify a parent in" + " range [1, %s].", input.parent, commitToCherryPick.getParentCount()));
        }
        // If the commit message is not set, the commit message of the source commit will be used.
        String commitMessage = Strings.nullToEmpty(input.message);
        commitMessage = commitMessage.isEmpty() ? commitToCherryPick.getFullMessage() : commitMessage;
        String destChangeId = getDestinationChangeId(commitMessage, changeIdForNewChange);
        ChangeData destChange = null;
        if (destChangeId != null) {
            // If "idForNewChange" is not null we must fail, since we are not expecting an already
            // existing change.
            destChange = getDestChangeWithVerification(destChangeId, dest, idForNewChange != null);
        }
        if (changeIdForNewChange != null) {
            // If Change-Id was explicitly provided for the new change, override the value in commit
            // message.
            commitMessage = ChangeIdUtil.insertId(commitMessage, changeIdForNewChange, true);
        } else if (destChangeId == null) {
            // If commit message did not specify Change-Id, generate a new one and insert to the
            // message.
            commitMessage = ChangeIdUtil.insertId(commitMessage, CommitMessageUtil.generateChangeId(), true);
        }
        commitMessage = CommitMessageUtil.checkAndSanitizeCommitMessage(commitMessage);
        CodeReviewCommit cherryPickCommit;
        ProjectState projectState = projectCache.get(dest.project()).orElseThrow(noSuchProject(dest.project()));
        PersonIdent committerIdent = identifiedUser.newCommitterIdent(timestamp, serverTimeZone);
        try {
            MergeUtil mergeUtil;
            if (input.allowConflicts) {
                // allowConflicts requires to use content merge
                mergeUtil = mergeUtilFactory.create(projectState, true);
            } else {
                // use content merge only if it's configured on the project
                mergeUtil = mergeUtilFactory.create(projectState);
            }
            cherryPickCommit = mergeUtil.createCherryPickFromCommit(oi, git.getConfig(), baseCommit, commitToCherryPick, committerIdent, commitMessage, revWalk, input.parent - 1, input.allowEmpty, input.allowConflicts);
            oi.flush();
        } catch (MergeIdenticalTreeException | MergeConflictException e) {
            throw new IntegrationConflictException("Cherry pick failed: " + e.getMessage(), e);
        }
        try (BatchUpdate bu = batchUpdateFactory.create(project, identifiedUser, timestamp)) {
            bu.setRepository(git, revWalk, oi);
            bu.setNotify(resolveNotify(input));
            Change.Id changeId;
            String newTopic = null;
            if (input.topic != null) {
                newTopic = Strings.emptyToNull(input.topic.trim());
            }
            if (newTopic == null && sourceChange != null && !Strings.isNullOrEmpty(sourceChange.getTopic())) {
                newTopic = sourceChange.getTopic() + "-" + dest.shortName();
            }
            if (destChange != null) {
                // The change key exists on the destination branch. The cherry pick
                // will be added as a new patch set.
                changeId = insertPatchSet(bu, git, destChange.notes(), cherryPickCommit, sourceChange, newTopic, input, workInProgress);
            } else {
                // Change key not found on destination branch. We can create a new
                // change.
                changeId = createNewChange(bu, cherryPickCommit, dest.branch(), newTopic, project, sourceChange, sourceCommit, input, revertedChange, idForNewChange, workInProgress);
            }
            bu.execute();
            return Result.create(changeId, cherryPickCommit.getFilesWithGitConflicts());
        }
    }
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) Change(com.google.gerrit.entities.Change) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) ChangeData(com.google.gerrit.server.query.change.ChangeData) MergeIdenticalTreeException(com.google.gerrit.server.submit.MergeIdenticalTreeException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) MergeUtil(com.google.gerrit.server.git.MergeUtil) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ProjectState(com.google.gerrit.server.project.ProjectState) IntegrationConflictException(com.google.gerrit.server.submit.IntegrationConflictException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 8 with CodeReviewRevWalk

use of com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk in project gerrit by GerritCodeReview.

the class RebaseSorter method isAlreadyMerged.

private boolean isAlreadyMerged(CodeReviewCommit commit, Branch.NameKey dest) throws IOException {
    try (CodeReviewRevWalk mirw = CodeReviewCommit.newRevWalk(rw.getObjectReader())) {
        mirw.reset();
        mirw.markStart(commit);
        // check if the commit is merged in other branches
        for (RevCommit accepted : alreadyAccepted) {
            if (mirw.isMergedInto(mirw.parseCommit(commit), mirw.parseCommit(accepted))) {
                log.debug("Dependency {} merged into branch head {}.", commit.getName(), accepted.getName());
                return true;
            }
        }
        // check if the commit associated change is merged in the same branch
        List<ChangeData> changes = internalChangeQuery.byCommit(commit);
        for (ChangeData change : changes) {
            if (change.change().getStatus() == Status.MERGED && change.change().getDest().equals(dest)) {
                log.debug("Dependency {} associated with merged change {}.", commit.getName(), change.getId());
                return true;
            }
        }
        return false;
    } catch (OrmException e) {
        throw new IOException(e);
    }
}
Also used : OrmException(com.google.gwtorm.server.OrmException) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) IOException(java.io.IOException) ChangeData(com.google.gerrit.server.query.change.ChangeData) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 9 with CodeReviewRevWalk

use of com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk in project gerrit by GerritCodeReview.

the class RebaseChangeOp method rebaseCommit.

/**
 * Rebase a commit.
 *
 * @param ctx repo context.
 * @param original the commit to rebase.
 * @param base base to rebase against.
 * @return the rebased commit.
 * @throws MergeConflictException the rebase failed due to a merge conflict.
 * @throws IOException the merge failed for another reason.
 */
private CodeReviewCommit rebaseCommit(RepoContext ctx, RevCommit original, ObjectId base, String commitMessage) throws ResourceConflictException, IOException {
    RevCommit parentCommit = original.getParent(0);
    if (base.equals(parentCommit)) {
        throw new ResourceConflictException("Change is already up to date.");
    }
    ThreeWayMerger merger = newMergeUtil().newThreeWayMerger(ctx.getInserter(), ctx.getRepoView().getConfig());
    merger.setBase(parentCommit);
    DirCache dc = DirCache.newInCore();
    if (allowConflicts && merger instanceof ResolveMerger) {
        // The DirCache must be set on ResolveMerger before calling
        // ResolveMerger#merge(AnyObjectId...) otherwise the entries in DirCache don't get populated.
        ((ResolveMerger) merger).setDirCache(dc);
    }
    boolean success = merger.merge(original, base);
    ObjectId tree;
    ImmutableSet<String> filesWithGitConflicts;
    if (success) {
        filesWithGitConflicts = null;
        tree = merger.getResultTreeId();
    } else {
        List<String> conflicts = ImmutableList.of();
        if (merger instanceof ResolveMerger) {
            conflicts = ((ResolveMerger) merger).getUnmergedPaths();
        }
        if (!allowConflicts || !(merger instanceof ResolveMerger)) {
            throw new MergeConflictException("The change could not be rebased due to a conflict during merge.\n\n" + MergeUtil.createConflictMessage(conflicts));
        }
        Map<String, MergeResult<? extends Sequence>> mergeResults = ((ResolveMerger) merger).getMergeResults();
        filesWithGitConflicts = mergeResults.entrySet().stream().filter(e -> e.getValue().containsConflicts()).map(Map.Entry::getKey).collect(toImmutableSet());
        tree = MergeUtil.mergeWithConflicts(ctx.getRevWalk(), ctx.getInserter(), dc, "PATCH SET", original, "BASE", ctx.getRevWalk().parseCommit(base), mergeResults);
    }
    CommitBuilder cb = new CommitBuilder();
    cb.setTreeId(tree);
    cb.setParentId(base);
    cb.setAuthor(original.getAuthorIdent());
    cb.setMessage(commitMessage);
    if (committerIdent != null) {
        cb.setCommitter(committerIdent);
    } else {
        cb.setCommitter(ctx.newCommitterIdent());
    }
    if (matchAuthorToCommitterDate) {
        cb.setAuthor(new PersonIdent(cb.getAuthor(), cb.getCommitter().getWhen(), cb.getCommitter().getTimeZone()));
    }
    ObjectId objectId = ctx.getInserter().insert(cb);
    ctx.getInserter().flush();
    CodeReviewCommit commit = ((CodeReviewRevWalk) ctx.getRevWalk()).parseCommit(objectId);
    commit.setFilesWithGitConflicts(filesWithGitConflicts);
    return commit;
}
Also used : PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) RevCommit(org.eclipse.jgit.revwalk.RevCommit) GroupCollector(com.google.gerrit.server.git.GroupCollector) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) RepoContext(com.google.gerrit.server.update.RepoContext) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Assisted(com.google.inject.assistedinject.Assisted) RevWalk(org.eclipse.jgit.revwalk.RevWalk) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) ImmutableList(com.google.common.collect.ImmutableList) MergeUtil(com.google.gerrit.server.git.MergeUtil) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) PostUpdateContext(com.google.gerrit.server.update.PostUpdateContext) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) Objects.requireNonNull(java.util.Objects.requireNonNull) Map(java.util.Map) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) ImmutableSet(com.google.common.collect.ImmutableSet) CurrentUser(com.google.gerrit.server.CurrentUser) Sequence(org.eclipse.jgit.diff.Sequence) ProjectState(com.google.gerrit.server.project.ProjectState) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) Base(com.google.gerrit.server.change.RebaseUtil.Base) Preconditions.checkState(com.google.common.base.Preconditions.checkState) ObjectId(org.eclipse.jgit.lib.ObjectId) PersonIdent(org.eclipse.jgit.lib.PersonIdent) MergeResult(org.eclipse.jgit.merge.MergeResult) List(java.util.List) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) DirCache(org.eclipse.jgit.dircache.DirCache) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) ObjectId(org.eclipse.jgit.lib.ObjectId) MergeResult(org.eclipse.jgit.merge.MergeResult) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) ThreeWayMerger(org.eclipse.jgit.merge.ThreeWayMerger) Sequence(org.eclipse.jgit.diff.Sequence) ResolveMerger(org.eclipse.jgit.merge.ResolveMerger) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) DirCache(org.eclipse.jgit.dircache.DirCache) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MergeConflictException(com.google.gerrit.extensions.restapi.MergeConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 10 with CodeReviewRevWalk

use of com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk in project gerrit by GerritCodeReview.

the class MergeabilityCacheImpl method get.

@Override
public boolean get(ObjectId commit, Ref intoRef, SubmitType submitType, String mergeStrategy, BranchNameKey dest, Repository repo) {
    ObjectId into = intoRef != null ? intoRef.getObjectId() : ObjectId.zeroId();
    EntryKey key = new EntryKey(commit, into, submitType, mergeStrategy);
    try {
        return cache.get(key, () -> {
            if (key.into.equals(ObjectId.zeroId())) {
                // Assume yes on new branch.
                return true;
            }
            try (CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
                Set<RevCommit> accepted = SubmitDryRun.getAlreadyAccepted(repo, rw);
                accepted.add(rw.parseCommit(key.into));
                accepted.addAll(Arrays.asList(rw.parseCommit(key.commit).getParents()));
                return submitDryRun.run(null, key.submitType, repo, rw, dest, key.into, key.commit, accepted);
            }
        });
    } catch (ExecutionException | UncheckedExecutionException e) {
        logger.atSevere().withCause(e.getCause()).log("Error checking mergeability of %s into %s (%s)", key.commit.name(), key.into.name(), key.submitType.name());
        return false;
    }
}
Also used : UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ObjectId(org.eclipse.jgit.lib.ObjectId) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

CodeReviewRevWalk (com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk)15 ObjectId (org.eclipse.jgit.lib.ObjectId)11 RevCommit (org.eclipse.jgit.revwalk.RevCommit)10 Repository (org.eclipse.jgit.lib.Repository)9 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)7 CodeReviewCommit (com.google.gerrit.server.git.CodeReviewCommit)7 ProjectState (com.google.gerrit.server.project.ProjectState)7 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)7 PersonIdent (org.eclipse.jgit.lib.PersonIdent)7 Change (com.google.gerrit.entities.Change)6 IOException (java.io.IOException)6 MergeConflictException (com.google.gerrit.extensions.restapi.MergeConflictException)5 Map (java.util.Map)5 Preconditions.checkState (com.google.common.base.Preconditions.checkState)4 PatchSet (com.google.gerrit.entities.PatchSet)4 ImmutableList (com.google.common.collect.ImmutableList)3 ImmutableSet (com.google.common.collect.ImmutableSet)3 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)3 Iterables (com.google.common.collect.Iterables)3 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)3