Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Add generateOriginalAndDiff method and test class #164

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions java-diff-utils/src/main/java/com/github/difflib/UnifiedDiffUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@
import com.github.difflib.patch.Chunk;
import com.github.difflib.patch.AbstractDelta;
import com.github.difflib.patch.Patch;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
*
Expand Down Expand Up @@ -313,4 +317,151 @@ private static List<String> getDeltaText(AbstractDelta<String> delta) {

private UnifiedDiffUtils() {
}

/**
* Compare the differences between two files and return to the original file and diff format
*
* (This method compares the original file with the comparison file to obtain a diff, and inserts the diff into the corresponding position of the original file.
* You can see all the differences and unmodified places from the original file.
* Also, this will be very easy and useful for making side-by-side comparison display applications,
* for example, if you use diff2html (https://github.com/rtfpessoa/diff2html#usage)
* Wait for tools to display your differences on html pages, you only need to insert the return value into your js code)
*
* @param original Original file content
* @param revised revised file content
*
*/
public static List<String> generateOriginalAndDiff(List<String> original, List<String> revised) {
return generateOriginalAndDiff(original, revised, null, null);
}


/**
* Compare the differences between two files and return to the original file and diff format
*
* (This method compares the original file with the comparison file to obtain a diff, and inserts the diff into the corresponding position of the original file.
* You can see all the differences and unmodified places from the original file.
* Also, this will be very easy and useful for making side-by-side comparison display applications,
* for example, if you use diff2html (https://github.com/rtfpessoa/diff2html#usage)
* Wait for tools to display your differences on html pages, you only need to insert the return value into your js code)
*
* @param original Original file content
* @param revised revised file content
* @param originalFileName Original file name
* @param revisedFileName revised file name
*/
public static List<String> generateOriginalAndDiff(List<String> original, List<String> revised, String originalFileName, String revisedFileName) {
String originalFileNameTemp = originalFileName;
String revisedFileNameTemp = originalFileName;
if (originalFileNameTemp == null) {
originalFileNameTemp = "original";
}
if (revisedFileNameTemp == null) {
revisedFileNameTemp = "revised";
}
Patch<String> patch = DiffUtils.diff(original, revised);
List<String> unifiedDiff = generateUnifiedDiff(originalFileNameTemp, revisedFileNameTemp, original, patch, 0);
if (unifiedDiff.isEmpty()) {
unifiedDiff.add("--- " + originalFileNameTemp);
unifiedDiff.add("+++ " + revisedFileNameTemp);
unifiedDiff.add("@@ -0,0 +0,0 @@");
} else if (unifiedDiff.size() >= 3 && !unifiedDiff.get(2).contains("@@ -1,")) {
unifiedDiff.set(1, unifiedDiff.get(1));
unifiedDiff.add(2, "@@ -0,0 +0,0 @@");
}
List<String> originalWithPrefix = original.stream().map(v -> " " + v).collect(Collectors.toList());
return insertOrig(originalWithPrefix, unifiedDiff);
}

//Insert the diff format to the original file
private static List<String> insertOrig(List<String> original, List<String> unifiedDiff) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor the method to use more descriptive variable names. For example, instead of using "d", you can use "diff".

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method is very long, it could be broken into multiple small methods to increase readability of the code.

List<String> result = new ArrayList<>();
List<List<String>> diffList = new ArrayList<>();
List<String> diff = new ArrayList<>();
for (int i = 0; i < unifiedDiff.size(); i++) {
String u = unifiedDiff.get(i);
if (u.startsWith("@@") && !"@@ -0,0 +0,0 @@".equals(u) && !u.contains("@@ -1,")) {
List<String> twoList = new ArrayList<>();
twoList.addAll(diff);
diffList.add(twoList);
diff.clear();
diff.add(u);
continue;
}
if (i == unifiedDiff.size() - 1) {
diff.add(u);
List<String> twoList = new ArrayList<>();
twoList.addAll(diff);
diffList.add(twoList);
diff.clear();
break;
}
diff.add(u);
}
insertOrig(diffList, result, original);
return result;
}

