-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
92 lines (83 loc) · 2.29 KB
/
file.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
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"bytes"
"errors"
"io/fs"
"os"
"path/filepath"
"github.com/avamsi/ergo/assert"
)
type fileState int
const (
fileStateUnknown fileState = iota
fileUnedited
fileSameAsBase
fileSameAsLeft
fileSameAsRight
fileEditedOther
)
type file struct {
base, left, right, output string // paths (empty if not applicable)
relpath string
state fileState
baseContent, leftContent, rightContent []byte
initialContent []byte
}
func readFile(path string) ([]byte, bool) {
b, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return nil, false
}
assert.Nil(err)
return b, true
}
func newFile(base, left, right, output, relpath string) file {
f := file{
left: filepath.Join(left, relpath),
right: filepath.Join(right, relpath),
relpath: relpath,
state: fileUnedited,
}
var ok bool
if f.leftContent, ok = readFile(f.left); !ok {
f.left = "/dev/null"
}
f.rightContent, ok = readFile(f.right)
// TODO: we require right to exist for now, but this is not ideal as it's
// possible for right to be deleted. folderphile should gracefully allow the
// user to create right again, instead of just panicking.
assert.Truef(ok, "right file %q does not exist", f.right)
if base != "" {
f.base = filepath.Join(base, relpath)
if f.baseContent, ok = readFile(f.base); !ok {
f.base = "/dev/null"
}
}
if output != "" {
f.output = filepath.Join(output, relpath)
f.initialContent, ok = readFile(f.output)
// TODO: similar to right above, output need not exist.
assert.Truef(ok, "output file %q does not exist", f.output)
} else {
// Assumed to be a 2-way diff, where right is the editable side.
assert.Truef(base == "", "base is not empty (%q) in a 2-way diff", base)
f.output = f.right
f.initialContent = f.rightContent
}
return f
}
func (f *file) updateState() {
switch content, _ := readFile(f.output); {
case bytes.Equal(content, f.initialContent):
f.state = fileUnedited
case bytes.Equal(content, f.leftContent):
f.state = fileSameAsLeft
case bytes.Equal(content, f.rightContent):
f.state = fileSameAsRight
// Same-as-base is not as likely as others, check last.
case f.base != "" && bytes.Equal(content, f.baseContent):
f.state = fileSameAsBase
default:
f.state = fileEditedOther
}
}