Search in sources :

Example 1 with CommentValidationFailure

use of com.google.gerrit.extensions.validators.CommentValidationFailure in project gerrit by GerritCodeReview.

the class ReceiveCommits method requestReplaceAndValidateComments.

/**
 * Update an existing change. If draft comments are to be published, these are validated and may
 * be withheld.
 *
 * @return True if the command succeeded, false if it was rejected.
 */
private boolean requestReplaceAndValidateComments(ReceiveCommand cmd, boolean checkMergedInto, Change change, RevCommit newCommit) throws IOException {
    try (TraceTimer traceTimer = newTimer("requestReplaceAndValidateComments")) {
        if (change.isClosed()) {
            reject(cmd, changeFormatter.changeClosed(ChangeReportFormatter.Input.builder().setChange(change).build()));
            return false;
        }
        ReplaceRequest req = new ReplaceRequest(change.getId(), newCommit, cmd, checkMergedInto);
        if (replaceByChange.containsKey(req.ontoChange)) {
            reject(cmd, "duplicate request");
            return false;
        }
        if (magicBranch != null && magicBranch.shouldPublishComments()) {
            List<HumanComment> drafts = commentsUtil.draftByChangeAuthor(notesFactory.createChecked(change), user.getAccountId());
            ImmutableList<CommentForValidation> draftsForValidation = drafts.stream().map(comment -> CommentForValidation.create(CommentSource.HUMAN, comment.lineNbr > 0 ? CommentType.INLINE_COMMENT : CommentType.FILE_COMMENT, comment.message, comment.message.length())).collect(toImmutableList());
            CommentValidationContext ctx = CommentValidationContext.create(change.getChangeId(), change.getProject().get(), change.getDest().branch());
            ImmutableList<CommentValidationFailure> commentValidationFailures = PublishCommentUtil.findInvalidComments(ctx, commentValidators, draftsForValidation);
            magicBranch.setWithholdComments(!commentValidationFailures.isEmpty());
            commentValidationFailures.forEach(failure -> addMessage("Comment validation failure: " + failure.getMessage(), ValidationMessage.Type.WARNING));
        }
        replaceByChange.put(req.ontoChange, req);
        return true;
    }
}
Also used : NotifyInfo(com.google.gerrit.extensions.api.changes.NotifyInfo) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) MultimapBuilder(com.google.common.collect.MultimapBuilder) ChangeReportFormatter(com.google.gerrit.server.git.ChangeReportFormatter) DeadlineChecker(com.google.gerrit.server.DeadlineChecker) ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) RevObject(org.eclipse.jgit.revwalk.RevObject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) HashtagsInput(com.google.gerrit.extensions.api.changes.HashtagsInput) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Config(org.eclipse.jgit.lib.Config) Future(java.util.concurrent.Future) FooterLine(org.eclipse.jgit.revwalk.FooterLine) Map(java.util.Map) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) Metadata(com.google.gerrit.server.logging.Metadata) MailRecipients(com.google.gerrit.server.mail.MailUtil.MailRecipients) RevSort(org.eclipse.jgit.revwalk.RevSort) Constants(org.eclipse.jgit.lib.Constants) PublishCommentsOp(com.google.gerrit.server.PublishCommentsOp) Collectors.joining(java.util.stream.Collectors.joining) RequestListener(com.google.gerrit.server.RequestListener) PersonIdent(org.eclipse.jgit.lib.PersonIdent) TagCache(com.google.gerrit.server.git.TagCache) Stream(java.util.stream.Stream) HashtagsUtil.cleanupHashtag(com.google.gerrit.server.change.HashtagsUtil.cleanupHashtag) BooleanProjectConfig(com.google.gerrit.entities.BooleanProjectConfig) Counter3(com.google.gerrit.metrics.Counter3) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) ProjectConfigEntryType(com.google.gerrit.extensions.api.projects.ProjectConfigEntryType) Counter0(com.google.gerrit.metrics.Counter0) MetricMaker(com.google.gerrit.metrics.MetricMaker) PatchSetInfo(com.google.gerrit.entities.PatchSetInfo) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) ValidationError(com.google.gerrit.server.git.ValidationError) SAME_CHANGE_ID_IN_MULTIPLE_CHANGES(com.google.gerrit.server.git.receive.ReceiveConstants.SAME_CHANGE_ID_IN_MULTIPLE_CHANGES) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) CommentsUtil(com.google.gerrit.server.CommentsUtil) RequestScopePropagator(com.google.gerrit.server.util.RequestScopePropagator) PerformanceLogger(com.google.gerrit.server.logging.PerformanceLogger) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) Lists(com.google.common.collect.Lists) SubmissionExecutor(com.google.gerrit.server.update.SubmissionExecutor) Description(com.google.gerrit.metrics.Description) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) StreamSupport(java.util.stream.StreamSupport) MagicBranch(com.google.gerrit.server.util.MagicBranch) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) ObjectIds.abbreviateName(com.google.gerrit.git.ObjectIds.abbreviateName) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ChangeEdit(com.google.gerrit.server.edit.ChangeEdit) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.entities.Project) DynamicSet(com.google.gerrit.extensions.registration.DynamicSet) NOT_ATTEMPTED(org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED) LabelVote(com.google.gerrit.server.util.LabelVote) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) CommentValidator(com.google.gerrit.extensions.validators.CommentValidator) ONLY_USERS_WITH_TOGGLE_WIP_STATE_PERM_CAN_MODIFY_WIP(com.google.gerrit.server.git.receive.ReceiveConstants.ONLY_USERS_WITH_TOGGLE_WIP_STATE_PERM_CAN_MODIFY_WIP) RequestCancelledException(com.google.gerrit.server.cancellation.RequestCancelledException) RequestId(com.google.gerrit.server.logging.RequestId) REJECTED_MISSING_OBJECT(org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_MISSING_OBJECT) CommentSizeValidator(com.google.gerrit.server.git.validators.CommentSizeValidator) RefPermission(com.google.gerrit.server.permissions.RefPermission) PUSH_OPTION_SKIP_VALIDATION(com.google.gerrit.server.git.receive.ReceiveConstants.PUSH_OPTION_SKIP_VALIDATION) URLDecoder(java.net.URLDecoder) ValidationMessage(com.google.gerrit.server.git.validators.ValidationMessage) Inject(com.google.inject.Inject) MissingObjectException(org.eclipse.jgit.errors.MissingObjectException) RepoOnlyOp(com.google.gerrit.server.update.RepoOnlyOp) PatchSetInfoFactory(com.google.gerrit.server.patch.PatchSetInfoFactory) UpdateException(com.google.gerrit.server.update.UpdateException) Assisted(com.google.inject.assistedinject.Assisted) ImmutableListMultimap.toImmutableListMultimap(com.google.common.collect.ImmutableListMultimap.toImmutableListMultimap) LabelType(com.google.gerrit.entities.LabelType) AuthException(com.google.gerrit.extensions.restapi.AuthException) AutoMerger(com.google.gerrit.server.patch.AutoMerger) PerformanceLogContext(com.google.gerrit.server.logging.PerformanceLogContext) PluginConfig(com.google.gerrit.server.config.PluginConfig) NoteMap(org.eclipse.jgit.notes.NoteMap) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) CommentCountValidator(com.google.gerrit.server.git.validators.CommentCountValidator) BiMap(com.google.common.collect.BiMap) ImmutableSet(com.google.common.collect.ImmutableSet) SortedSetMultimap(com.google.common.collect.SortedSetMultimap) Collection(java.util.Collection) OK(org.eclipse.jgit.transport.ReceiveCommand.Result.OK) PermissionDeniedException(com.google.gerrit.server.permissions.PermissionDeniedException) Collectors(java.util.stream.Collectors) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) Objects(java.util.Objects) CmdLineException(org.kohsuke.args4j.CmdLineException) SetPrivateOp(com.google.gerrit.server.change.SetPrivateOp) ChangeData(com.google.gerrit.server.query.change.ChangeData) Nullable(com.google.gerrit.common.Nullable) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) Ref(org.eclipse.jgit.lib.Ref) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Providers(com.google.inject.util.Providers) Queue(java.util.Queue) RefNames.isConfigRef(com.google.gerrit.entities.RefNames.isConfigRef) RequestStateContext(com.google.gerrit.server.cancellation.RequestStateContext) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) RepoContext(com.google.gerrit.server.update.RepoContext) MergedByPushOp(com.google.gerrit.server.git.MergedByPushOp) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) REFS_CHANGES(com.google.gerrit.entities.RefNames.REFS_CHANGES) Field(com.google.gerrit.metrics.Field) UsedAt(com.google.gerrit.common.UsedAt) Change(com.google.gerrit.entities.Change) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) SetTopicOp(com.google.gerrit.server.change.SetTopicOp) SetHashtagsOp(com.google.gerrit.server.change.SetHashtagsOp) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ProjectState(com.google.gerrit.server.project.ProjectState) Collectors.toList(java.util.stream.Collectors.toList) HashBiMap(com.google.common.collect.HashBiMap) Provider(com.google.inject.Provider) ReceivePack(org.eclipse.jgit.transport.ReceivePack) SuperprojectUpdateOnSubmission(com.google.gerrit.server.update.SuperprojectUpdateOnSubmission) Arrays(java.util.Arrays) ProjectConfig(com.google.gerrit.server.project.ProjectConfig) ListMultimap(com.google.common.collect.ListMultimap) GroupCollector(com.google.gerrit.server.git.GroupCollector) ProjectCache(com.google.gerrit.server.project.ProjectCache) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) InvalidDeadlineException(com.google.gerrit.server.InvalidDeadlineException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) RetryHelper(com.google.gerrit.server.update.RetryHelper) 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) BranchNameKey(com.google.gerrit.entities.BranchNameKey) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) ProjectPermission(com.google.gerrit.server.permissions.ProjectPermission) NEW_PATCHSET_PATTERN(com.google.gerrit.server.git.validators.CommitValidators.NEW_PATCHSET_PATTERN) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) LazyArgs.lazy(com.google.common.flogger.LazyArgs.lazy) Singleton(com.google.inject.Singleton) Iterables(com.google.common.collect.Iterables) CommentType(com.google.gerrit.extensions.validators.CommentForValidation.CommentType) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) RefOperationValidationException(com.google.gerrit.server.git.validators.RefOperationValidationException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) CancellationMetrics(com.google.gerrit.server.CancellationMetrics) SubmissionListener(com.google.gerrit.server.update.SubmissionListener) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) ChangeEditUtil(com.google.gerrit.server.edit.ChangeEditUtil) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) Extension(com.google.gerrit.extensions.registration.Extension) LinkedHashSet(java.util.LinkedHashSet) UNKNOWN(com.google.gerrit.server.git.MultiProgressMonitor.UNKNOWN) CommitValidationMessage(com.google.gerrit.server.git.validators.CommitValidationMessage) Sequences(com.google.gerrit.server.notedb.Sequences) CreateRefControl(com.google.gerrit.server.project.CreateRefControl) RevFilter(org.eclipse.jgit.revwalk.filter.RevFilter) AttentionSetUnchangedOp(com.google.gerrit.server.change.AttentionSetUnchangedOp) StorageException(com.google.gerrit.exceptions.StorageException) StringWriter(java.io.StringWriter) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) CmdLineParser(com.google.gerrit.util.cli.CmdLineParser) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) R_HEADS(org.eclipse.jgit.lib.Constants.R_HEADS) RefOperationValidators(com.google.gerrit.server.git.validators.RefOperationValidators) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) ObjectReader(org.eclipse.jgit.lib.ObjectReader) Repository(org.eclipse.jgit.lib.Repository) REJECTED_OTHER_REASON(org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_OTHER_REASON) MailUtil.getRecipientsFromFooters(com.google.gerrit.server.mail.MailUtil.getRecipientsFromFooters) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) HumanComment(com.google.gerrit.entities.HumanComment) SubmissionId(com.google.gerrit.entities.SubmissionId) RefNames.isRefsUsersSelf(com.google.gerrit.entities.RefNames.isRefsUsersSelf) LabelTypes(com.google.gerrit.entities.LabelTypes) ChangeIndexer(com.google.gerrit.server.index.change.ChangeIndexer) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) SubmitInput(com.google.gerrit.extensions.api.changes.SubmitInput) RefNames(com.google.gerrit.entities.RefNames) COMMAND_REJECTION_MESSAGE_FOOTER(com.google.gerrit.server.git.receive.ReceiveConstants.COMMAND_REJECTION_MESSAGE_FOOTER) Splitter(com.google.common.base.Splitter) ReceivePackInitializer(com.google.gerrit.server.git.ReceivePackInitializer) LinkedListMultimap(com.google.common.collect.LinkedListMultimap) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) Task(com.google.gerrit.server.git.MultiProgressMonitor.Task) ImmutableMap(com.google.common.collect.ImmutableMap) Account(com.google.gerrit.entities.Account) RequestInfo(com.google.gerrit.server.RequestInfo) ProjectConfigEntry(com.google.gerrit.server.config.ProjectConfigEntry) Option(org.kohsuke.args4j.Option) Streams(com.google.common.collect.Streams) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) BanCommit(com.google.gerrit.server.git.BanCommit) CommentSource(com.google.gerrit.extensions.validators.CommentForValidation.CommentSource) PublishCommentUtil(com.google.gerrit.server.PublishCommentUtil) MultiProgressMonitor(com.google.gerrit.server.git.MultiProgressMonitor) MergeOpRepoManager(com.google.gerrit.server.submit.MergeOpRepoManager) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) CreateGroupPermissionSyncer(com.google.gerrit.server.CreateGroupPermissionSyncer) HashMap(java.util.HashMap) ReplyAttentionSetUpdates(com.google.gerrit.server.restapi.change.ReplyAttentionSetUpdates) MergeOp(com.google.gerrit.server.submit.MergeOp) PostUpdateContext(com.google.gerrit.server.update.PostUpdateContext) Objects.requireNonNull(java.util.Objects.requireNonNull) ChangeInserter(com.google.gerrit.server.change.ChangeInserter) AccountResolver(com.google.gerrit.server.account.AccountResolver) Iterator(java.util.Iterator) Maps(com.google.common.collect.Maps) ObjectId(org.eclipse.jgit.lib.ObjectId) RecipientType(com.google.gerrit.extensions.api.changes.RecipientType) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) Collections(java.util.Collections) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) HumanComment(com.google.gerrit.entities.HumanComment)

