com.github.difflib.algorithm.DiffException Java Examples

The following examples show how to use com.github.difflib.algorithm.DiffException. 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 7 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: PreprocessAsciiDocMojo.java    From helidon-build-tools with Apache License 2.0 5 votes vote down vote up
private void compareFiles(Path pathA, Path pathB) throws IOException, MojoFailureException, MojoExecutionException {
    if (pathA.equals(pathB)) {
        getLog().warn(
                new IllegalArgumentException(
                    "'check' set to true but it will always pass: "
                            + "input and output files are the same"));
    }
    try {
        byte[] inputDigest = digest(pathA);
        byte[] outputDigest = digest(pathB);
        if (!Arrays.equals(inputDigest, outputDigest)) {
            throw new MojoFailureException(String.format(
                    "file %s does not match its expected pre-processed form; "
                            + "the commit might need an up-to-date file from running 'preprocess-adoc'%n%s ",
                    pathA.toString(),
                    formatDiffs(pathA, pathB)));
        }
    } catch (NoSuchAlgorithmException e) {
        throw new MojoExecutionException("error checking for matching input and output files", e);
    } catch (DiffException ex) {
        throw new MojoExecutionException(
            String.format("Error comparing %s and %s",
                    pathA.toString(),
                    pathB.toString()),
            ex);
    }
}
 
Example #4
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 #5
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 #6
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 #7
Source File: TextDiffSubject.java    From nomulus with Apache License 2.0 5 votes vote down vote up
static String generateSideBySideDiff(
    ImmutableList<String> expectedContent, ImmutableList<String> actualContent) {
  DiffRowGenerator generator =
      DiffRowGenerator.create()
          .showInlineDiffs(true)
          .inlineDiffByWord(true)
          .oldTag(f -> "~")
          .newTag(f -> "**")
          .build();
  List<DiffRow> rows;
  try {
    rows = generator.generateDiffRows(expectedContent, actualContent);
  } catch (DiffException e) {
    throw new RuntimeException(e);
  }

  int maxExpectedLineLength =
      findMaxLineLength(rows.stream().map(DiffRow::getOldLine).collect(Collectors.toList()));
  int maxActualLineLength =
      findMaxLineLength(rows.stream().map(DiffRow::getNewLine).collect(Collectors.toList()));

  SideBySideRowFormatter sideBySideRowFormatter =
      new SideBySideRowFormatter(maxExpectedLineLength, maxActualLineLength);

  return Joiner.on('\n')
      .join(
          sideBySideRowFormatter.formatRow("Expected", "Actual", ' '),
          sideBySideRowFormatter.formatRow("", "", '-'),
          rows.stream()
              .map(
                  row ->
                      sideBySideRowFormatter.formatRow(row.getOldLine(), row.getNewLine(), ' '))
              .toArray());
}
 
Example #8
Source File: MorphAnalyzeService.java    From KOMORAN with Apache License 2.0 5 votes vote down vote up
public Map<String, String> generateDiffRows(List<String> resultSrc, List<String> resultDest) {

        Map<String, String> result = new HashMap<>();

        StringBuffer resultSrcHtml = new StringBuffer();
        StringBuffer resultDestHtml = new StringBuffer();
        boolean isFirst = true;

        DiffRowGenerator generator = DiffRowGenerator.create()
                .showInlineDiffs(true)
                .inlineDiffByWord(true)
                .build();
        try {
            for (int i = 0; i < resultSrc.size(); i++) {
                List<DiffRow> rows = generator.generateDiffRows(Arrays.asList(resultSrc.get(i).split(" ")), Arrays.asList(resultDest.get(i).split(" ")));

                for (DiffRow row : rows) {
                    if (!isFirst) {
                        resultSrcHtml.append(" ");
                        resultDestHtml.append(" ");
                    } else {
                        isFirst = false;
                    }

                    resultSrcHtml.append(row.getOldLine());
                    resultDestHtml.append(row.getNewLine());
                }
                resultSrcHtml.append("<br />");
                resultDestHtml.append("<br />");
            }
        } catch (DiffException e) {
            throw new ServerErrorException("분석 결과 비교 중 문제가 발생하였습니다.");
        }

        result.put("srcHtml", resultSrcHtml.toString());
        result.put("destHtml", resultDestHtml.toString());
        return result;
    }
 
