com.github.difflib.DiffUtils Java Examples

The following examples show how to use com.github.difflib.DiffUtils. 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: Client.java    From batfish with Apache License 2.0 6 votes vote down vote up
/**
 * Computes a unified diff of the input strings, returning the empty string if the {@code
 * expected} and {@code actual} are equal.
 */
@Nonnull
@VisibleForTesting
static String getPatch(
    String expected, String actual, String expectedFileName, String actualFileName)
    throws DiffException {
  List<String> referenceLines = Arrays.asList(expected.split("\n"));
  List<String> testLines = Arrays.asList(actual.split("\n"));
  Patch<String> patch = DiffUtils.diff(referenceLines, testLines);
  if (patch.getDeltas().isEmpty()) {
    return "";
  } else {
    List<String> patchLines =
        UnifiedDiffUtils.generateUnifiedDiff(
            expectedFileName, actualFileName, referenceLines, patch, 3);
    return StringUtils.join(patchLines, "\n");
  }
}
 
Example #2
Source File: IncludePreprocessorTest.java    From helidon-build-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitialProcessing() throws IOException, DiffException, URISyntaxException {
    String testFileDir = "preprocess-adoc";
    Path originalPath = Paths.get(testFileDir, "variousIncludes.adoc");
    List<String> originalLines = loadFromPath(originalPath);

    Path afterInitialPreprocessingPath = Paths.get(testFileDir,
            "variousIncludes-afterInitialPreprocessing.adoc");
    List<String> expectedAfterInitialPreprocessingLines =
            loadFromPath(afterInitialPreprocessingPath);

    List<String> actualAfterInitialPreprocessingLines =
            IncludePreprocessor.convertHybridToBracketed(originalLines);

    assertEquals(expectedAfterInitialPreprocessingLines,
            actualAfterInitialPreprocessingLines,
            DiffUtils.diff(expectedAfterInitialPreprocessingLines,
                    actualAfterInitialPreprocessingLines).toString());
}
 
Example #3
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 #4
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 #5
Source File: TextDiffSubject.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static String generateUnifiedDiff(
    ImmutableList<String> expectedContent, ImmutableList<String> actualContent) {
  Patch<String> diff;
  try {
    diff = DiffUtils.diff(expectedContent, actualContent);
  } catch (DiffException e) {
    throw new RuntimeException(e);
  }
  List<String> unifiedDiff =
      UnifiedDiffUtils.generateUnifiedDiff("expected", "actual", expectedContent, diff, 0);

  return Joiner.on('\n').join(unifiedDiff);
}
 
Example #6
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 #7
Source File: UnifiedDiffRoundTripTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Issue 19
 */
@Test
public void testDiffWithHeaderLineInText() throws IOException {
    List<String> original = new ArrayList<>();
    List<String> revised = new ArrayList<>();

    original.add("test line1");
    original.add("test line2");
    original.add("test line 4");
    original.add("test line 5");

    revised.add("test line1");
    revised.add("test line2");
    revised.add("@@ -2,6 +2,7 @@");
    revised.add("test line 4");
    revised.add("test line 5");

    Patch<String> patch = DiffUtils.diff(original, revised);
    StringWriter writer = new StringWriter();
    UnifiedDiffWriter.write(
            UnifiedDiff.from("header", "tail", UnifiedDiffFile.from("original", "revised", patch)),
            name -> original,
            writer, 10);

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

    UnifiedDiff unifiedDiff = UnifiedDiffReader.parseUnifiedDiff(new ByteArrayInputStream(writer.toString().getBytes()));
}
 
Example #8
Source File: UnifiedDiffRoundTripTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateUnifiedDiffWithoutAnyDeltas() throws IOException {
    List<String> test = Arrays.asList("abc");
    Patch<String> patch = DiffUtils.diff(test, test);
    StringWriter writer = new StringWriter();

    UnifiedDiffWriter.write(
            UnifiedDiff.from("header", "tail", UnifiedDiffFile.from("abc", "abc", patch)),
            name -> test,
            writer, 0);

    System.out.println(writer);
}
 
Example #9
Source File: ComputeDifference.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    List<String> original = Files.readAllLines(new File(ORIGINAL).toPath());
    List<String> revised = Files.readAllLines(new File(RIVISED).toPath());

    // Compute diff. Get the Patch object. Patch is the container for computed deltas.
    Patch<String> patch = DiffUtils.diff(original, revised);

    for (AbstractDelta<String> delta : patch.getDeltas()) {
        System.out.println(delta);
    }
}
 
Example #10
Source File: PreprocessAsciiDocMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private String formatDiffs(Path pathA, Path pathB) throws IOException, DiffException {
    List<String> contentA = Files.readAllLines(pathA);
    List<String> contentB = Files.readAllLines(pathB);
    return DiffUtils.diff(contentA, contentB).getDeltas().stream()
            .map(Delta::toString)
            .collect(Collectors.joining(System.lineSeparator()));
}
 
