|
1 | 1 | package diffr |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "bufio" |
4 | 5 | "fmt" |
5 | | - "io/ioutil" |
6 | 6 | "os" |
7 | 7 | "path/filepath" |
| 8 | + "runtime" |
| 9 | + "strings" |
8 | 10 | "sync" |
9 | 11 |
|
10 | 12 | "github.com/pmezard/go-difflib/difflib" |
11 | 13 | ) |
12 | 14 |
|
| 15 | +func readFileContent(filePath string) (string, error) { |
| 16 | + file, err := os.Open(filePath) |
| 17 | + if err != nil { |
| 18 | + return "", err |
| 19 | + } |
| 20 | + defer file.Close() |
| 21 | + |
| 22 | + bufferedReader := bufio.NewReader(file) |
| 23 | + var contentBuilder strings.Builder |
| 24 | + bufferSize := 4096 |
| 25 | + buffer := make([]byte, bufferSize) |
| 26 | + |
| 27 | + for { |
| 28 | + n, err := bufferedReader.Read(buffer) |
| 29 | + if err != nil { |
| 30 | + break |
| 31 | + } |
| 32 | + contentBuilder.Write(buffer[:n]) |
| 33 | + } |
| 34 | + |
| 35 | + return contentBuilder.String(), nil |
| 36 | +} |
| 37 | + |
13 | 38 | func compareFiles(file1, file2 string) (string, error) { |
14 | | - content1, err := ioutil.ReadFile(file1) |
| 39 | + content1, err := readFileContent(file1) |
15 | 40 | if err != nil { |
16 | 41 | return "", err |
17 | 42 | } |
18 | 43 |
|
19 | | - content2, err := ioutil.ReadFile(file2) |
| 44 | + content2, err := readFileContent(file2) |
20 | 45 | if err != nil { |
21 | 46 | return "", err |
22 | 47 | } |
23 | 48 |
|
24 | 49 | diff := difflib.UnifiedDiff{ |
25 | | - A: difflib.SplitLines(string(content1)), |
26 | | - B: difflib.SplitLines(string(content2)), |
| 50 | + A: difflib.SplitLines(content1), |
| 51 | + B: difflib.SplitLines(content2), |
27 | 52 | FromFile: file1, |
28 | 53 | ToFile: file2, |
29 | 54 | Context: 3, |
@@ -69,9 +94,16 @@ func CompareDirectories(dir1, dir2 string, diffChan chan<- string, errorChan cha |
69 | 94 | diffChan <- fmt.Sprintf("Differences in file: %s\n%s", relPath, diff) |
70 | 95 | } |
71 | 96 | } else if os.IsNotExist(err) { |
72 | | - diff, err := compareFiles(path1, "/dev/null") |
| 97 | + var nullDevice string |
| 98 | + if runtime.GOOS == "windows" { |
| 99 | + nullDevice = "NUL" |
| 100 | + } else { |
| 101 | + nullDevice = "/dev/null" |
| 102 | + } |
| 103 | + |
| 104 | + diff, err := compareFiles(path1, nullDevice) |
73 | 105 | if err != nil { |
74 | | - errorChan <- fmt.Errorf("error comparing files %s and /dev/null: %s", path1, err) |
| 106 | + errorChan <- fmt.Errorf("error comparing files %s and %s: %s", path1, nullDevice, err) |
75 | 107 | return nil |
76 | 108 | } |
77 | 109 |
|
|
0 commit comments