com.github.difflib.patch.PatchFailedException Java Examples

The following examples show how to use com.github.difflib.patch.PatchFailedException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddOneLineFile() throws IOException, PatchFailedException {
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/newfile b/newfile",
          "new file mode 100644",
          "index 0000000..f742c88",
          "--- /dev/null",
          "+++ b/newfile",
          "@@ -0,0 +1 @@", // diff will produce such chunk header for one line file.
          "+hello, world");
  PatchUtil.apply(patchFile, 1, root);
  Path newFile = root.getRelative("newfile");
  ImmutableList<String> newFileContent = ImmutableList.of("hello, world");
  assertThat(PatchUtil.readFile(newFile)).containsExactlyElementsIn(newFileContent);
}
 
Example #2
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongChunkFormat3() throws IOException {
  scratch.file(
      "/root/foo.cc", "#include <stdio.h>", "", "void main(){", "  printf(\"Hello foo\");", "}");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ b/foo.cc",
          // Missing @@ -l,s +l,s @@ line
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          " }");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains("Looks like a unified diff at line 3, but no patch chunk was found.");
}
 
Example #3
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongChunkFormat2() throws IOException {
  scratch.file(
      "/root/foo.cc", "#include <stdio.h>", "", "void main(){", "  printf(\"Hello foo\");", "}");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ b/foo.cc",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected).hasMessageThat().contains("Expecting more chunk line at line 10");
}
 
Example #4
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testWrongChunkFormat1() throws IOException {
  scratch.file(
      "/root/foo.cc", "#include <stdio.h>", "", "void main(){", "  printf(\"Hello foo\");", "}");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ b/foo.cc",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          "+", // Adding this line will cause the chunk body not matching the header "@@ -2,4 +2,5
          // @@"
          " }");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains("Wrong chunk detected near line 11:  }, does not expect a context line here.");
}
 
Example #5
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testPatchOutsideOfRepository() throws IOException {
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/../other_root/foo.cc",
          "+++ b/../other_root/foo.cc",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          " }");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains(
          "Cannot patch file outside of external repository (/root), "
              + "file path = \"../other_root/foo.cc\" at line 3");
}
 
Example #6
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCannotFindFileToPatch() throws IOException {
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ /dev/null",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          " }");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains(
          "Cannot find file to patch (near line 3), old file name (foo.cc) doesn't exist, "
              + "new file name is not specified.");
}
 
Example #7
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testMissingBothOldAndNewFile() throws IOException {
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/ b/",
          "index f3008f9..ec4aaa0 100644",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          " }");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains("Wrong patch format near line 3, neither new file or old file are specified.");
}
 
Example #8
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailedToGetFileName() throws IOException {
  scratch.file(
      "/root/foo.cc", "#include <stdio.h>", "", "void main(){", "  printf(\"Hello foo\");", "}");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ b/foo.cc",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          " }");
  PatchFailedException expected =
      assertThrows(
          PatchFailedException.class,
          () -> PatchUtil.apply(patchFile, 2, root)); // strip=2 is wrong
  assertThat(expected)
      .hasMessageThat()
      .contains("Cannot determine file name with strip = 2 at line 3:\n--- a/foo.cc");
}
 
Example #9
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testChangeFilePermission() throws IOException, PatchFailedException {
  Path myFile = scratch.file("/root/test.sh", "line one");
  myFile.setReadable(true);
  myFile.setWritable(true);
  myFile.setExecutable(false);
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/test.sh b/test.sh",
          "old mode 100644",
          "new mode 100755");
  PatchUtil.apply(patchFile, 1, root);
  assertThat(PatchUtil.readFile(myFile)).containsExactly("line one");
  assertThat(myFile.isReadable()).isTrue();
  assertThat(myFile.isWritable()).isTrue();
  assertThat(myFile.isExecutable()).isTrue();
}
 
Example #10
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplyToNewFile() throws IOException, PatchFailedException {
  // If only newfile exists, we should patch the new file.
  Path newFile = scratch.file("/root/newfile", "line one");
  newFile.setReadable(true);
  newFile.setWritable(true);
  newFile.setExecutable(true);
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "--- oldfile",
          "+++ newfile",
          "@@ -1,1 +1,2 @@",
          " line one",
          "+line two");
  PatchUtil.apply(patchFile, 0, root);
  ImmutableList<String> newContent = ImmutableList.of("line one", "line two");
  assertThat(PatchUtil.readFile(newFile)).containsExactlyElementsIn(newContent);
  // Make sure file permission is preserved.
  assertThat(newFile.isReadable()).isTrue();
  assertThat(newFile.isWritable()).isTrue();
  assertThat(newFile.isExecutable()).isTrue();
}
 