Example #11
Source File: PatchTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatch_Change() {
    final List<String> changeTest_from = Arrays.asList("aaa", "bbb", "ccc", "ddd");
    final List<String> changeTest_to = Arrays.asList("aaa", "bxb", "cxc", "ddd");

    final Patch<String> patch = DiffUtils.diff(changeTest_from, changeTest_to);
    try {
        assertEquals(changeTest_to, DiffUtils.patch(changeTest_from, patch));
    } catch (PatchFailedException e) {
        fail(e.getMessage());
    }
}
 
Example #12
Source File: PatchTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatch_Delete() {
    final List<String> deleteTest_from = Arrays.asList("ddd", "fff", "ggg", "hhh");
    final List<String> deleteTest_to = Arrays.asList("ggg");

    final Patch<String> patch = DiffUtils.diff(deleteTest_from, deleteTest_to);
    try {
        assertEquals(deleteTest_to, DiffUtils.patch(deleteTest_from, patch));
    } catch (PatchFailedException e) {
        fail(e.getMessage());
    }
}
 
Example #13
Source File: PatchTest.java    From java-diff-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void testPatch_Insert() {
    final List<String> insertTest_from = Arrays.asList("hhh");
    final List<String> insertTest_to = Arrays.asList("hhh", "jjj", "kkk", "lll");

    final Patch<String> patch = DiffUtils.diff(insertTest_from, insertTest_to);
    try {
        assertEquals(insertTest_to, DiffUtils.patch(insertTest_from, patch));
    } catch (PatchFailedException e) {
        fail(e.getMessage());
    }
}
 
Example #14
Source File: TestHelper.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
/**
 * Render the expected template and compare it with the given actual file.
 * The actual file must exist and be identical to the rendered template,
 * otherwise assert errors will be thrown.
 *
 * @param outputdir the output directory where to render the expected template
 * @param expectedTpl the template used for comparing the actual file
 * @param actual the rendered file to be compared
 * @throws Exception if an error occurred
 */
public static void assertRendering(File outputdir, File expectedTpl, File actual)
        throws Exception {

    assertTrue(actual.exists(), actual.getAbsolutePath() + " does not exist");

    // render expected
    FileTemplateLoader ftl = new FileTemplateLoader(expectedTpl.getParentFile());
    Configuration config = new Configuration(Configuration.VERSION_2_3_23);
    config.setTemplateLoader(ftl);
    Template template = config.getTemplate(expectedTpl.getName());
    File expected = new File(outputdir, "expected_" + actual.getName());
    FileWriter writer = new FileWriter(expected);
    Map<String, Object> model = new HashMap<>();
    model.put("basedir", getBasedirPath());
    template.process(model, writer);

    // diff expected and rendered
    List<String> expectedLines = Files.readAllLines(expected.toPath());
    List<String> actualLines = Files.readAllLines(actual.toPath());

    // compare expected and rendered
    Patch<String> patch = DiffUtils.diff(expectedLines, actualLines);
    if (patch.getDeltas().size() > 0) {
        fail("rendered file " + actual.getAbsolutePath() + " differs from expected: " + patch.toString());
    }
}
 
Example #15
Source File: PreprocessAsciiDocMojoTest.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private void runMojo(
        String pomFile,
        String expectedFile,
        String goal,
        Class<? extends AbstractAsciiDocMojo> mojoClass) throws Exception {
    AbstractAsciiDocMojo mojo = MavenPluginHelper.getInstance().getMojo(
            pomFile,
            INCLUDES_TEST_ROOT.toFile(),
            goal,
            mojoClass);
    mojo.execute();

    String baseDir = mojo.project().getBasedir().toPath().toString();
    Path mojoOutputPath = Paths.get(baseDir, "../../../../target/docs",
            "variousIncludes.adoc").normalize();
    List<String> mojoOutput = Files.readAllLines(mojoOutputPath);

    Path expectedOutputPath = Paths.get(
            baseDir,
            "../preprocess-adoc",
            expectedFile);
    List<String> expectedOutput = Files.readAllLines(expectedOutputPath);

    assertEquals(expectedOutput, mojoOutput, () -> {
        try {
            return DiffUtils.diff(expectedOutput, mojoOutput).toString();
        } catch (DiffException ex) {
            throw new RuntimeException(ex);
        }
    });
}
 
