Search in sources :

Example 16 with FileDiffOutput

use of com.google.gerrit.server.patch.filediff.FileDiffOutput in project gerrit by GerritCodeReview.

the class PRED_files_1 method exec.

@Override
public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();
    Term listHead = Prolog.Nil;
    try (RevWalk revWalk = new RevWalk(StoredValues.REPOSITORY.get(engine))) {
        RevCommit commit = revWalk.parseCommit(StoredValues.getPatchSet(engine).commitId());
        Collection<FileDiffOutput> modifiedFiles = StoredValues.DIFF_LIST.get(engine).values();
        Set<String> submodules = getAllSubmodulePaths(StoredValues.REPOSITORY.get(engine), commit, modifiedFiles);
        for (FileDiffOutput fileDiff : modifiedFiles) {
            if (fileDiff.newPath().isPresent() && Patch.isMagic(fileDiff.newPath().get())) {
                continue;
            }
            String newPath = FilePathAdapter.getNewPath(fileDiff.oldPath(), fileDiff.newPath(), fileDiff.changeType());
            SymbolTerm fileNameTerm = SymbolTerm.create(newPath);
            SymbolTerm changeType = SymbolTerm.create(fileDiff.changeType().getCode());
            SymbolTerm fileType;
            if (submodules.contains(newPath)) {
                fileType = SymbolTerm.create("SUBMODULE");
            } else {
                fileType = SymbolTerm.create("REGULAR");
            }
            listHead = new ListTerm(new StructureTerm(file, fileNameTerm, changeType, fileType), listHead);
        }
    } catch (IOException ex) {
        return engine.fail();
    }
    if (!a1.unify(listHead, engine.trail)) {
        return engine.fail();
    }
    return cont;
}
Also used : ListTerm(com.googlecode.prolog_cafe.lang.ListTerm) StructureTerm(com.googlecode.prolog_cafe.lang.StructureTerm) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) Term(com.googlecode.prolog_cafe.lang.Term) StructureTerm(com.googlecode.prolog_cafe.lang.StructureTerm) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) ListTerm(com.googlecode.prolog_cafe.lang.ListTerm) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 17 with FileDiffOutput

use of com.google.gerrit.server.patch.filediff.FileDiffOutput in project gerrit by GerritCodeReview.

the class RevisionDiffIT method diffWithRootCommit.

@Test
public void diffWithRootCommit() throws Exception {
    projectOperations.project(project).forUpdate().add(allow(Permission.PUSH).ref("refs/*").group(adminGroupUuid()).force(true)).update();
    testRepo.reset(initialCommit);
    PushOneCommit push = pushFactory.create(admin.newIdent(), testRepo, "subject", ImmutableMap.of("f.txt", "content")).noParent();
    push.setForce(true);
    PushOneCommit.Result result = push.to("refs/heads/master");
    Map<String, FileDiffOutput> modifiedFiles = diffOperations.listModifiedFilesAgainstParent(project, result.getCommit(), /* parentNum= */
    0, DiffOptions.DEFAULTS);
    assertThat(modifiedFiles.keySet()).containsExactly("/COMMIT_MSG", "f.txt");
    assertThat(modifiedFiles.values().stream().map(FileDiffOutput::oldCommitId).collect(Collectors.toSet())).containsExactly(ObjectId.zeroId());
    assertThat(modifiedFiles.get("/COMMIT_MSG").changeType()).isEqualTo(Patch.ChangeType.ADDED);
    assertThat(modifiedFiles.get("f.txt").changeType()).isEqualTo(Patch.ChangeType.ADDED);
}
Also used : Result(com.google.gerrit.acceptance.PushOneCommit.Result) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 18 with FileDiffOutput

use of com.google.gerrit.server.patch.filediff.FileDiffOutput in project gerrit by GerritCodeReview.

the class EventFactory method addPatchSetFileNames.

