Search in sources :

Example 6 with FixReplacement

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

the class FixReplacementInterpreter method shiftRangesBy.

private static FixReplacement shiftRangesBy(FixReplacement fixReplacement, int shiftedAmount) {
    Range adjustedRange = new Range(fixReplacement.range);
    adjustedRange.startLine += shiftedAmount;
    adjustedRange.endLine += shiftedAmount;
    return new FixReplacement(fixReplacement.path, adjustedRange, fixReplacement.replacement);
}
Also used : Range(com.google.gerrit.entities.Comment.Range) FixReplacement(com.google.gerrit.entities.FixReplacement)

Example 7 with FixReplacement

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

the class FixReplacementInterpreter method getNewCommitMessage.

private static String getNewCommitMessage(Repository repository, ObjectId patchSetCommitId, List<FixReplacement> fixReplacements) throws ResourceConflictException, IOException {
    try (ObjectReader reader = repository.newObjectReader()) {
        // In the magic /COMMIT_MSG file, the actual commit message is placed after some generated
        // header lines. -> Need to find out to which actual line of the commit message a replacement
        // refers.
        MagicFile commitMessageFile = MagicFile.forCommitMessage(reader, patchSetCommitId);
        int commitMessageStartLine = commitMessageFile.getStartLineOfModifiableContent();
        // Line numbers are 1-based. -> Add 1 to not move first line.
        // Move up for any additionally found lines.
        int necessaryRangeShift = -commitMessageStartLine + 1;
        ImmutableList<FixReplacement> adjustedReplacements = shiftRangesBy(fixReplacements, necessaryRangeShift);
        if (referToNonPositiveLine(adjustedReplacements)) {
            throw new ResourceConflictException(String.format("The header of the %s file cannot be modified.", Patch.COMMIT_MSG));
        }
        String commitMessage = commitMessageFile.modifiableContent();
        return FixCalculator.getNewFileContent(commitMessage, adjustedReplacements);
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MagicFile(com.google.gerrit.server.patch.MagicFile) ObjectReader(org.eclipse.jgit.lib.ObjectReader) FixReplacement(com.google.gerrit.entities.FixReplacement)

Example 8 with FixReplacement

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

the class PostReview method ensureFixReplacementsAreAddable.

private static void ensureFixReplacementsAreAddable(String commentPath, List<FixReplacementInfo> fixReplacementInfos) throws BadRequestException {
    ensureReplacementsArePresent(commentPath, fixReplacementInfos);
    for (FixReplacementInfo fixReplacementInfo : fixReplacementInfos) {
        ensureReplacementPathIsSetAndNotPatchsetLevel(commentPath, fixReplacementInfo.path);
        ensureRangeIsSet(commentPath, fixReplacementInfo.range);
        ensureRangeIsValid(commentPath, fixReplacementInfo.range);
        ensureReplacementStringIsSet(commentPath, fixReplacementInfo.replacement);
    }
    Map<String, List<FixReplacementInfo>> replacementsPerFilePath = fixReplacementInfos.stream().collect(groupingBy(fixReplacement -> fixReplacement.path));
    for (List<FixReplacementInfo> sameFileReplacements : replacementsPerFilePath.values()) {
        ensureRangesDoNotOverlap(commentPath, sameFileReplacements);
    }
}
Also used : FixReplacementInfo(com.google.gerrit.extensions.common.FixReplacementInfo) 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) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ArrayList(java.util.ArrayList) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Collectors.toList(java.util.stream.Collectors.toList)

Example 9 with FixReplacement

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

the class GetFixPreview method apply.

@Override
public Response<Map<String, DiffInfo>> apply(FixResource resource) throws PermissionBackendException, ResourceNotFoundException, ResourceConflictException, AuthException, IOException, InvalidChangeOperationException {
    Map<String, DiffInfo> result = new HashMap<>();
    PatchSet patchSet = resource.getRevisionResource().getPatchSet();
    ChangeNotes notes = resource.getRevisionResource().getNotes();
    Change change = notes.getChange();
    ProjectState state = projectCache.get(change.getProject()).orElseThrow(illegalState(change.getProject()));
    Map<String, List<FixReplacement>> fixReplacementsPerFilePath = resource.getFixReplacements().stream().collect(groupingBy(fixReplacement -> fixReplacement.path));
    try {
        try (Repository git = repoManager.openRepository(notes.getProjectName())) {
            for (Map.Entry<String, List<FixReplacement>> entry : fixReplacementsPerFilePath.entrySet()) {
                String fileName = entry.getKey();
                DiffInfo diffInfo = getFixPreviewForSingleFile(git, patchSet, state, notes, fileName, ImmutableList.copyOf(entry.getValue()));
                result.put(fileName, diffInfo);
            }
        }
    } catch (NoSuchChangeException e) {
        throw new ResourceNotFoundException(e.getMessage(), e);
    } catch (LargeObjectException e) {
        throw new ResourceConflictException(e.getMessage(), e);
    }
    return Response.ok(result);
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) DiffInfo(com.google.gerrit.extensions.common.DiffInfo) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) HashMap(java.util.HashMap) Response(com.google.gerrit.extensions.restapi.Response) PatchScriptFactoryForAutoFix(com.google.gerrit.server.patch.PatchScriptFactoryForAutoFix) PatchScript(com.google.gerrit.common.data.PatchScript) ImmutableList(com.google.common.collect.ImmutableList) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) FixReplacement(com.google.gerrit.entities.FixReplacement) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) RestReadView(com.google.gerrit.extensions.restapi.RestReadView) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) ProjectState(com.google.gerrit.server.project.ProjectState) MoreObjects(com.google.common.base.MoreObjects) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) DiffSide(com.google.gerrit.server.diff.DiffSide) DiffWebLinksProvider(com.google.gerrit.server.diff.DiffWebLinksProvider) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) List(java.util.List) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) DiffWebLinkInfo(com.google.gerrit.extensions.common.DiffWebLinkInfo) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) DiffInfoCreator(com.google.gerrit.server.diff.DiffInfoCreator) FixResource(com.google.gerrit.server.change.FixResource) Repository(org.eclipse.jgit.lib.Repository) Singleton(com.google.inject.Singleton) HashMap(java.util.HashMap) PatchSet(com.google.gerrit.entities.PatchSet) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) Change(com.google.gerrit.entities.Change) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) ProjectState(com.google.gerrit.server.project.ProjectState) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) HashMap(java.util.HashMap) Map(java.util.Map) DiffInfo(com.google.gerrit.extensions.common.DiffInfo)