Example #11
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testApplyToOldFile() throws IOException, PatchFailedException {
  // If both oldfile and newfile exist, we should patch the old file.
  Path oldFile = scratch.file("/root/oldfile", "line one");
  Path newFile = scratch.file("/root/newfile", "line one");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "--- oldfile",
          "+++ newfile",
          "@@ -1,1 +1,2 @@",
          " line one",
          "+line two");
  PatchUtil.apply(patchFile, 0, root);
  ImmutableList<String> newContent = ImmutableList.of("line one", "line two");
  assertThat(PatchUtil.readFile(oldFile)).containsExactlyElementsIn(newContent);
  // new file should not change
  assertThat(PatchUtil.readFile(newFile)).containsExactly("line one");
}
 
Example #12
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteAllContentButNotFile() throws IOException, PatchFailedException {
  // If newfile is not /dev/null, we don't delete the file even it's empty after patching,
  // this is the behavior of patch command line tool.
  Path oldFile = scratch.file("/root/oldfile", "I'm an old file", "bye, world");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "--- a/oldfile",
          "+++ b/oldfile",
          "@@ -1,2 +0,0 @@",
          "-I'm an old file",
          "-bye, world");
  PatchUtil.apply(patchFile, 1, root);
  assertThat(oldFile.exists()).isTrue();
  assertThat(PatchUtil.readFile(oldFile)).isEmpty();
}
 
Example #13
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddFile() throws IOException, PatchFailedException {
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/newfile b/newfile",
          "new file mode 100544",
          "index 0000000..f742c88",
          "--- /dev/null",
          "+++ b/newfile",
          "@@ -0,0 +1,2 @@",
          "+I'm a new file",
          "+hello, world",
          "-- ",
          "2.21.0.windows.1");
  PatchUtil.apply(patchFile, 1, root);
  Path newFile = root.getRelative("newfile");
  ImmutableList<String> newFileContent = ImmutableList.of("I'm a new file", "hello, world");
  assertThat(PatchUtil.readFile(newFile)).containsExactlyElementsIn(newFileContent);
  // Make sure file permission is set as specified.
  assertThat(newFile.isReadable()).isTrue();
  assertThat(newFile.isWritable()).isFalse();
  assertThat(newFile.isExecutable()).isTrue();
}
 
Example #14
Source File: PatchUtil.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void checkFilesStatusForRenaming(
    Path oldFile, Path newFile, String oldFileStr, String newFileStr, int loc)
    throws PatchFailedException {
  // If we're doing a renaming,
  // old file should be specified and exists,
  // new file should be specified but doesn't exist yet.
  String oldFileError = "";
  String newFileError = "";
  if (oldFile == null) {
    oldFileError = ", old file name (%s) is not specified";
  } else if (!oldFile.exists()) {
    oldFileError = String.format(", old file name (%s) doesn't exist", oldFileStr);
  }
  if (newFile == null) {
    newFileError = ", new file name is not specified";
  } else if (newFile.exists()) {
    newFileError = String.format(", new file name (%s) already exists", newFileStr);
  }
  if (!oldFileError.isEmpty() || !newFileError.isEmpty()) {
    throw new PatchFailedException(
        String.format("Cannot rename file (near line %d)%s%s.", loc, oldFileError, newFileError));
  }
}
 
Example #15
Source File: PatchUtil.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void checkPatchContentIsComplete(
    List<String> patchContent, ChunkHeader header, int oldLineCount, int newLineCount, int loc)
    throws PatchFailedException {
  // If the patchContent is not empty, it should have correct format.
  if (!patchContent.isEmpty()) {
    if (header == null) {
      throw new PatchFailedException(
          String.format(
              "Looks like a unified diff at line %d, but no patch chunk was found.", loc));
    }
    Result result = header.check(oldLineCount, newLineCount);
    // result will never be Result.Error here because it would have been throw in previous
    // line already.
    if (result == Result.CONTINUE) {
      throw new PatchFailedException(
          String.format("Expecting more chunk line at line %d", loc + patchContent.size()));
    }
  }
}
 
Example #16
Source File: PatchUtil.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the file path from a patch line starting with "--- " or "+++ " Returns null if the path
 * is /dev/null, otherwise returns the extracted path if succeeded or throw an exception if
 * failed.
 */