Example 2 with CommentValidationFailure

use of com.google.gerrit.extensions.validators.CommentValidationFailure in project gerrit by GerritCodeReview.

the class CommentCumulativeSizeValidator method validateComments.

@Override
public ImmutableList<CommentValidationFailure> validateComments(CommentValidationContext ctx, ImmutableList<CommentForValidation> comments) {
    ChangeNotes notes = notesFactory.createChecked(Project.nameKey(ctx.getProject()), Change.id(ctx.getChangeId()));
    int existingCumulativeSize = Stream.concat(notes.getHumanComments().values().stream(), notes.getRobotComments().values().stream()).mapToInt(Comment::getApproximateSize).sum() + notes.getChangeMessages().stream().mapToInt(cm -> cm.getMessage().length()).sum();
    int newCumulativeSize = comments.stream().mapToInt(CommentForValidation::getApproximateSize).sum();
    ImmutableList.Builder<CommentValidationFailure> failures = ImmutableList.builder();
    if (!comments.isEmpty() && !isEnoughSpace(notes, newCumulativeSize, maxCumulativeSize)) {
        // This warning really applies to the set of all comments, but we need to pick one to attach
        // the message to.
        CommentForValidation commentForFailureMessage = Iterables.getLast(comments);
        failures.add(commentForFailureMessage.failValidation(String.format("Exceeding maximum cumulative size of comments and change messages:" + " %d (existing) + %d (new) > %d", existingCumulativeSize, newCumulativeSize, maxCumulativeSize)));
    }
    return failures.build();
}
Also used : Comment(com.google.gerrit.entities.Comment) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ImmutableList(com.google.common.collect.ImmutableList) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes)

