Search in sources :

Example 96 with ChangeData

use of com.google.gerrit.server.query.change.ChangeData in project gerrit by GerritCodeReview.

the class SubmitRequirementsEvaluatorIT method byFileEdits_addedContent_nonMatching.

@Test
public void byFileEdits_addedContent_nonMatching() throws Exception {
    Change.Id parent = changeOperations.newChange().file(FILE_NAME).content(CONTENT).create();
    Change.Id childId = changeOperations.newChange().file(FILE_NAME).content(CONTENT + "line 4\n").childOf().change(parent).create();
    SubmitRequirementExpression exp = SubmitRequirementExpression.create("file:\"'^.*\\.txt',withDiffContaining='line 5'\"");
    ChangeData childChangeData = changeQueryProvider.get().byLegacyChangeId(childId).get(0);
    SubmitRequirementExpressionResult srResult = evaluator.evaluateExpression(exp, childChangeData);
    assertThat(srResult.status()).isEqualTo(SubmitRequirementExpressionResult.Status.FAIL);
}
Also used : SubmitRequirementExpression(com.google.gerrit.entities.SubmitRequirementExpression) SubmitRequirementExpressionResult(com.google.gerrit.entities.SubmitRequirementExpressionResult) Change(com.google.gerrit.entities.Change) ChangeData(com.google.gerrit.server.query.change.ChangeData) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 97 with ChangeData

use of com.google.gerrit.server.query.change.ChangeData in project gerrit by GerritCodeReview.

the class EventFactory method addDependsOn.

private void addDependsOn(RevWalk rw, ChangeAttribute ca, Change change, PatchSet currentPs) throws IOException {
    RevCommit commit = rw.parseCommit(currentPs.commitId());
    final List<String> parentNames = new ArrayList<>(commit.getParentCount());
    for (RevCommit p : commit.getParents()) {
        parentNames.add(p.name());
    }
    // this patch set's revision.
    for (ChangeData cd : queryProvider.get().byProjectCommits(change.getProject(), parentNames)) {
        for (PatchSet ps : cd.patchSets()) {
            for (String p : parentNames) {
                if (!ps.commitId().name().equals(p)) {
                    continue;
                }
                ca.dependsOn.add(newDependsOn(requireNonNull(cd.change()), ps));
            }
        }
    }
    // Sort by original parent order.
    ca.dependsOn.sort(comparing(d -> {
        for (int i = 0; i < parentNames.size(); i++) {
            if (parentNames.get(i).equals(d.revision)) {
                return i;
            }
        }
        return parentNames.size() + 1;
    }));
}
Also used : SubmitRequirementAttribute(com.google.gerrit.server.data.SubmitRequirementAttribute) ListMultimap(com.google.common.collect.ListMultimap) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) Inject(com.google.inject.Inject) HumanComment(com.google.gerrit.entities.HumanComment) RefUpdateAttribute(com.google.gerrit.server.data.RefUpdateAttribute) RevWalk(org.eclipse.jgit.revwalk.RevWalk) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LabelTypes(com.google.gerrit.entities.LabelTypes) LegacySubmitRequirement(com.google.gerrit.entities.LegacySubmitRequirement) DiffNotAvailableException(com.google.gerrit.server.patch.DiffNotAvailableException) UserIdentity(com.google.gerrit.entities.UserIdentity) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) AccountAttribute(com.google.gerrit.server.data.AccountAttribute) PatchSetCommentAttribute(com.google.gerrit.server.data.PatchSetCommentAttribute) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) PatchSetAttribute(com.google.gerrit.server.data.PatchSetAttribute) Set(java.util.Set) ChangeKindCache(com.google.gerrit.server.change.ChangeKindCache) SubmitRecord(com.google.gerrit.entities.SubmitRecord) ApprovalAttribute(com.google.gerrit.server.data.ApprovalAttribute) BranchNameKey(com.google.gerrit.entities.BranchNameKey) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) PersonIdent(org.eclipse.jgit.lib.PersonIdent) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Emails(com.google.gerrit.server.account.Emails) DiffOperations(com.google.gerrit.server.patch.DiffOperations) SubmitRecordAttribute(com.google.gerrit.server.data.SubmitRecordAttribute) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Optional(java.util.Optional) FluentLogger(com.google.common.flogger.FluentLogger) TrackingIdAttribute(com.google.gerrit.server.data.TrackingIdAttribute) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) IndexConfig(com.google.gerrit.index.IndexConfig) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ArrayList(java.util.ArrayList) ChangeMessage(com.google.gerrit.entities.ChangeMessage) Lists(com.google.common.collect.Lists) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Objects.requireNonNull(java.util.Objects.requireNonNull) FilePathAdapter(com.google.gerrit.server.patch.FilePathAdapter) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Comparator.comparing(java.util.Comparator.comparing) SubmitLabelAttribute(com.google.gerrit.server.data.SubmitLabelAttribute) StorageException(com.google.gerrit.exceptions.StorageException) DependencyAttribute(com.google.gerrit.server.data.DependencyAttribute) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ObjectId(org.eclipse.jgit.lib.ObjectId) DiffOptions(com.google.gerrit.server.patch.DiffOptions) Provider(com.google.inject.Provider) MessageAttribute(com.google.gerrit.server.data.MessageAttribute) AccountTemplateUtil(com.google.gerrit.server.util.AccountTemplateUtil) AccountState(com.google.gerrit.server.account.AccountState) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ChangeAttribute(com.google.gerrit.server.data.ChangeAttribute) PatchAttribute(com.google.gerrit.server.data.PatchAttribute) ArrayList(java.util.ArrayList) PatchSet(com.google.gerrit.entities.PatchSet) ChangeData(com.google.gerrit.server.query.change.ChangeData) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 98 with ChangeData