private static String extractPath(String line, int strip, int loc) throws PatchFailedException {
  // The line could look like:
  // --- a/foo/bar.txt   2019-05-27 17:19:37.054593200 +0200
  // +++ b/foo/bar.txt   2019-05-27 17:19:37.054593200 +0200
  // If strip is 1, we want extract the file path as foo/bar.txt
  Preconditions.checkArgument(line.startsWith("+++ ") || line.startsWith("--- "));
  line = Iterables.get(Splitter.on('\t').split(line), 0);
  if (line.length() > 4) {
    String path = line.substring(4).trim();
    if (path.equals("/dev/null")) {
      return null;
    }
    path = stripPath(path, strip);
    if (!path.isEmpty()) {
      return path;
    }
  }
  throw new PatchFailedException(
      String.format(
          "Cannot determine file name with strip = %d at line %d:\n%s", strip, loc, line));
}
 
Example #17
Source File: UnifiedDiffRoundTripTest.java    From java-diff-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testDiff_Issue10() throws IOException {
    final List<String> baseLines = fileToLines(TestConstants.MOCK_FOLDER + "issue10_base.txt");
    final List<String> patchLines = fileToLines(TestConstants.MOCK_FOLDER + "issue10_patch.txt");

    UnifiedDiff unifiedDiff = UnifiedDiffReader.parseUnifiedDiff(
            new ByteArrayInputStream(patchLines.stream().collect(joining("\n")).getBytes())
    );

    final Patch<String> p = unifiedDiff.getFiles().get(0).getPatch();
    try {
        DiffUtils.patch(baseLines, p);
    } catch (PatchFailedException e) {
        fail(e.getMessage());
    }
}
 
Example #18
Source File: PatchUtil.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static PatchFailedException applyDelta(
    AbstractDelta<String> delta, List<String> result) {
  try {
    delta.applyTo(result);
    return null;
  } catch (PatchFailedException e) {
    String msg =
        String.join(
            "\n",
            "**Original Position**: " + (delta.getSource().getPosition() + 1) + "\n",
            "**Original Content**:",
            String.join("\n", delta.getSource().getLines()) + "\n",
            "**Revised Content**:",
            String.join("\n", delta.getTarget().getLines()) + "\n");
    return new PatchFailedException(e.getMessage() + "\n" + msg);
  }
}
 
Example #19
Source File: GenerateUnifiedDiffTest.java    From java-diff-utils with Apache License 2.0 6 votes vote down vote up
private void verify(List<String> origLines, List<String> revLines,
        String originalFile, String revisedFile) {
    Patch<String> patch = DiffUtils.diff(origLines, revLines);
    List<String> unifiedDiff = UnifiedDiffUtils.generateUnifiedDiff(originalFile, revisedFile,
            origLines, patch, 10);

    System.out.println(unifiedDiff.stream().collect(joining("\n")));

    Patch<String> fromUnifiedPatch = UnifiedDiffUtils.parseUnifiedDiff(unifiedDiff);
    List<String> patchedLines;
    try {
        patchedLines = fromUnifiedPatch.applyTo(origLines);
        assertEquals(revLines.size(), patchedLines.size());
        for (int i = 0; i < revLines.size(); i++) {
            String l1 = revLines.get(i);
            String l2 = patchedLines.get(i);
            if (!l1.equals(l2)) {
                fail("Line " + (i + 1) + " of the patched file did not match the revised original");
            }
        }
    } catch (PatchFailedException e) {
        fail(e.getMessage());
    }
}
 
Example #20
Source File: ApplyPatch.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws PatchFailedException, IOException {
    List<String> original = Files.readAllLines(new File(ORIGINAL).toPath());
    List<String> patched = Files.readAllLines(new File(PATCH).toPath());

    // At first, parse the unified diff file and get the patch
    Patch<String> patch = UnifiedDiffUtils.parseUnifiedDiff(patched);

    // Then apply the computed patch to the given text
    List<String> result = DiffUtils.patch(original, patch);
    System.out.println(result);
    // / Or we can call patch.applyTo(original). There is no difference.
}
 
Example #21
Source File: PatchUtil.java    From bazel with Apache License 2.0 5 votes vote down vote up
private static Path getFilePath(String path, Path outputDirectory, int loc)
    throws PatchFailedException {
  if (path == null) {
    return null;
  }
  Path filePath = outputDirectory.getRelative(path);
  if (!filePath.startsWith(outputDirectory)) {
    throw new PatchFailedException(
        String.format(
            "Cannot patch file outside of external repository (%s), file path = \"%s\" at line"
                + " %d",
            outputDirectory.getPathString(), path, loc));
  }
  return filePath;
}
 
