-
Notifications
You must be signed in to change notification settings - Fork 8
/
diff.go
74 lines (60 loc) · 1.23 KB
/
diff.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
package yam
import (
"errors"
"fmt"
"os"
"os/exec"
)
type DiffHandler func(want, got []byte) error
func ExecDiff(want, got []byte) error {
handlerOutput := os.Stderr
tempWant, err := os.CreateTemp("", "want-*")
if err != nil {
return err
}
defer os.Remove(tempWant.Name())
tempGot, err := os.CreateTemp("", "got-*")
if err != nil {
return err
}
defer os.Remove(tempGot.Name())
_, err = tempWant.Write(want)
if err != nil {
return err
}
_, err = tempGot.Write(got)
if err != nil {
return err
}
const command = "diff"
_, err = exec.LookPath(command)
if err != nil {
return fmt.Errorf("unable to execute diff command: %w", err)
}
cmd := exec.Command(
command,
"-U",
"5",
"--label",
"want",
"--label",
"got",
tempWant.Name(),
tempGot.Name(),
)
cmd.Stdout = handlerOutput
cmd.Stderr = handlerOutput
err = cmd.Run()
if err != nil {
var exitError *exec.ExitError
if errors.As(err, &exitError) {
if exitError.ExitCode() == 1 {
// that's expected for `diff` when there's a diff!
fmt.Fprint(handlerOutput, "\n") // for gap between diffs; useful if diffing multiple files.
return nil
}
}
return fmt.Errorf("error executing diff command %q: %w", cmd, err)
}
return nil
}