Search in sources :

Example 6 with Patch

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

the class RevisionDiffIT method rebaseHunksDirectlyTouchingHunksOfPatchSetsNotModifiedBetweenThemAreIdentified.

@Test
public void rebaseHunksDirectlyTouchingHunksOfPatchSetsNotModifiedBetweenThemAreIdentified() throws Exception {
    // Add to hunks in a patch set and remove them in a further patch set to allow rebasing.
    Function<String, String> contentModification = fileContent -> fileContent.replace("Line 1\n", "Line one\n").replace("Line 3\n", "Line three\n");
    addModifiedPatchSet(changeId, FILE_NAME, contentModification);
    String previousPatchSetId = gApi.changes().id(changeId).get().currentRevision;
    Function<String, String> reverseContentModification = fileContent -> fileContent.replace("Line one\n", "Line 1\n").replace("Line three\n", "Line 3\n");
    addModifiedPatchSet(changeId, FILE_NAME, reverseContentModification);
    String newFileContent = FILE_CONTENT.replace("Line 2\n", "Line two\n");
    ObjectId commit2 = addCommit(commit1, FILE_NAME, newFileContent);
    rebaseChangeOn(changeId, commit2);
    // Add the hunks again and modify another line so that we get a diff for the file.
    // (Files with only edits due to rebase are filtered out.)
    addModifiedPatchSet(changeId, FILE_NAME, contentModification.andThen(fileContent -> fileContent.replace("Line 10\n", "Line ten\n")));
    DiffInfo diffInfo = getDiffRequest(changeId, CURRENT, FILE_NAME).withBase(previousPatchSetId).get();
    assertThat(diffInfo).content().element(0).commonLines().isNotEmpty();
    assertThat(diffInfo).content().element(1).linesOfA().containsExactly("Line 2");
    assertThat(diffInfo).content().element(1).linesOfB().containsExactly("Line two");
    assertThat(diffInfo).content().element(1).isDueToRebase();
    assertThat(diffInfo).content().element(2).commonLines().isNotEmpty();
    assertThat(diffInfo).content().element(3).linesOfA().containsExactly("Line 10");
    assertThat(diffInfo).content().element(3).linesOfB().containsExactly("Line ten");
    assertThat(diffInfo).content().element(3).isNotDueToRebase();
    assertThat(diffInfo).content().element(4).commonLines().isNotEmpty();
    Map<String, FileInfo> changedFiles = gApi.changes().id(changeId).current().files(previousPatchSetId);
    assertThat(changedFiles.get(FILE_NAME)).linesInserted().isEqualTo(1);
    assertThat(changedFiles.get(FILE_NAME)).linesDeleted().isEqualTo(1);
}
Also used : Patch(com.google.gerrit.entities.Patch) Arrays(java.util.Arrays) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) Collectors.toMap(java.util.stream.Collectors.toMap) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) Locale(java.util.Locale) Map(java.util.Map) ImageIO(javax.imageio.ImageIO) TestProjectUpdate.allow(com.google.gerrit.acceptance.testsuite.project.TestProjectUpdate.allow) FileInfoSubject.assertThat(com.google.gerrit.extensions.common.testing.FileInfoSubject.assertThat) ImmutableMap(com.google.common.collect.ImmutableMap) BufferedImage(java.awt.image.BufferedImage) Collectors(java.util.stream.Collectors) COMMIT_MSG(com.google.gerrit.entities.Patch.COMMIT_MSG) Collectors.joining(java.util.stream.Collectors.joining) Result(com.google.gerrit.acceptance.PushOneCommit.Result) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) RebaseInput(com.google.gerrit.extensions.api.changes.RebaseInput) DiffOperations(com.google.gerrit.server.patch.DiffOperations) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) GerritJUnit.assertThrows(com.google.gerrit.testing.GerritJUnit.assertThrows) Joiner(com.google.common.base.Joiner) IntStream(java.util.stream.IntStream) DiffInfo(com.google.gerrit.extensions.common.DiffInfo) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RawInputUtil(com.google.gerrit.common.RawInputUtil) MERGE_LIST(com.google.gerrit.entities.Patch.MERGE_LIST) Function(java.util.function.Function) ArrayList(java.util.ArrayList) PATCHSET_LEVEL(com.google.gerrit.entities.Patch.PATCHSET_LEVEL) EditWebLink(com.google.gerrit.extensions.webui.EditWebLink) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult) DiffInfoSubject.assertThat(com.google.gerrit.extensions.common.testing.DiffInfoSubject.assertThat) ImmutableList(com.google.common.collect.ImmutableList) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) GitUtil(com.google.gerrit.acceptance.GitUtil) FileApi(com.google.gerrit.extensions.api.changes.FileApi) FileInfo(com.google.gerrit.extensions.common.FileInfo) ExtensionRegistry(com.google.gerrit.acceptance.ExtensionRegistry) Before(org.junit.Before) TruthJUnit.assume(com.google.common.truth.TruthJUnit.assume) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) ObjectIds.abbreviateName(com.google.gerrit.git.ObjectIds.abbreviateName) Permission(com.google.gerrit.entities.Permission) IOException(java.io.IOException) Test(org.junit.Test) Truth.assertThat(com.google.common.truth.Truth.assertThat) ObjectId(org.eclipse.jgit.lib.ObjectId) ChangeType(com.google.gerrit.extensions.common.ChangeType) DiffOptions(com.google.gerrit.server.patch.DiffOptions) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) Ignore(org.junit.Ignore) ProjectOperations(com.google.gerrit.acceptance.testsuite.project.ProjectOperations) DateTimeFormatter(java.time.format.DateTimeFormatter) FileInfo(com.google.gerrit.extensions.common.FileInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) DiffInfo(com.google.gerrit.extensions.common.DiffInfo) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 7 with Patch

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