Example #22
Source File: UnifiedDiffRoundTripTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
private void verify(List<String> origLines, List<String> revLines,
            String originalFile, String revisedFile) throws IOException {
        Patch<String> patch = DiffUtils.diff(origLines, revLines);

        StringWriter writer = new StringWriter();
        UnifiedDiffWriter.write(
                UnifiedDiff.from("header", "tail", UnifiedDiffFile.from(originalFile, revisedFile, patch)),
                name -> origLines,
                writer, 10);

        System.out.println(writer.toString());

        UnifiedDiff unifiedDiff = UnifiedDiffReader.parseUnifiedDiff(new ByteArrayInputStream(writer.toString().getBytes()));

        List<String> patchedLines;
        try {
//            if (unifiedDiff.getFiles().isEmpty()) {
//                patchedLines = new ArrayList<>(origLines);
//            } else {
//                Patch<String> fromUnifiedPatch = unifiedDiff.getFiles().get(0).getPatch();
//                patchedLines = fromUnifiedPatch.applyTo(origLines);
//            }
            patchedLines = unifiedDiff.spplyPatchTo(file -> originalFile.equals(file), origLines);
            assertEquals(revLines.size(), patchedLines.size());
            for (int i = 0; i < revLines.size(); i++) {
                String l1 = revLines.get(i);
                String l2 = patchedLines.get(i);
                if (!l1.equals(l2)) {
                    fail("Line " + (i + 1) + " of the patched file did not match the revised original");
                }
            }
        } catch (PatchFailedException e) {
            fail(e.getMessage());
        }
    }
 
Example #23
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testChunkDoesNotMatch() throws IOException {
  scratch.file(
      "/root/foo.cc", "#include <stdio.h>", "", "void main(){", "  printf(\"Hello foo\");", "}");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ b/foo.cc",
          "@@ -2,4 +2,5 @@",
          " ",
          " void main(){",
          "   printf(\"Hello bar\");", // Should be "Hello foo"
          "+  printf(\"Hello from patch\");",
          " }");
  PatchFailedException expected =
      assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains(
          "Incorrect Chunk: the chunk content doesn't match the target\n"
              + "**Original Position**: 2\n"
              + "\n"
              + "**Original Content**:\n"
              + "\n"
              + "void main(){\n"
              + "  printf(\"Hello bar\");\n"
              + "}\n"
              + "\n"
              + "**Revised Content**:\n"
              + "\n"
              + "void main(){\n"
              + "  printf(\"Hello bar\");\n"
              + "  printf(\"Hello from patch\");\n"
              + "}\n");
}
 
Example #24
Source File: GenerateUnifiedDiffTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiff_Issue10() throws IOException {
    final List<String> baseLines = fileToLines(TestConstants.MOCK_FOLDER + "issue10_base.txt");
    final List<String> patchLines = fileToLines(TestConstants.MOCK_FOLDER + "issue10_patch.txt");
    final Patch<String> p = UnifiedDiffUtils.parseUnifiedDiff(patchLines);
    try {
        DiffUtils.patch(baseLines, p);
    } catch (PatchFailedException e) {
        fail(e.getMessage());
    }
}
 
Example #25
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testCannotRenameFile() throws IOException {
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/bar.cc b/bar.cpp",
          "similarity index 61%",
          "rename from bar.cc",
          "rename to bar.cpp",
          "index e77137b..9e35ee4 100644",
          "--- a/bar.cc",
          "+++ b/bar.cpp",
          "@@ -1,3 +1,4 @@",
          " void lib(){",
          "   printf(\"Hello bar\");",
          "+  printf(\"Hello cpp\");",
          " }",
          "diff --git a/foo.cc b/foo.cpp",
          "similarity index 100%",
          "rename from foo.cc",
          "rename to foo.cpp");

  PatchFailedException expected;
  expected = assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains("Cannot rename file (near line 6), old file name (bar.cc) doesn't exist.");

  scratch.file("/root/bar.cc", "void lib(){", "  printf(\"Hello bar\");", "}");
  scratch.file("/root/foo.cc");
  scratch.file("/root/foo.cpp");

  expected = assertThrows(PatchFailedException.class, () -> PatchUtil.apply(patchFile, 1, root));
  assertThat(expected)
      .hasMessageThat()
      .contains("Cannot rename file (near line 17), new file name (foo.cpp) already exists.");
}
 
Example #26
Source File: HistogramDiffTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Test of diff method, of class HistogramDiff.
 */