Example 3 with CommentValidationFailure

use of com.google.gerrit.extensions.validators.CommentValidationFailure in project gerrit by GerritCodeReview.

the class MailProcessor method persistComments.

private void persistComments(BatchUpdate.Factory buf, MailMessage message, MailMetadata metadata, Account.Id sender) throws UpdateException, RestApiException {
    try (ManualRequestContext ctx = oneOffRequestContext.openAs(sender)) {
        List<ChangeData> changeDataList = queryProvider.get().enforceVisibility(true).byLegacyChangeId(Change.id(metadata.changeNumber));
        if (changeDataList.isEmpty()) {
            sendRejectionEmail(message, InboundEmailError.CHANGE_NOT_FOUND);
            return;
        }
        if (changeDataList.size() != 1) {
            logger.atSevere().log("Message %s references unique change %s," + " but there are %d matching changes in the index." + " Will delete message.", message.id(), metadata.changeNumber, changeDataList.size());
            sendRejectionEmail(message, InboundEmailError.INTERNAL_EXCEPTION);
            return;
        }
        ChangeData cd = Iterables.getOnlyElement(changeDataList);
        if (existingMessageIds(cd).contains(message.id())) {
            logger.atInfo().log("Message %s was already processed. Will delete message.", message.id());
            return;
        }
        // Get all comments; filter and sort them to get the original list of
        // comments from the outbound email.
        // TODO(hiesel) Also filter by original comment author.
        Collection<HumanComment> comments = cd.publishedComments().stream().filter(c -> (c.writtenOn.getTime() / 1000) == (metadata.timestamp.getTime() / 1000)).sorted(CommentsUtil.COMMENT_ORDER).collect(toList());
        Project.NameKey project = cd.project();
        // If URL is not defined, we won't be able to parse line comments. We still attempt to get the
        // other ones.
        String changeUrl = urlFormatter.get().getChangeViewUrl(cd.project(), cd.getId()).orElse("http://gerrit.invalid/");
        List<MailComment> parsedComments;
        if (useHtmlParser(message)) {
            parsedComments = HtmlParser.parse(message, comments, changeUrl);
        } else {
            parsedComments = TextParser.parse(message, comments, changeUrl);
        }
        if (parsedComments.isEmpty()) {
            logger.atWarning().log("Could not parse any comments from %s. Will delete message.", message.id());
            sendRejectionEmail(message, InboundEmailError.PARSING_ERROR);
            return;
        }
        ImmutableList<CommentForValidation> parsedCommentsForValidation = parsedComments.stream().map(comment -> CommentForValidation.create(CommentForValidation.CommentSource.HUMAN, MAIL_COMMENT_TYPE_TO_VALIDATION_TYPE.get(comment.getType()), comment.getMessage(), comment.getMessage().length())).collect(ImmutableList.toImmutableList());
        CommentValidationContext commentValidationCtx = CommentValidationContext.create(cd.change().getChangeId(), cd.change().getProject().get(), cd.change().getDest().branch());
        ImmutableList<CommentValidationFailure> commentValidationFailures = PublishCommentUtil.findInvalidComments(commentValidationCtx, commentValidators, parsedCommentsForValidation);
        if (!commentValidationFailures.isEmpty()) {
            sendRejectionEmail(message, InboundEmailError.COMMENT_REJECTED);
            return;
        }
        Op o = new Op(PatchSet.id(cd.getId(), metadata.patchSet), parsedComments, message.id());
        BatchUpdate batchUpdate = buf.create(project, ctx.getUser(), TimeUtil.now());
        batchUpdate.addOp(cd.getId(), o);
        batchUpdate.execute();
    }
}
Also used : DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) Inject(com.google.inject.Inject) HumanComment(com.google.gerrit.entities.HumanComment) UpdateException(com.google.gerrit.server.update.UpdateException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Map(java.util.Map) RetryHelper(com.google.gerrit.server.update.RetryHelper) UrlFormatter(com.google.gerrit.server.config.UrlFormatter) Side(com.google.gerrit.extensions.client.Side) OneOffRequestContext(com.google.gerrit.server.util.OneOffRequestContext) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) MailFilter(com.google.gerrit.server.mail.MailFilter) Set(java.util.Set) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) HtmlParser(com.google.gerrit.mail.HtmlParser) Emails(com.google.gerrit.server.account.Emails) CommentAdded(com.google.gerrit.server.extensions.events.CommentAdded) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Optional(java.util.Optional) MailMetadata(com.google.gerrit.mail.MailMetadata) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) FluentLogger(com.google.common.flogger.FluentLogger) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) Iterables(com.google.common.collect.Iterables) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) TextParser(com.google.gerrit.mail.TextParser) PublishCommentUtil(com.google.gerrit.server.PublishCommentUtil) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) CommentsUtil(com.google.gerrit.server.CommentsUtil) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) PATCHSET_LEVEL(com.google.gerrit.entities.Patch.PATCHSET_LEVEL) Strings(com.google.common.base.Strings) MessageIdGenerator(com.google.gerrit.server.mail.send.MessageIdGenerator) ImmutableList(com.google.common.collect.ImmutableList) PostUpdateContext(com.google.gerrit.server.update.PostUpdateContext) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) MailComment(com.google.gerrit.mail.MailComment) ChangeContext(com.google.gerrit.server.update.ChangeContext) Extension(com.google.gerrit.extensions.registration.Extension) InboundEmailError(com.google.gerrit.server.mail.send.InboundEmailRejectionSender.InboundEmailError) MailMessage(com.google.gerrit.mail.MailMessage) MailHeaderParser(com.google.gerrit.mail.MailHeaderParser) StorageException(com.google.gerrit.exceptions.StorageException) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ManualRequestContext(com.google.gerrit.server.util.ManualRequestContext) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) Project(com.google.gerrit.entities.Project) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) CommentValidator(com.google.gerrit.extensions.validators.CommentValidator) AccountState(com.google.gerrit.server.account.AccountState) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) EmailReviewComments(com.google.gerrit.server.change.EmailReviewComments) InboundEmailRejectionSender(com.google.gerrit.server.mail.send.InboundEmailRejectionSender) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) MailComment(com.google.gerrit.mail.MailComment) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) ChangeData(com.google.gerrit.server.query.change.ChangeData) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Project(com.google.gerrit.entities.Project) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ManualRequestContext(com.google.gerrit.server.util.ManualRequestContext) HumanComment(com.google.gerrit.entities.HumanComment)