//Insert the diff format to the original file
private static void insertOrig(List<List<String>> diffList, List<String> result, List<String> original) {
for (int i = 0; i < diffList.size(); i++) {
List<String> diff = diffList.get(i);
List<String> nexDiff = i == diffList.size() - 1 ? null : diffList.get(i + 1);
String simb = i == 0 ? diff.get(2) : diff.get(0);
String nexSimb = nexDiff == null ? null : nexDiff.get(0);
insert(result, diff);
Map<String, Integer> map = getRowMap(simb);
if (null != nexSimb) {
Map<String, Integer> nexMap = getRowMap(nexSimb);
int start = 0;
if (map.get("orgRow") != 0) {
start = map.get("orgRow") + map.get("orgDel") - 1;
}
int end = nexMap.get("revRow") - 2;
insert(result, getOrigList(original, start, end));
}
if (simb.contains("@@ -1,") && null == nexSimb && map.get("orgDel") != original.size()) {
insert(result, getOrigList(original, 0, original.size() - 1));
} else if (null == nexSimb && (map.get("orgRow") + map.get("orgDel") - 1) < original.size()) {
int start = map.get("orgRow") + map.get("orgDel") - 1;
start = start == -1 ? 0 : start;
insert(result, getOrigList(original, start, original.size() - 1));
}
}
}

//Insert the unchanged content in the source file into result
private static void insert(List<String> result, List<String> noChangeContent) {
for (String ins : noChangeContent) {
result.add(ins);
}
}

//Parse the line containing @@ to get the modified line number to delete or add a few lines
private static Map<String, Integer> getRowMap(String str) {
Map<String, Integer> map = new HashMap<>();
if (str.startsWith("@@")) {
String[] sp = str.split(" ");
String org = sp[1];
String[] orgSp = org.split(",");
map.put("orgRow", Integer.valueOf(orgSp[0].substring(1)));
map.put("orgDel", Integer.valueOf(orgSp[1]));
String[] revSp = org.split(",");
map.put("revRow", Integer.valueOf(revSp[0].substring(1)));
map.put("revAdd", Integer.valueOf(revSp[1]));
}
return map;
}

//Get the specified part of the line from the original file
private static List<String> getOrigList(List<String> originalWithPrefix, int start, int end) {
List<String> list = new ArrayList<>();
if (originalWithPrefix.size() >= 1 && start <= end && end < originalWithPrefix.size()) {
int startTemp = start;
for (; startTemp <= end; startTemp++) {
list.add(originalWithPrefix.get(startTemp));
}
}
return list;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.github.difflib.examples;

import com.github.difflib.TestConstants;
import com.github.difflib.UnifiedDiffUtils;
import org.junit.jupiter.api.Test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static java.util.stream.Collectors.joining;
import static org.junit.jupiter.api.Assertions.fail;

public class OriginalAndDiffTest {

@Test
public void testGenerateOriginalAndDiff() {
List<String> origLines = null;
List<String> revLines = null;
try {
origLines = fileToLines(TestConstants.MOCK_FOLDER + "original.txt");
revLines = fileToLines(TestConstants.MOCK_FOLDER + "revised.txt");
} catch (IOException e) {
fail(e.getMessage());
}

List<String> originalAndDiff = UnifiedDiffUtils.generateOriginalAndDiff(origLines, revLines);
System.out.println(originalAndDiff.stream().collect(joining("\n")));
}

public static List<String> fileToLines(String filename) throws FileNotFoundException, IOException {
List<String> lines = new ArrayList<>();
String line = "";
try (BufferedReader in = new BufferedReader(new FileReader(filename))) {
while ((line = in.readLine()) != null) {
lines.add(line);
}
}
return lines;
}
}