use of com.google.gerrit.server.query.change.ChangeData 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 99 with ChangeData

use of com.google.gerrit.server.query.change.ChangeData in project gerrit by GerritCodeReview.

the class RelatedChangesSorter method collectById.

private Map<ObjectId, PatchSetData> collectById(List<ChangeData> in) throws IOException {
    Project.NameKey project = in.get(0).change().getProject();
    Map<ObjectId, PatchSetData> result = Maps.newHashMapWithExpectedSize(in.size() * 3);
    try (Repository repo = repoManager.openRepository(project);
        RevWalk rw = new RevWalk(repo)) {
        rw.setRetainBody(true);
        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()) {
                RevCommit c = rw.parseCommit(ps.commitId());
                PatchSetData psd = PatchSetData.create(cd, ps, c);
                result.put(ps.commitId(), psd);
            }
        }
    }
    return result;
}
Also used : Project(com.google.gerrit.entities.Project) Repository(org.eclipse.jgit.lib.Repository) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.entities.PatchSet) RevWalk(org.eclipse.jgit.revwalk.RevWalk) ChangeData(com.google.gerrit.server.query.change.ChangeData) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 100 with ChangeData

use of com.google.gerrit.server.query.change.ChangeData in project gerrit by GerritCodeReview.

the class WalkSorter method byCommit.

private ListMultimap<RevCommit, PatchSetData> byCommit(RevWalk rw, Collection<ChangeData> in) throws IOException {
    ListMultimap<RevCommit, PatchSetData> byCommit = MultimapBuilder.hashKeys(in.size()).arrayListValues(1).build();
    for (ChangeData cd : in) {
        PatchSet maxPs = null;
        for (PatchSet ps : cd.patchSets()) {
            if (shouldInclude(ps) && (maxPs == null || ps.id().get() > maxPs.id().get())) {
                maxPs = ps;
            }
        }
        if (maxPs == null) {
            // No patch sets matched.
            continue;
        }
        try {
            RevCommit c = rw.parseCommit(maxPs.commitId());
            byCommit.put(c, PatchSetData.create(cd, maxPs, c));
        } catch (MissingObjectException | IncorrectObjectTypeException e) {
            logger.atWarning().withCause(e).log("missing commit %s for patch set %s", maxPs.commitId().name(), maxPs.id());
        }
    }
    return byCommit;
}
Also used : PatchSet(com.google.gerrit.entities.PatchSet) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) ChangeData(com.google.gerrit.server.query.change.ChangeData) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Aggregations

ChangeData (com.google.gerrit.server.query.change.ChangeData)208 Test (org.junit.Test)75 Change (com.google.gerrit.entities.Change)58 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)57 RevCommit (org.eclipse.jgit.revwalk.RevCommit)53 ObjectId (org.eclipse.jgit.lib.ObjectId)45 ArrayList (java.util.ArrayList)41 IOException (java.io.IOException)33 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)27 PatchSet (com.google.gerrit.entities.PatchSet)26 StorageException (com.google.gerrit.exceptions.StorageException)25 Inject (com.google.inject.Inject)25 HashMap (java.util.HashMap)25 Map (java.util.Map)24 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)23 List (java.util.List)23 Project (com.google.gerrit.entities.Project)21 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)21 OrmException (com.google.gwtorm.server.OrmException)20 Repository (org.eclipse.jgit.lib.Repository)20