This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
equal.go
81 lines (67 loc) · 1.47 KB
/
equal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package swfs
import (
"bufio"
"errors"
"fmt"
"io/fs"
)
func equalFiles(a fs.FS, b fs.FS, path string) error {
fileA, err := a.Open(path)
if err != nil {
return err
}
defer fileA.Close()
fileAInfo, err := fileA.Stat()
if err != nil {
return err
}
fileB, err := b.Open(path)
if err != nil {
return err
}
defer fileB.Close()
fileBInfo, err := fileB.Stat()
if err != nil {
return err
}
if fileAInfo.Size() != fileBInfo.Size() {
return errors.New("file sizes not equal")
}
scannerA := bufio.NewScanner(fileA)
scannerB := bufio.NewScanner(fileB)
for scannerA.Scan() {
if !scannerB.Scan() {
return fmt.Errorf("reached end of file")
}
textA := scannerA.Text()
textB := scannerB.Text()
if textA != textB {
return fmt.Errorf("lines not equal: '%s' / '%s'", textA, textB)
}
}
return nil
}
var errorUnequal = "files are not equal"
// Equal ensures that all files and folders in 'a' exist in 'b'.
// This function will return true even if dirB contains more items than 'a', as long as
// all items in 'a' exist in 'b'.
func Equal(a fs.FS, b fs.FS) (bool, error) {
if err := fs.WalkDir(a, ".", func(path string, d fs.DirEntry, err error) error {
if path == "." {
return nil
}
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
if err := equalFiles(a, b, path); err != nil {
return fmt.Errorf("files not equal '%s' for equality: %w", path, err)
}
return nil
}); err != nil {
return false, err
}
return true, nil
}