the class FixReplacementInterpreter method toCommitModification.

/**
 * Transforms the given {@code FixReplacement}s into {@code TreeModification}s.
 *
 * @param repository the affected Git repository
 * @param projectState the affected project
 * @param patchSetCommitId the patch set which should be modified
 * @param fixReplacements the replacements which should be applied
 * @return a list of {@code TreeModification}s representing the given replacements
 * @throws ResourceNotFoundException if a file to which one of the replacements refers doesn't
 *     exist
 * @throws ResourceConflictException if the replacements can't be transformed into {@code
 *     TreeModification}s
 */
public CommitModification toCommitModification(Repository repository, ProjectState projectState, ObjectId patchSetCommitId, List<FixReplacement> fixReplacements) throws BadRequestException, ResourceNotFoundException, IOException, ResourceConflictException {
    requireNonNull(fixReplacements, "Fix replacements must not be null");
    Map<String, List<FixReplacement>> fixReplacementsPerFilePath = fixReplacements.stream().collect(groupingBy(fixReplacement -> fixReplacement.path));
    CommitModification.Builder modificationBuilder = CommitModification.builder();
    for (Map.Entry<String, List<FixReplacement>> entry : fixReplacementsPerFilePath.entrySet()) {
        if (Objects.equals(entry.getKey(), Patch.COMMIT_MSG)) {
            String newCommitMessage = getNewCommitMessage(repository, patchSetCommitId, entry.getValue());
            modificationBuilder.newCommitMessage(newCommitMessage);
        } else {
            TreeModification treeModification = toTreeModification(repository, projectState, patchSetCommitId, entry.getKey(), entry.getValue());
            modificationBuilder.addTreeModification(treeModification);
        }
    }
    return modificationBuilder.build();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Patch(com.google.gerrit.entities.Patch) Inject(com.google.inject.Inject) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) RawInputUtil(com.google.gerrit.common.RawInputUtil) ChangeFileContentModification(com.google.gerrit.server.edit.tree.ChangeFileContentModification) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult) ImmutableList(com.google.common.collect.ImmutableList) FileContentUtil(com.google.gerrit.server.change.FileContentUtil) MagicFile(com.google.gerrit.server.patch.MagicFile) Objects.requireNonNull(java.util.Objects.requireNonNull) Map(java.util.Map) FixReplacement(com.google.gerrit.entities.FixReplacement) TreeModification(com.google.gerrit.server.edit.tree.TreeModification) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ProjectState(com.google.gerrit.server.project.ProjectState) IOException(java.io.IOException) ObjectId(org.eclipse.jgit.lib.ObjectId) Objects(java.util.Objects) CommitModification(com.google.gerrit.server.edit.CommitModification) List(java.util.List) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) Repository(org.eclipse.jgit.lib.Repository) Range(com.google.gerrit.entities.Comment.Range) Singleton(com.google.inject.Singleton) CommitModification(com.google.gerrit.server.edit.CommitModification) ImmutableList(com.google.common.collect.ImmutableList) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) List(java.util.List) TreeModification(com.google.gerrit.server.edit.tree.TreeModification) Map(java.util.Map)

Example 8 with Patch

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

the class SubmitWithStickyApprovalDiff method apply.

