Search in sources :

Example 16 with LabelTypes

use of com.google.gerrit.entities.LabelTypes in project gerrit by GerritCodeReview.

the class PostReview method apply.

public Response<ReviewResult> apply(RevisionResource revision, ReviewInput input, Instant ts) throws RestApiException, UpdateException, IOException, PermissionBackendException, ConfigInvalidException, PatchListNotAvailableException {
    // Respect timestamp, but truncate at change created-on time.
    ts = Ordering.natural().max(ts, revision.getChange().getCreatedOn());
    if (revision.getEdit().isPresent()) {
        throw new ResourceConflictException("cannot post review on edit");
    }
    ProjectState projectState = projectCache.get(revision.getProject()).orElseThrow(illegalState(revision.getProject()));
    LabelTypes labelTypes = projectState.getLabelTypes(revision.getNotes());
    logger.atFine().log("strict label checking is %s", (strictLabels ? "enabled" : "disabled"));
    metrics.draftHandling.increment(input.drafts == null ? "N/A" : input.drafts.name());
    input.drafts = firstNonNull(input.drafts, DraftHandling.KEEP);
    logger.atFine().log("draft handling = %s", input.drafts);
    if (input.onBehalfOf != null) {
        revision = onBehalfOf(revision, labelTypes, input);
    }
    if (input.labels != null) {
        checkLabels(revision, labelTypes, input.labels);
    }
    if (input.comments != null) {
        input.comments = cleanUpComments(input.comments);
        checkComments(revision, input.comments);
    }
    if (input.draftIdsToPublish != null) {
        checkDraftIds(revision, input.draftIdsToPublish, input.drafts);
    }
    if (input.robotComments != null) {
        input.robotComments = cleanUpComments(input.robotComments);
        checkRobotComments(revision, input.robotComments);
    }
    if (input.notify == null) {
        input.notify = defaultNotify(revision.getChange(), input);
    }
    logger.atFine().log("notify handling = %s", input.notify);
    Map<String, ReviewerResult> reviewerJsonResults = null;
    List<ReviewerModification> reviewerResults = Lists.newArrayList();
    boolean hasError = false;
    boolean confirm = false;
    if (input.reviewers != null) {
        reviewerJsonResults = Maps.newHashMap();
        for (ReviewerInput reviewerInput : input.reviewers) {
            ReviewerModification result = reviewerModifier.prepare(revision.getNotes(), revision.getUser(), reviewerInput, true);
            reviewerJsonResults.put(reviewerInput.reviewer, result.result);
            if (result.result.error != null) {
                logger.atFine().log("Adding %s as reviewer failed: %s", reviewerInput.reviewer, result.result.error);
                hasError = true;
                continue;
            }
            if (result.result.confirm != null) {
                logger.atFine().log("Adding %s as reviewer requires confirmation", reviewerInput.reviewer);
                confirm = true;
                continue;
            }
            logger.atFine().log("Adding %s as reviewer was prepared", reviewerInput.reviewer);
            reviewerResults.add(result);
        }
    }
    ReviewResult output = new ReviewResult();
    output.reviewers = reviewerJsonResults;
    if (hasError || confirm) {
        output.error = ERROR_ADDING_REVIEWER;
        return Response.withStatusCode(SC_BAD_REQUEST, output);
    }
    output.labels = input.labels;
    try (BatchUpdate bu = updateFactory.create(revision.getChange().getProject(), revision.getUser(), ts)) {
        Account account = revision.getUser().asIdentifiedUser().getAccount();
        boolean ccOrReviewer = false;
        if (input.labels != null && !input.labels.isEmpty()) {
            ccOrReviewer = input.labels.values().stream().anyMatch(v -> v != 0);
            if (ccOrReviewer) {
                logger.atFine().log("calling user is cc/reviewer on the change due to voting on a label");
            }
        }
        if (!ccOrReviewer) {
            // Check if user was already CCed or reviewing prior to this review.
            ReviewerSet currentReviewers = approvalsUtil.getReviewers(revision.getChangeResource().getNotes());
            ccOrReviewer = currentReviewers.all().contains(account.id());
            if (ccOrReviewer) {
                logger.atFine().log("calling user is already cc/reviewer on the change");
            }
        }
        // Apply reviewer changes first. Revision emails should be sent to the
        // updated set of reviewers. Also keep track of whether the user added
        // themselves as a reviewer or to the CC list.
        logger.atFine().log("adding reviewer additions");
        for (ReviewerModification reviewerResult : reviewerResults) {
            // Send a single batch email below.
            reviewerResult.op.suppressEmail();
            // Send events below, if possible as batch.
            reviewerResult.op.suppressEvent();
            bu.addOp(revision.getChange().getId(), reviewerResult.op);
            if (!ccOrReviewer && reviewerResult.reviewers.contains(account)) {
                logger.atFine().log("calling user is explicitly added as reviewer or CC");
                ccOrReviewer = true;
            }
        }
        if (!ccOrReviewer) {
            // User posting this review isn't currently in the reviewer or CC list,
            // isn't being explicitly added, and isn't voting on any label.
            // Automatically CC them on this change so they receive replies.
            logger.atFine().log("CCing calling user");
            ReviewerModification selfAddition = reviewerModifier.ccCurrentUser(revision.getUser(), revision);
            selfAddition.op.suppressEmail();
            selfAddition.op.suppressEvent();
            bu.addOp(revision.getChange().getId(), selfAddition.op);
        }
        // Add WorkInProgressOp if requested.
        if ((input.ready || input.workInProgress) && didWorkInProgressChange(revision.getChange().isWorkInProgress(), input)) {
            if (input.ready && input.workInProgress) {
                output.error = ERROR_WIP_READY_MUTUALLY_EXCLUSIVE;
                return Response.withStatusCode(SC_BAD_REQUEST, output);
            }
            revision.getChangeResource().permissions().check(ChangePermission.TOGGLE_WORK_IN_PROGRESS_STATE);
            if (input.ready) {
                output.ready = true;
            }
            logger.atFine().log("setting work-in-progress to %s", input.workInProgress);
            WorkInProgressOp wipOp = workInProgressOpFactory.create(input.workInProgress, new WorkInProgressOp.Input());
            wipOp.suppressEmail();
            bu.addOp(revision.getChange().getId(), wipOp);
        }
        // Add the review op.
        logger.atFine().log("posting review");
        bu.addOp(revision.getChange().getId(), new Op(projectState, revision.getPatchSet().id(), input));
        // Notify based on ReviewInput, ignoring the notify settings from any ReviewerInputs.
        NotifyResolver.Result notify = notifyResolver.resolve(input.notify, input.notifyDetails);
        bu.setNotify(notify);
        // Adjust the attention set based on the input
        replyAttentionSetUpdates.updateAttentionSet(bu, revision.getNotes(), input, revision.getUser());
        bu.execute();
        // Re-read change to take into account results of the update.
        ChangeData cd = changeDataFactory.create(revision.getProject(), revision.getChange().getId());
        for (ReviewerModification reviewerResult : reviewerResults) {
            reviewerResult.gatherResults(cd);
        }
        // Sending emails and events from ReviewersOps was suppressed so we can send a single batch
        // email/event here.
        batchEmailReviewers(revision.getUser(), revision.getChange(), reviewerResults, notify);
        batchReviewerEvents(revision.getUser(), cd, revision.getPatchSet(), reviewerResults, ts);
    }
    return Response.ok(output);
}
Also used : ON_BEHALF_OF(com.google.gerrit.server.permissions.LabelPermission.ForUser.ON_BEHALF_OF) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) ProjectCache(com.google.gerrit.server.project.ProjectCache) Comment(com.google.gerrit.entities.Comment) FixSuggestion(com.google.gerrit.entities.FixSuggestion) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerSet(com.google.gerrit.server.ReviewerSet) DiffSummaryKey(com.google.gerrit.server.patch.DiffSummaryKey) Config(org.eclipse.jgit.lib.Config) Map(java.util.Map) FixReplacement(com.google.gerrit.entities.FixReplacement) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) Metadata(com.google.gerrit.server.logging.Metadata) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) TraceContext(com.google.gerrit.server.logging.TraceContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) Stream(java.util.stream.Stream) CommentAdded(com.google.gerrit.server.extensions.events.CommentAdded) AutoValue(com.google.auto.value.AutoValue) DiffSummary(com.google.gerrit.server.patch.DiffSummary) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) Counter1(com.google.gerrit.metrics.Counter1) MetricMaker(com.google.gerrit.metrics.MetricMaker) PatchListKey(com.google.gerrit.server.patch.PatchListKey) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) CommentsUtil(com.google.gerrit.server.CommentsUtil) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) Response(com.google.gerrit.extensions.restapi.Response) ArrayList(java.util.ArrayList) PATCHSET_LEVEL(com.google.gerrit.entities.Patch.PATCHSET_LEVEL) Strings(com.google.common.base.Strings) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput) Lists(com.google.common.collect.Lists) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) Description(com.google.gerrit.metrics.Description) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) Address(com.google.gerrit.entities.Address) REVIEWER(com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) HashCode(com.google.common.hash.HashCode) Result(com.google.gerrit.server.change.ReviewerOp.Result) PatchListCache(com.google.gerrit.server.patch.PatchListCache) StorageException(com.google.gerrit.exceptions.StorageException) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) RobotCommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.RobotCommentInput) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) LabelVote(com.google.gerrit.server.util.LabelVote) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) CommentValidator(com.google.gerrit.extensions.validators.CommentValidator) AccountState(com.google.gerrit.server.account.AccountState) Patch(com.google.gerrit.entities.Patch) Inject(com.google.inject.Inject) HumanComment(com.google.gerrit.entities.HumanComment) UpdateException(com.google.gerrit.server.update.UpdateException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LabelTypes(com.google.gerrit.entities.LabelTypes) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) LabelType(com.google.gerrit.entities.LabelType) AuthException(com.google.gerrit.extensions.restapi.AuthException) ReviewerModifier(com.google.gerrit.server.change.ReviewerModifier) Collectors.toSet(java.util.stream.Collectors.toSet) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) Objects(java.util.Objects) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) FixSuggestionInfo(com.google.gerrit.extensions.common.FixSuggestionInfo) Url(com.google.gerrit.extensions.restapi.Url) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) LabelPermission(com.google.gerrit.server.permissions.LabelPermission) PatchListNotAvailableException(com.google.gerrit.server.patch.PatchListNotAvailableException) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) PublishCommentUtil(com.google.gerrit.server.PublishCommentUtil) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) Hashing(com.google.common.hash.Hashing) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) HashSet(java.util.HashSet) CommentsRejectedException(com.google.gerrit.server.update.CommentsRejectedException) ImmutableList(com.google.common.collect.ImmutableList) ChangeResource(com.google.gerrit.server.change.ChangeResource) PostUpdateContext(com.google.gerrit.server.update.PostUpdateContext) CommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput) Range(com.google.gerrit.extensions.client.Comment.Range) RobotComment(com.google.gerrit.entities.RobotComment) Field(com.google.gerrit.metrics.Field) Change(com.google.gerrit.entities.Change) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) ModifyReviewersEmail(com.google.gerrit.server.change.ModifyReviewersEmail) FixReplacementInfo(com.google.gerrit.extensions.common.FixReplacementInfo) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResolver(com.google.gerrit.server.account.AccountResolver) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ReviewerAdded(com.google.gerrit.server.extensions.events.ReviewerAdded) ProjectState(com.google.gerrit.server.project.ProjectState) Maps(com.google.common.collect.Maps) ObjectId(org.eclipse.jgit.lib.ObjectId) Collectors.toList(java.util.stream.Collectors.toList) Ordering(com.google.common.collect.Ordering) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) RevisionResource(com.google.gerrit.server.change.RevisionResource) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) EmailReviewComments(com.google.gerrit.server.change.EmailReviewComments) Collections(java.util.Collections) Account(com.google.gerrit.entities.Account) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) LabelTypes(com.google.gerrit.entities.LabelTypes) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) ChangeData(com.google.gerrit.server.query.change.ChangeData) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ReviewerSet(com.google.gerrit.server.ReviewerSet) ProjectState(com.google.gerrit.server.project.ProjectState) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput)

Aggregations

LabelTypes (com.google.gerrit.entities.LabelTypes)16 LabelType (com.google.gerrit.entities.LabelType)11 PatchSetApproval (com.google.gerrit.entities.PatchSetApproval)8 Map (java.util.Map)6 Account (com.google.gerrit.entities.Account)5 PatchSet (com.google.gerrit.entities.PatchSet)5 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)5 ChangeData (com.google.gerrit.server.query.change.ChangeData)5 HashMap (java.util.HashMap)5 LabelPermission (com.google.gerrit.server.permissions.LabelPermission)4 HashSet (java.util.HashSet)4 LinkedHashMap (java.util.LinkedHashMap)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 Lists (com.google.common.collect.Lists)3 Maps (com.google.common.collect.Maps)3 FluentLogger (com.google.common.flogger.FluentLogger)3 Nullable (com.google.gerrit.common.Nullable)3 Change (com.google.gerrit.entities.Change)3 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)3 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)3