use of com.google.gerrit.extensions.validators.CommentForValidation 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;
}
}
use of com.google.gerrit.extensions.validators.CommentForValidation in project gerrit by GerritCodeReview.
the class MailProcessorIT method setupFailValidation.
private void setupFailValidation(CommentForValidation.CommentType type, String failProject, int failChange) {
CommentForValidation commentForValidation = CommentForValidation.create(CommentForValidation.CommentSource.HUMAN, type, COMMENT_TEXT, COMMENT_TEXT.length());
when(mockCommentValidator.validateComments(CommentValidationContext.create(failChange, failProject, "refs/heads/master"), ImmutableList.of(commentForValidation))).thenReturn(ImmutableList.of(commentForValidation.failValidation("Oh no!")));
}
use of com.google.gerrit.extensions.validators.CommentForValidation 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();
}
use of com.google.gerrit.extensions.validators.CommentForValidation 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();
}
}
use of com.google.gerrit.extensions.validators.CommentForValidation 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();
}
Aggregations