public String apply(ChangeNotes notes, CurrentUser currentUser) throws AuthException, IOException, PermissionBackendException, InvalidChangeOperationException {
    PatchSet currentPatchset = notes.getCurrentPatchSet();
    PatchSet.Id latestApprovedPatchsetId = getLatestApprovedPatchsetId(notes);
    if (latestApprovedPatchsetId.get() == currentPatchset.id().get()) {
        // If the latest approved patchset is the current patchset, no need to return anything.
        return "";
    }
    StringBuilder diff = new StringBuilder(String.format("\n\n%d is the latest approved patch-set.\n", latestApprovedPatchsetId.get()));
    Map<String, FileDiffOutput> modifiedFiles = listModifiedFiles(notes.getProjectName(), currentPatchset, notes.getPatchSets().get(latestApprovedPatchsetId));
    // To make the message a bit more concise, we skip the magic files.
    List<FileDiffOutput> modifiedFilesList = modifiedFiles.values().stream().filter(p -> !Patch.isMagic(p.newPath().orElse(""))).collect(Collectors.toList());
    if (modifiedFilesList.isEmpty()) {
        diff.append("No files were changed between the latest approved patch-set and the submitted one.\n");
        return diff.toString();
    }
    diff.append("The change was submitted with unreviewed changes in the following files:\n\n");
    TemporaryBuffer.Heap buffer = new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, DEFAULT_POST_SUBMIT_SIZE_LIMIT), DEFAULT_POST_SUBMIT_SIZE_LIMIT);
    try (Repository repository = repositoryManager.openRepository(notes.getProjectName());
        DiffFormatter formatter = new DiffFormatter(buffer)) {
        formatter.setRepository(repository);
        formatter.setDetectRenames(true);
        boolean isDiffTooLarge = false;
        List<String> formatterResult = null;
        try {
            formatter.format(modifiedFilesList.get(0).oldCommitId(), modifiedFilesList.get(0).newCommitId());
            // This returns the diff for all the files.
            formatterResult = Arrays.stream(RawParseUtils.decode(buffer.toByteArray()).split("\n")).collect(Collectors.toList());
        } catch (IOException e) {
            if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
                isDiffTooLarge = true;
            } else {
                throw e;
            }
        }
        if (formatterResult != null) {
            int addedBytes = formatterResult.stream().mapToInt(String::length).sum();
            if (!CommentCumulativeSizeValidator.isEnoughSpace(notes, addedBytes, maxCumulativeSize)) {
                isDiffTooLarge = true;
            }
        }
        for (FileDiffOutput fileDiff : modifiedFilesList) {
            diff.append(getDiffForFile(notes, currentPatchset.id(), latestApprovedPatchsetId, fileDiff, currentUser, formatterResult, isDiffTooLarge));
        }
    }
    return diff.toString();
}
Also used : Patch(com.google.gerrit.entities.Patch) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Arrays(java.util.Arrays) LabelId(com.google.gerrit.entities.LabelId) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) JGitText(org.eclipse.jgit.internal.JGitText) ArrayList(java.util.ArrayList) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) Config(org.eclipse.jgit.lib.Config) PatchScript(com.google.gerrit.common.data.PatchScript) ChangeType(com.google.gerrit.entities.Patch.ChangeType) CommentCumulativeSizeValidator(com.google.gerrit.server.git.validators.CommentCumulativeSizeValidator) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) PatchSet(com.google.gerrit.entities.PatchSet) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) CurrentUser(com.google.gerrit.server.CurrentUser) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) StorageException(com.google.gerrit.exceptions.StorageException) ProjectState(com.google.gerrit.server.project.ProjectState) RawParseUtils(org.eclipse.jgit.util.RawParseUtils) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) DiffInfoCreator(com.google.gerrit.server.diff.DiffInfoCreator) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) Repository(org.eclipse.jgit.lib.Repository) PatchSet(com.google.gerrit.entities.PatchSet) IOException(java.io.IOException) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Repository(org.eclipse.jgit.lib.Repository) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter)

Aggregations

Patch (com.google.gerrit.entities.Patch)8 Inject (com.google.inject.Inject)8 List (java.util.List)8 Map (java.util.Map)8 ImmutableList (com.google.common.collect.ImmutableList)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)7 BinaryResult (com.google.gerrit.extensions.restapi.BinaryResult)7 Arrays (java.util.Arrays)7 ImmutableMap (com.google.common.collect.ImmutableMap)6 Truth.assertThat (com.google.common.truth.Truth.assertThat)6 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)6 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)6 RawInputUtil (com.google.gerrit.common.RawInputUtil)6 COMMIT_MSG (com.google.gerrit.entities.Patch.COMMIT_MSG)6 PATCHSET_LEVEL (com.google.gerrit.entities.Patch.PATCHSET_LEVEL)6 DiffPreferencesInfo (com.google.gerrit.extensions.client.DiffPreferencesInfo)6 ChangeType (com.google.gerrit.extensions.common.ChangeType)6 DiffInfo (com.google.gerrit.extensions.common.DiffInfo)6 DiffInfoSubject.assertThat (com.google.gerrit.extensions.common.testing.DiffInfoSubject.assertThat)6 Joiner (com.google.common.base.Joiner)5