Example #9
Source File: ClientTest.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Test
public void getPatch() throws DiffException {
  String expected = "1\n2\n3";
  String actual = "1\n2";

  assertThat(
      Client.getPatch(expected, actual, "expected.txt", "actual.txt"),
      equalTo(
          "--- expected.txt\n"
              + "+++ actual.txt\n"
              + "@@ -1,3 +1,2 @@\n"
              + " 1\n"
              + " 2\n"
              + "-3"));
}
 
Example #10
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 #11
Source File: MorphAnalyzeService.java    From KOMORAN with Apache License 2.0 4 votes vote down vote up
public Map<String, String> getDiffsFromAnalyzedResults(String strToAnalyze, String modelNameSrc, String modelNameDest) {
    ModelValidator.CheckValidModelName(modelNameSrc);
    ModelValidator.CheckValidModelName(modelNameDest);

    String resultSrc;
    String resultDest;
    Map<String, String> result = new HashMap<>();

    if ("DEFAULT".equals(modelNameSrc)) {
        resultSrc = this.analyzeWithLightModel(strToAnalyze);
    } else {
        resultSrc = this.analyzeWithUserModel(strToAnalyze, modelNameSrc);
    }

    if ("DEFAULT".equals(modelNameDest)) {
        resultDest = this.analyzeWithLightModel(strToAnalyze);
    } else {
        resultDest = this.analyzeWithUserModel(strToAnalyze, modelNameDest);
    }

    StringBuffer resultSrcHtml = new StringBuffer();
    StringBuffer resultDestHtml = new StringBuffer();
    boolean isFirst = true;

    DiffRowGenerator generator = DiffRowGenerator.create()
            .showInlineDiffs(true)
            .inlineDiffByWord(true)
            .build();
    try {
        List<DiffRow> rows = generator.generateDiffRows(Arrays.asList(resultSrc.split(" ")), Arrays.asList(resultDest.split(" ")));

        for (DiffRow row : rows) {
            if (!isFirst) {
                resultSrcHtml.append(" ");
                resultDestHtml.append(" ");
            } else {
                isFirst = false;
            }

            resultSrcHtml.append(row.getOldLine());
            resultDestHtml.append(row.getNewLine());
        }
    } catch (DiffException e) {
        throw new ServerErrorException("분석 결과 비교 중 문제가 발생하였습니다.");
    }

    result.put("srcHtml", resultSrcHtml.toString());
    result.put("destHtml", resultDestHtml.toString());

    return result;
}
 
Example #12
Source File: FineGrainDifftAnalyzer.java    From coming with MIT License 4 votes vote down vote up
/**
	 * Analyze a commit finding instances of changes return a Map<FileCommit, List>
	 */
	@SuppressWarnings("rawtypes")
	public AnalysisResult analyze(IRevision revision) {

		List<IRevisionPair> javaFiles = revision.getChildren();

		Map<String, Diff> diffOfFiles = new HashMap<>();

		List<DiffRow> rows = null;

		log.info("\n*****\nCommit: " + revision.getName());

		for (IRevisionPair<String> fileFromRevision : javaFiles) {

			String left = fileFromRevision.getPreviousVersion();
			String right = fileFromRevision.getNextVersion();

			String leftName = fileFromRevision.getPreviousName();
			String rightName = fileFromRevision.getName();

			Diff diff = compare(left, right, leftName, rightName);
			if (diff != null) {
				diffOfFiles.put(fileFromRevision.getName(), diff);
			}

			DiffRowGenerator generator = DiffRowGenerator.create().showInlineDiffs(false).inlineDiffByWord(false)
					.ignoreWhiteSpaces(true).build();

			try {
				rows = generator.generateDiffRows(
						Arrays.stream(fileFromRevision.getPreviousVersion().split("\n")).collect(Collectors.toList()),
						Arrays.stream(fileFromRevision.getNextVersion().split("\n")).collect(Collectors.toList()));
			} catch (DiffException e) {
				e.printStackTrace();
			}

//			System.out.println("Diff of the revision");
//			for (DiffRow row : rows) {
//				switch (row.getTag()) {
//					case INSERT:
//						System.out.println("+ " + valueOf(row.getNewLine()));
//						break;
//					case DELETE:
//						System.out.println("- " + valueOf(row.getOldLine()));
//						break;
//					case CHANGE:
//						System.out.println("- " + valueOf(row.getOldLine()));
//						System.out.println("+ " + valueOf(row.getNewLine()));
//						break;
//				}
//			}

		}

		return (new DiffResult<IRevision, Diff>(revision, diffOfFiles, rows));
	}