Example 4 with CommentValidationFailure

use of com.google.gerrit.extensions.validators.CommentValidationFailure in project gerrit by GerritCodeReview.

the class CommentCountValidator method validateComments.

@Override
public ImmutableList<CommentValidationFailure> validateComments(CommentValidationContext ctx, ImmutableList<CommentForValidation> comments) {
    ImmutableList.Builder<CommentValidationFailure> failures = ImmutableList.builder();
    ChangeNotes notes = notesFactory.createChecked(Project.nameKey(ctx.getProject()), Change.id(ctx.getChangeId()));
    int numExistingCommentsAndChangeMessages = notes.getHumanComments().size() + notes.getRobotComments().size() + notes.getChangeMessages().size();
    if (!comments.isEmpty() && numExistingCommentsAndChangeMessages + comments.size() > maxComments) {
        // This warning really applies to the set of all comments, but we need to pick one to attach
        // the message to.
        CommentForValidation commentForFailureMessage = Iterables.getLast(comments);
        failures.add(commentForFailureMessage.failValidation(String.format("Exceeding maximum number of comments: %d (existing) + %d (new) > %d", numExistingCommentsAndChangeMessages, comments.size(), maxComments)));
    }
    return failures.build();
}
Also used : CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ImmutableList(com.google.common.collect.ImmutableList) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes)

Aggregations

ImmutableList (com.google.common.collect.ImmutableList)4 CommentForValidation (com.google.gerrit.extensions.validators.CommentForValidation)4 CommentValidationFailure (com.google.gerrit.extensions.validators.CommentValidationFailure)4 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)4 Strings (com.google.common.base.Strings)2 ImmutableMap (com.google.common.collect.ImmutableMap)2 Iterables (com.google.common.collect.Iterables)2 FluentLogger (com.google.common.flogger.FluentLogger)2 Account (com.google.gerrit.entities.Account)2 Change (com.google.gerrit.entities.Change)2 HumanComment (com.google.gerrit.entities.HumanComment)2 Joiner (com.google.common.base.Joiner)1 MoreObjects.firstNonNull (com.google.common.base.MoreObjects.firstNonNull)1 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 Splitter (com.google.common.base.Splitter)1 Throwables (com.google.common.base.Throwables)1 BiMap (com.google.common.collect.BiMap)1 HashBiMap (com.google.common.collect.HashBiMap)1 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)1 ImmutableListMultimap (com.google.common.collect.ImmutableListMultimap)1