Search in sources :

Example 46 with HumanComment

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

the class DeleteCommentRewriter method getPutInComments.

/**
 * Gets the comments put in by the current commit. The message of the target comment will be
 * replaced by the new message.
 *
 * @param parMap the comment map of the parent commit.
 * @param curMap the comment map of the current commit.
 * @return The comments put in by the current commit.
 */
private List<HumanComment> getPutInComments(Map<String, HumanComment> parMap, Map<String, HumanComment> curMap) {
    List<HumanComment> comments = new ArrayList<>();
    for (String key : curMap.keySet()) {
        if (!parMap.containsKey(key)) {
            HumanComment comment = curMap.get(key);
            if (key.equals(uuid)) {
                comment.message = newMessage;
                comment.unresolved = false;
            }
            comments.add(comment);
        }
    }
    return comments;
}
Also used : ArrayList(java.util.ArrayList) HumanComment(com.google.gerrit.entities.HumanComment)

Example 47 with HumanComment

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

the class DraftCommentNotes method onLoad.

@Override
protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
    ObjectId rev = handle.id();
    if (rev == null) {
        loadDefaults();
        return;
    }
    logger.atFine().log("Load draft comment notes for change %s of project %s", getChangeId(), getProjectName());
    RevCommit tipCommit = handle.walk().parseCommit(rev);
    ObjectReader reader = handle.walk().getObjectReader();
    revisionNoteMap = RevisionNoteMap.parse(args.changeNoteJson, reader, NoteMap.read(reader, tipCommit), HumanComment.Status.DRAFT);
    ImmutableListMultimap.Builder<ObjectId, HumanComment> cs = ImmutableListMultimap.builder();
    for (ChangeRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
        for (HumanComment c : rn.getEntities()) {
            cs.put(c.getCommitId(), c);
        }
    }
    comments = cs.build();
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) ObjectReader(org.eclipse.jgit.lib.ObjectReader) HumanComment(com.google.gerrit.entities.HumanComment) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 48 with HumanComment

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

the class ChangeNotesParser method parseNotes.

private void parseNotes() throws IOException, ConfigInvalidException {
    ObjectReader reader = walk.getObjectReader();
    ChangeNotesCommit tipCommit = walk.parseCommit(tip);
    revisionNoteMap = RevisionNoteMap.parse(changeNoteJson, reader, NoteMap.read(reader, tipCommit), HumanComment.Status.PUBLISHED);
    Map<ObjectId, ChangeRevisionNote> rns = revisionNoteMap.revisionNotes;
    for (Map.Entry<ObjectId, ChangeRevisionNote> e : rns.entrySet()) {
        for (HumanComment c : e.getValue().getEntities()) {
            humanComments.put(e.getKey(), c);
        }
    }
    // PS of them.
    for (PatchSet.Builder ps : patchSets.values().stream().sorted(comparingInt((PatchSet.Builder p) -> p.id().get()).reversed()).collect(Collectors.toList())) {
        Optional<ObjectId> maybePsCommitId = ps.commitId();
        if (!maybePsCommitId.isPresent()) {
            continue;
        }
        ObjectId psCommitId = maybePsCommitId.get();
        if (rns.containsKey(psCommitId) && rns.get(psCommitId).getSubmitRequirementsResult() != null) {
            rns.get(psCommitId).getSubmitRequirementsResult().forEach(sr -> submitRequirementResults.add(sr));
            break;
        }
    }
    for (PatchSet.Builder b : patchSets.values()) {
        ObjectId commitId = b.commitId().orElseThrow(() -> new IllegalStateException("never parsed commit ID for patch set " + b.id()));
        ChangeRevisionNote rn = rns.get(commitId);
        if (rn != null && rn.getPushCert() != null) {
            b.pushCertificate(Optional.of(rn.getPushCert()));
        }
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ObjectReader(org.eclipse.jgit.lib.ObjectReader) PatchSet(com.google.gerrit.entities.PatchSet) Map(java.util.Map) NoteMap(org.eclipse.jgit.notes.NoteMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HumanComment(com.google.gerrit.entities.HumanComment)

Example 49 with HumanComment

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

the class ChangeDraftUpdate method storeCommentsInNotes.

private CommitBuilder storeCommentsInNotes(RevWalk rw, ObjectInserter ins, ObjectId curr, CommitBuilder cb) throws ConfigInvalidException, IOException {
    RevisionNoteMap<ChangeRevisionNote> rnm = getRevisionNoteMap(rw, curr);
    RevisionNoteBuilder.Cache cache = new RevisionNoteBuilder.Cache(rnm);
    for (HumanComment c : put) {
        if (!delete.keySet().contains(key(c))) {
            cache.get(c.getCommitId()).putComment(c);
        }
    }
    for (Key k : delete.keySet()) {
        cache.get(k.commitId()).deleteComment(k.key());
    }
    // keyed by commit ID.
    Map<ObjectId, RevisionNoteBuilder> builders = cache.getBuilders();
    boolean touchedAnyRevs = false;
    for (Map.Entry<ObjectId, RevisionNoteBuilder> e : builders.entrySet()) {
        ObjectId id = e.getKey();
        byte[] data = e.getValue().build(noteUtil.getChangeNoteJson());
        if (!Arrays.equals(data, e.getValue().baseRaw)) {
            touchedAnyRevs = true;
        }
        if (data.length == 0) {
            rnm.noteMap.remove(id);
        } else {
            ObjectId dataBlob = ins.insert(OBJ_BLOB, data);
            rnm.noteMap.set(id, dataBlob);
        }
    }
    // data yet.
    if (!touchedAnyRevs) {
        return NO_OP_UPDATE;
    }
    // caller to delete the entire ref.
    if (!rnm.noteMap.iterator().hasNext()) {
        return null;
    }
    ObjectId treeId = rnm.noteMap.writeTree(ins);
    cb.setTreeId(treeId);
    return cb;
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) HumanComment(com.google.gerrit.entities.HumanComment) HashMap(java.util.HashMap) Map(java.util.Map) NoteMap(org.eclipse.jgit.notes.NoteMap)

Example 50 with HumanComment

use of com.google.gerrit.entities.HumanComment 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)

Aggregations

HumanComment (com.google.gerrit.entities.HumanComment)87 Test (org.junit.Test)53 Change (com.google.gerrit.entities.Change)39 PatchSet (com.google.gerrit.entities.PatchSet)39 ObjectId (org.eclipse.jgit.lib.ObjectId)39 CommentRange (com.google.gerrit.entities.CommentRange)25 Instant (java.time.Instant)20 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)14 Comment (com.google.gerrit.entities.Comment)11 Project (com.google.gerrit.entities.Project)11 Map (java.util.Map)11 ArrayList (java.util.ArrayList)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 HashMap (java.util.HashMap)7 NoteMap (org.eclipse.jgit.notes.NoteMap)7 ImmutableMap (com.google.common.collect.ImmutableMap)6 TraceTimer (com.google.gerrit.server.logging.TraceContext.TraceTimer)6 FluentLogger (com.google.common.flogger.FluentLogger)5 Account (com.google.gerrit.entities.Account)5 BranchNameKey (com.google.gerrit.entities.BranchNameKey)5