Example 10 with FixReplacement

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

the class FixReplacementInterpreterTest method replacementsCanModifySeveralFilesInAnyOrder.

@Test
public void replacementsCanModifySeveralFilesInAnyOrder() throws Exception {
    FixReplacement fixReplacement1 = new FixReplacement(filePath1, new Range(1, 1, 3, 2), "Modified content");
    mockFileContent(filePath1, "First line\nSecond line\nThird line\n");
    FixReplacement fixReplacement2 = new FixReplacement(filePath2, new Range(2, 0, 3, 0), "First modification\n");
    FixReplacement fixReplacement3 = new FixReplacement(filePath2, new Range(3, 0, 4, 0), "Second modification\n");
    mockFileContent(filePath2, "1st line\n2nd line\n3rd line\n");
    CommitModification commitModification = toCommitModification(fixReplacement3, fixReplacement1, fixReplacement2);
    List<TreeModification> sortedTreeModifications = getSortedCopy(commitModification.treeModifications());
    assertThatList(sortedTreeModifications).element(0).asChangeFileContentModification().newContent().isEqualTo("FModified contentird line\n");
    assertThatList(sortedTreeModifications).element(1).asChangeFileContentModification().newContent().isEqualTo("1st line\nFirst modification\nSecond modification\n");
}
Also used : CommitModification(com.google.gerrit.server.edit.CommitModification) TreeModification(com.google.gerrit.server.edit.tree.TreeModification) FixReplacement(com.google.gerrit.entities.FixReplacement) Range(com.google.gerrit.entities.Comment.Range) Test(org.junit.Test)

Aggregations

FixReplacement (com.google.gerrit.entities.FixReplacement)14 Range (com.google.gerrit.entities.Comment.Range)10 Test (org.junit.Test)8 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)5 FixResult (com.google.gerrit.server.fixes.FixCalculator.FixResult)5 CommitModification (com.google.gerrit.server.edit.CommitModification)4 TreeModification (com.google.gerrit.server.edit.tree.TreeModification)4 Edit (org.eclipse.jgit.diff.Edit)4 ImmutableList (com.google.common.collect.ImmutableList)3 ProjectState (com.google.gerrit.server.project.ProjectState)3 Inject (com.google.inject.Inject)3 Singleton (com.google.inject.Singleton)3 IOException (java.io.IOException)3 List (java.util.List)3 Map (java.util.Map)3 Collectors.groupingBy (java.util.stream.Collectors.groupingBy)3 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 Change (com.google.gerrit.entities.Change)2 Patch (com.google.gerrit.entities.Patch)2 PatchSet (com.google.gerrit.entities.PatchSet)2