public void addPatchSetFileNames(PatchSetAttribute patchSetAttribute, Change change, PatchSet patchSet) {
    try {
        Map<String, FileDiffOutput> modifiedFiles = diffOperations.listModifiedFilesAgainstParent(change.getProject(), patchSet.commitId(), /* parentNum= */
        0, DiffOptions.DEFAULTS);
        for (FileDiffOutput diff : modifiedFiles.values()) {
            if (patchSetAttribute.files == null) {
                patchSetAttribute.files = new ArrayList<>();
            }
            PatchAttribute p = new PatchAttribute();
            p.file = FilePathAdapter.getNewPath(diff.oldPath(), diff.newPath(), diff.changeType());
            p.fileOld = FilePathAdapter.getOldPath(diff.oldPath(), diff.changeType());
            p.type = diff.changeType();
            p.deletions -= diff.deletions();
            p.insertions = diff.insertions();
            patchSetAttribute.files.add(p);
        }
    } catch (DiffNotAvailableException e) {
        logger.atSevere().withCause(e).log("Cannot get patch list");
    }
}
Also used : PatchAttribute(com.google.gerrit.server.data.PatchAttribute) DiffNotAvailableException(com.google.gerrit.server.patch.DiffNotAvailableException) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput)

Example 19 with FileDiffOutput

use of com.google.gerrit.server.patch.filediff.FileDiffOutput 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)

Example 20 with FileDiffOutput

use of com.google.gerrit.server.patch.filediff.FileDiffOutput in project gerrit by GerritCodeReview.

the class FileDiffOutputSerializerTest method roundTrip.

@Test
public void roundTrip() {
    ImmutableList<TaggedEdit> edits = ImmutableList.of(TaggedEdit.create(Edit.create(1, 5, 3, 4), true), TaggedEdit.create(Edit.create(21, 30, 150, 158), false));
    FileDiffOutput fileDiff = FileDiffOutput.builder().oldCommitId(ObjectId.fromString("dd4d2a1498870ca5fe415b33f65d052d69d9eaf5")).newCommitId(ObjectId.fromString("0cfaab3f2ba76f71798da0a2651f41be8d45f842")).comparisonType(ComparisonType.againstOtherPatchSet()).oldPath(Optional.of("old_file_path.txt")).newPath(Optional.empty()).changeType(ChangeType.DELETED).patchType(Optional.of(PatchType.UNIFIED)).size(23).sizeDelta(10).headerLines(ImmutableList.of("header line 1", "header line 2")).edits(edits).negative(Optional.of(true)).build();
    byte[] serialized = FileDiffOutput.Serializer.INSTANCE.serialize(fileDiff);
    assertThat(FileDiffOutput.Serializer.INSTANCE.deserialize(serialized)).isEqualTo(fileDiff);
}
Also used : TaggedEdit(com.google.gerrit.server.patch.filediff.TaggedEdit) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Test(org.junit.Test)

Aggregations

FileDiffOutput (com.google.gerrit.server.patch.filediff.FileDiffOutput)20 IOException (java.io.IOException)10 DiffNotAvailableException (com.google.gerrit.server.patch.DiffNotAvailableException)6 Repository (org.eclipse.jgit.lib.Repository)6 ArrayList (java.util.ArrayList)5 ObjectId (org.eclipse.jgit.lib.ObjectId)5 RevWalk (org.eclipse.jgit.revwalk.RevWalk)5 Patch (com.google.gerrit.entities.Patch)4 StorageException (com.google.gerrit.exceptions.StorageException)4 Test (org.junit.Test)4 Project (com.google.gerrit.entities.Project)3 Inject (com.google.inject.Inject)3 Term (com.googlecode.prolog_cafe.lang.Term)3 List (java.util.List)3 Map (java.util.Map)3 Optional (java.util.Optional)3 Config (org.eclipse.jgit.lib.Config)3 ImmutableList (com.google.common.collect.ImmutableList)2 FluentLogger (com.google.common.flogger.FluentLogger)2 Nullable (com.google.gerrit.common.Nullable)2