@Test
public void testDiff() throws PatchFailedException {
    List<String> orgList = Arrays.asList("A", "B", "C", "A", "B", "B", "A");
    List<String> revList = Arrays.asList("C", "B", "A", "B", "A", "C");
    final Patch<String> patch = Patch.generate(orgList, revList, new HistogramDiff().computeDiff(orgList, revList, null));
    System.out.println(patch);
    assertNotNull(patch);
    assertEquals(3, patch.getDeltas().size());
    assertEquals("Patch{deltas=[[DeleteDelta, position: 0, lines: [A, B]], [DeleteDelta, position: 3, lines: [A, B]], [InsertDelta, position: 7, lines: [B, A, C]]]}", patch.toString());

    List<String> patched = patch.applyTo(orgList);
    assertEquals(revList, patched);
}
 
Example #27
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatchFileNotFound() {
  PatchFailedException expected =
      assertThrows(
          PatchFailedException.class,
          () -> PatchUtil.apply(root.getRelative("patchfile"), 1, root));
  assertThat(expected).hasMessageThat().contains("Cannot find patch file: /root/patchfile");
}
 
Example #28
Source File: HistogramDiffTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testDiffWithListener() throws PatchFailedException {
    List<String> orgList = Arrays.asList("A", "B", "C", "A", "B", "B", "A");
    List<String> revList = Arrays.asList("C", "B", "A", "B", "A", "C");
    
    List<String> logdata = new ArrayList<>();
    final Patch<String> patch = Patch.generate(orgList, revList, new HistogramDiff().computeDiff(orgList, revList, new DiffAlgorithmListener() {
        @Override
        public void diffStart() {
            logdata.add("start");
        }

        @Override
        public void diffStep(int value, int max) {
            logdata.add(value + " - " + max);
        }

        @Override
        public void diffEnd() {
            logdata.add("end");
        }
    }));
    System.out.println(patch);
    assertNotNull(patch);
    assertEquals(3, patch.getDeltas().size());
    assertEquals("Patch{deltas=[[DeleteDelta, position: 0, lines: [A, B]], [DeleteDelta, position: 3, lines: [A, B]], [InsertDelta, position: 7, lines: [B, A, C]]]}", patch.toString());

    List<String> patched = patch.applyTo(orgList);
    assertEquals(revList, patched);
    
    System.out.println(logdata);
    assertEquals(17, logdata.size());
}
 
Example #29
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleChunksWithDifferentOffset() throws IOException, PatchFailedException {
  Path foo =
      scratch.file("/root/foo", "1", "3", "4", "5", "6", "7", "8", "9", "10", "11", "13", "14");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo b/foo",
          "index c20ab12..b83bdb1 100644",
          "--- a/foo",
          "+++ b/foo",
          "@@ -3,4 +3,5 @@", // Should match with offset -2, original is "@@ -1,4 +1,5 @@"
          " 1",
          "+2",
          " 3",
          " 4",
          " 5",
          "@@ -4,5 +5,6 @@", // Should match with offset 4, original is "@@ -8,4 +9,5 @@"
          " 9",
          " 10",
          " 11",
          "+12",
          " 13",
          " 14");
  PatchUtil.apply(patchFile, 1, root);
  ImmutableList<String> newFoo =
      ImmutableList.of("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14");
  assertThat(PatchUtil.readFile(foo)).containsExactlyElementsIn(newFoo);
}
 
Example #30
Source File: PatchUtilTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMatchWithOffset() throws IOException, PatchFailedException {
  Path foo =
      scratch.file(
          "/root/foo.cc",
          "#include <stdio.h>",
          "",
          "void main(){",
          "  printf(\"Hello foo\");",
          "}");
  Path patchFile =
      scratch.file(
          "/root/patchfile",
          "diff --git a/foo.cc b/foo.cc",
          "index f3008f9..ec4aaa0 100644",
          "--- a/foo.cc",
          "+++ b/foo.cc",
          "@@ -6,4 +6,5 @@", // Should match with offset -4, original is "@@ -2,4 +2,5 @@"
          " ",
          " void main(){",
          "   printf(\"Hello foo\");",
          "+  printf(\"Hello from patch\");",
          " }");
  PatchUtil.apply(patchFile, 1, root);
  ImmutableList<String> newFoo =
      ImmutableList.of(
          "#include <stdio.h>",
          "",
          "void main(){",
          "  printf(\"Hello foo\");",
          "  printf(\"Hello from patch\");",
          "}");
  assertThat(PatchUtil.readFile(foo)).containsExactlyElementsIn(newFoo);
}