Example #16
Source File: IncludePreprocessorTest.java    From helidon-build-tools with Apache License 2.0 4 votes vote down vote up
@Test
public void testSourceBlockIncludeBracketing() throws DiffException {
    List<String> orig = asList(
              "[source]\n"
            + ".Title of the source block\n"
            + "// _include::1-3:a.adoc\n"
            + "// _include::5-7:b.adoc\n"
            + "----\n"
            + "Not included\n"
            + "inc 1.1\n"
            + "inc 1.2\n"
            + "inc 1.3\n"
            + "Also not included\n"
            + "inc 2.1\n"
            + "inc 2.2\n"
            + "inc 2.3\n"
            + "Other not included\n"
            + "----"
    );

    List<String> expectedBracketed = asList(
              "[source]\n"
            + ".Title of the source block\n"
            + "----\n"
            + "Not included\n"
            + "// _include-start::a.adoc\n"
            + "include::a.adoc\n"
            + "// _include-end::a.adoc\n"
            + "Also not included\n"
            + "// _include-start::b.adoc\n"
            + "include::b.adoc\n"
            + "// _include-end::b.adoc\n"
            + "Other not included\n"
            + "----"
    );

    AtomicInteger lineNumber = new AtomicInteger(0);
    Block sba = Block.consumeBlock(orig, lineNumber);

    List<String> bracketed = sba.asBracketedBlock();
    assertEquals(expectedBracketed, bracketed,
            DiffUtils.diff(orig, bracketed).toString());
}
 
Example #17
Source File: BaseDocumentationTest.java    From connect-utils with Apache License 2.0 4 votes vote down vote up
@TestFactory
public Stream<DynamicTest> validateTransformationExamples() {
  Map<File, Plugin.Transformation> transformationExamples = examples(this.plugin.getTransformations());

  return transformationExamples.entrySet().stream()
      .map(e -> dynamicTest(String.format("%s/%s", e.getValue().getCls().getSimpleName(), e.getKey().getName()), () -> {
        final Plugin.Transformation transformation = e.getValue();
        final File rstOutputFile = outputRST(
            this.transformationsExampleDirectory,
            transformation.getCls(),
            e.getKey()
        );
        final Plugin.TransformationExample example = loadExample(e, Plugin.TransformationExample.class);

        final Class<? extends Transformation> transformationClass;

        if (Strings.isNullOrEmpty(example.getChildClass())) {
          transformationClass = transformation.getCls();
        } else {
          Optional<Class> childClass = Arrays.stream(transformation.getCls().getClasses())
              .filter(c -> example.getChildClass().equals(c.getSimpleName()))
              .findFirst();
          assertTrue(
              childClass.isPresent(),
              String.format(
                  "Could not find child '%s' of class '%s'",
                  example.getChildClass(),
                  transformation.getCls().getName()
              )
          );
          transformationClass = childClass.get();
        }

        Transformation<SinkRecord> transform = transformationClass.newInstance();
        transform.configure(example.getConfig());

        ImmutableTransformationExampleInput.Builder builder = ImmutableTransformationExampleInput.builder();
        builder.example(example);

        if (null != example.getConfig() && !example.getConfig().isEmpty()) {
          String transformKey = CaseFormat.UPPER_CAMEL.to(
              CaseFormat.LOWER_CAMEL,
              transformation.getCls().getSimpleName()
          );
          String transformPrefix = "transforms." + transformKey + ".";
          LinkedHashMap<String, String> config = new LinkedHashMap<>();
          config.put("transforms", transformKey);
          config.put(transformPrefix + "type", transformationClass.getName());

          for (Map.Entry<String, String> a : example.getConfig().entrySet()) {
            config.put(transformPrefix + a.getKey(), a.getValue());
          }

          String configJson = writeValueAsIndentedString(config);
          builder.config(configJson);
        }

        if (null != example.getInput()) {
          String inputJson = writeValueAsIndentedString(example.getInput());
          builder.inputJson(inputJson);

          SinkRecord output = transform.apply(example.getInput());
          if (null != output) {
            String outputJson = writeValueAsIndentedString(output);
            builder.outputJson(outputJson);

            final List<String> inputLines = Arrays.asList(inputJson.split("\\r?\\n"));
            final List<String> outputLines = Arrays.asList(outputJson.split("\\r?\\n"));


            Patch<String> patch = DiffUtils.diff(inputLines, outputLines);
            for (AbstractDelta<String> delta : patch.getDeltas()) {
              log.trace("delta: start={} end={}", delta.getTarget().getPosition(), delta.getTarget().last());
              final int lineStart = delta.getTarget().getPosition() + 1;
              final int lineEnd = lineStart + delta.getTarget().size() - 1;
              for (int i = lineStart; i <= lineEnd; i++) {
                builder.addOutputEmphasizeLines(i);
              }
            }
          }
        }

        try (Writer writer = Files.newWriter(rstOutputFile, Charsets.UTF_8)) {
          Template template = configuration.getTemplate("rst/transformationExample.rst.ftl");
          process(writer, template, builder.build());
        }
      }));
}
 
Example #18
Source File: DiffRowGenerator.java    From java-diff-utils with Apache License 2.0 2 votes vote down vote up
/**
 * Get the DiffRows describing the difference between original and revised texts using the given
 * patch. Useful for displaying side-by-side diff.
 *
 * @param original the original text
 * @param revised the revised text
 * @return the DiffRows between original and revised texts
 */
public List<DiffRow> generateDiffRows(List<String> original, List<String> revised) {
    return generateDiffRows(original, DiffUtils.diff(original, revised, equalizer));
}