/
diff.go
99 lines (84 loc) · 2.64 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package client
import (
"bytes"
"os"
"os/exec"
"regexp"
"strings"
"github.com/Masterminds/semver"
"github.com/grafana/tanka/pkg/kubernetes/manifest"
)
// DiffServerSide takes the desired state and computes the differences server-side, returning them in `diff(1)` format
func (k Kubectl) DiffServerSide(data manifest.List) (*string, error) {
return k.diff(data, true)
}
// ValidateServerSide takes the desired state and computes the differences, returning them in `diff(1)` format
// It also validates that manifests are valid server-side, but still returns the client-side diff
func (k Kubectl) ValidateServerSide(data manifest.List) (*string, error) {
if _, diffErr := k.diff(data, true); diffErr != nil {
return nil, diffErr
}
return k.diff(data, false)
}
// DiffClientSide takes the desired state and computes the differences, returning them in `diff(1)` format
func (k Kubectl) DiffClientSide(data manifest.List) (*string, error) {
return k.diff(data, false)
}
func (k Kubectl) diff(data manifest.List, serverSide bool) (*string, error) {
fw := FilterWriter{filters: []*regexp.Regexp{regexp.MustCompile(`exit status \d`)}}
args := []string{"-f", "-"}
if serverSide {
args = append(args, "--server-side", "--force-conflicts")
if k.info.ClientVersion.GreaterThan(semver.MustParse("1.19.0")) {
args = append(args, "--field-manager=tanka")
}
}
cmd := k.ctl("diff", args...)
raw := bytes.Buffer{}
// If using an external diff tool, let it keep the parent's stdout
if os.Getenv("KUBECTL_INTERACTIVE_DIFF") != "" {
cmd.Stdout = os.Stdout
} else {
cmd.Stdout = &raw
}
cmd.Stderr = &fw
cmd.Stdin = strings.NewReader(data.String())
err := cmd.Run()
if diffErr := parseDiffErr(err, fw.buf, k.Info().ClientVersion); diffErr != nil {
return nil, diffErr
}
s := raw.String()
if s == "" {
return nil, nil
}
return &s, nil
}
// parseDiffErr handles the exit status code of `kubectl diff`. It returns err
// when an error happened, nil otherwise.
// "Differences found (exit status 1)" is not an error.
//
// kubectl >= 1.18:
// 0: no error, no differences
// 1: differences found
// >1: error
//
// kubectl < 1.18:
// 0: no error, no differences
// 1: error OR differences found
func parseDiffErr(err error, stderr string, version *semver.Version) error {
exitErr, ok := err.(*exec.ExitError)
if !ok {
// this error is not kubectl related
return err
}
// internal kubectl error
if exitErr.ExitCode() != 1 {
return err
}
// before 1.18 "exit status 1" meant error as well ... so we need to check stderr
if version.LessThan(semver.MustParse("1.18.0")) && stderr != "" {
return err
}
// differences found is not an error
return nil
}