forked from vmware-archive/kubecfg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
diff.go
176 lines (156 loc) · 4.45 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright 2017 The kubecfg authors
//
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package kubecfg
import (
"fmt"
"io"
"os"
"sort"
isatty "github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/yudai/gojsondiff"
"github.com/yudai/gojsondiff/formatter"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
"github.com/ksonnet/kubecfg/utils"
)
var ErrDiffFound = fmt.Errorf("Differences found.")
// DiffCmd represents the diff subcommand
type DiffCmd struct {
ClientPool dynamic.ClientPool
Discovery discovery.DiscoveryInterface
DefaultNamespace string
DiffStrategy string
}
func (c DiffCmd) Run(apiObjects []*unstructured.Unstructured, out io.Writer) error {
sort.Sort(utils.AlphabeticalOrder(apiObjects))
diffFound := false
for _, obj := range apiObjects {
desc := fmt.Sprintf("%s %s", utils.ResourceNameFor(c.Discovery, obj), utils.FqName(obj))
log.Debugf("Fetching ", desc)
client, err := utils.ClientForResource(c.ClientPool, c.Discovery, obj, c.DefaultNamespace)
if err != nil {
return err
}
liveObj, err := client.Get(obj.GetName(), metav1.GetOptions{})
if err != nil && errors.IsNotFound(err) {
log.Debugf("%s doesn't exist on the server", desc)
liveObj = nil
} else if err != nil {
return fmt.Errorf("Error fetching %s: %v", desc, err)
}
fmt.Fprintln(out, "---")
fmt.Fprintf(out, "- live %s\n+ config %s\n", desc, desc)
if liveObj == nil {
fmt.Fprintf(out, "%s doesn't exist on server\n", desc)
diffFound = true
continue
}
liveObjObject := liveObj.Object
if c.DiffStrategy == "subset" {
liveObjObject = removeMapFields(obj.Object, liveObjObject)
}
diff := gojsondiff.New().CompareObjects(liveObjObject, obj.Object)
if diff.Modified() {
diffFound = true
fcfg := formatter.AsciiFormatterConfig{
Coloring: istty(out),
}
formatter := formatter.NewAsciiFormatter(liveObjObject, fcfg)
text, err := formatter.Format(diff)
if err != nil {
return err
}
fmt.Fprintf(out, "%s", text)
} else {
fmt.Fprintf(out, "%s unchanged\n", desc)
}
}
if diffFound {
return ErrDiffFound
}
return nil
}
// See also feature request for golang reflect pkg at
func isEmptyValue(i interface{}) bool {
switch v := i.(type) {
case []interface{}:
return len(v) == 0
case []string:
return len(v) == 0
case map[string]interface{}:
return len(v) == 0
case bool:
return !v
case float64:
return v == 0
case int64:
return v == 0
case string:
return v == ""
case nil:
return true
default:
panic(fmt.Sprintf("Found unexpected type %T in json unmarshal (value=%v)", i, i))
}
}
func removeFields(config, live interface{}) interface{} {
switch c := config.(type) {
case map[string]interface{}:
return removeMapFields(c, live.(map[string]interface{}))
case []interface{}:
return removeListFields(c, live.([]interface{}))
default:
return live
}
}
func removeMapFields(config, live map[string]interface{}) map[string]interface{} {
result := map[string]interface{}{}
for k, v1 := range config {
v2, ok := live[k]
if !ok {
// Copy empty value from config, as API won't return them,
// see https://github.com/ksonnet/kubecfg/issues/179
if isEmptyValue(v1) {
result[k] = v1
}
continue
}
result[k] = removeFields(v1, v2)
}
return result
}
func removeListFields(config, live []interface{}) []interface{} {
// If live is longer than config, then the extra elements at the end of the
// list will be returned as is so they appear in the diff.
result := make([]interface{}, 0, len(live))
for i, v2 := range live {
if len(config) > i {
result = append(result, removeFields(config[i], v2))
} else {
result = append(result, v2)
}
}
return result
}
func istty(w io.Writer) bool {
if f, ok := w.(*os.File); ok {
return isatty.IsTerminal(f.Fd())
}
return false
}