diff.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package diff
  14. import (
  15. "bytes"
  16. "encoding/json"
  17. "fmt"
  18. "reflect"
  19. "sort"
  20. "strings"
  21. "text/tabwriter"
  22. "github.com/davecgh/go-spew/spew"
  23. "k8s.io/apimachinery/pkg/util/validation/field"
  24. )
  25. // StringDiff diffs a and b and returns a human readable diff.
  26. func StringDiff(a, b string) string {
  27. ba := []byte(a)
  28. bb := []byte(b)
  29. out := []byte{}
  30. i := 0
  31. for ; i < len(ba) && i < len(bb); i++ {
  32. if ba[i] != bb[i] {
  33. break
  34. }
  35. out = append(out, ba[i])
  36. }
  37. out = append(out, []byte("\n\nA: ")...)
  38. out = append(out, ba[i:]...)
  39. out = append(out, []byte("\n\nB: ")...)
  40. out = append(out, bb[i:]...)
  41. out = append(out, []byte("\n\n")...)
  42. return string(out)
  43. }
  44. // ObjectDiff writes the two objects out as JSON and prints out the identical part of
  45. // the objects followed by the remaining part of 'a' and finally the remaining part of 'b'.
  46. // For debugging tests.
  47. func ObjectDiff(a, b interface{}) string {
  48. ab, err := json.Marshal(a)
  49. if err != nil {
  50. panic(fmt.Sprintf("a: %v", err))
  51. }
  52. bb, err := json.Marshal(b)
  53. if err != nil {
  54. panic(fmt.Sprintf("b: %v", err))
  55. }
  56. return StringDiff(string(ab), string(bb))
  57. }
  58. // ObjectGoPrintDiff is like ObjectDiff, but uses go-spew to print the objects,
  59. // which shows absolutely everything by recursing into every single pointer
  60. // (go's %#v formatters OTOH stop at a certain point). This is needed when you
  61. // can't figure out why reflect.DeepEqual is returning false and nothing is
  62. // showing you differences. This will.
  63. func ObjectGoPrintDiff(a, b interface{}) string {
  64. s := spew.ConfigState{DisableMethods: true}
  65. return StringDiff(
  66. s.Sprintf("%#v", a),
  67. s.Sprintf("%#v", b),
  68. )
  69. }
  70. func ObjectReflectDiff(a, b interface{}) string {
  71. vA, vB := reflect.ValueOf(a), reflect.ValueOf(b)
  72. if vA.Type() != vB.Type() {
  73. return fmt.Sprintf("type A %T and type B %T do not match", a, b)
  74. }
  75. diffs := objectReflectDiff(field.NewPath("object"), vA, vB)
  76. if len(diffs) == 0 {
  77. return "<no diffs>"
  78. }
  79. out := []string{""}
  80. for _, d := range diffs {
  81. elidedA, elidedB := limit(d.a, d.b, 80)
  82. out = append(out,
  83. fmt.Sprintf("%s:", d.path),
  84. fmt.Sprintf(" a: %s", elidedA),
  85. fmt.Sprintf(" b: %s", elidedB),
  86. )
  87. }
  88. return strings.Join(out, "\n")
  89. }
  90. // limit:
  91. // 1. stringifies aObj and bObj
  92. // 2. elides identical prefixes if either is too long
  93. // 3. elides remaining content from the end if either is too long
  94. func limit(aObj, bObj interface{}, max int) (string, string) {
  95. elidedPrefix := ""
  96. elidedASuffix := ""
  97. elidedBSuffix := ""
  98. a, b := fmt.Sprintf("%#v", aObj), fmt.Sprintf("%#v", bObj)
  99. if aObj != nil && bObj != nil {
  100. if aType, bType := fmt.Sprintf("%T", aObj), fmt.Sprintf("%T", bObj); aType != bType {
  101. a = fmt.Sprintf("%s (%s)", a, aType)
  102. b = fmt.Sprintf("%s (%s)", b, bType)
  103. }
  104. }
  105. for {
  106. switch {
  107. case len(a) > max && len(a) > 4 && len(b) > 4 && a[:4] == b[:4]:
  108. // a is too long, b has data, and the first several characters are the same
  109. elidedPrefix = "..."
  110. a = a[2:]
  111. b = b[2:]
  112. case len(b) > max && len(b) > 4 && len(a) > 4 && a[:4] == b[:4]:
  113. // b is too long, a has data, and the first several characters are the same
  114. elidedPrefix = "..."
  115. a = a[2:]
  116. b = b[2:]
  117. case len(a) > max:
  118. a = a[:max]
  119. elidedASuffix = "..."
  120. case len(b) > max:
  121. b = b[:max]
  122. elidedBSuffix = "..."
  123. default:
  124. // both are short enough
  125. return elidedPrefix + a + elidedASuffix, elidedPrefix + b + elidedBSuffix
  126. }
  127. }
  128. }
  129. func public(s string) bool {
  130. if len(s) == 0 {
  131. return false
  132. }
  133. return s[:1] == strings.ToUpper(s[:1])
  134. }
  135. type diff struct {
  136. path *field.Path
  137. a, b interface{}
  138. }
  139. type orderedDiffs []diff
  140. func (d orderedDiffs) Len() int { return len(d) }
  141. func (d orderedDiffs) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
  142. func (d orderedDiffs) Less(i, j int) bool {
  143. a, b := d[i].path.String(), d[j].path.String()
  144. if a < b {
  145. return true
  146. }
  147. return false
  148. }
  149. func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff {
  150. switch a.Type().Kind() {
  151. case reflect.Struct:
  152. var changes []diff
  153. for i := 0; i < a.Type().NumField(); i++ {
  154. if !public(a.Type().Field(i).Name) {
  155. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  156. continue
  157. }
  158. return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
  159. }
  160. if sub := objectReflectDiff(path.Child(a.Type().Field(i).Name), a.Field(i), b.Field(i)); len(sub) > 0 {
  161. changes = append(changes, sub...)
  162. }
  163. }
  164. return changes
  165. case reflect.Ptr, reflect.Interface:
  166. if a.IsNil() || b.IsNil() {
  167. switch {
  168. case a.IsNil() && b.IsNil():
  169. return nil
  170. case a.IsNil():
  171. return []diff{{path: path, a: nil, b: b.Interface()}}
  172. default:
  173. return []diff{{path: path, a: a.Interface(), b: nil}}
  174. }
  175. }
  176. return objectReflectDiff(path, a.Elem(), b.Elem())
  177. case reflect.Chan:
  178. if !reflect.DeepEqual(a.Interface(), b.Interface()) {
  179. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  180. }
  181. return nil
  182. case reflect.Slice:
  183. lA, lB := a.Len(), b.Len()
  184. l := lA
  185. if lB < lA {
  186. l = lB
  187. }
  188. if lA == lB && lA == 0 {
  189. if a.IsNil() != b.IsNil() {
  190. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  191. }
  192. return nil
  193. }
  194. var diffs []diff
  195. for i := 0; i < l; i++ {
  196. if !reflect.DeepEqual(a.Index(i), b.Index(i)) {
  197. diffs = append(diffs, objectReflectDiff(path.Index(i), a.Index(i), b.Index(i))...)
  198. }
  199. }
  200. for i := l; i < lA; i++ {
  201. diffs = append(diffs, diff{path: path.Index(i), a: a.Index(i), b: nil})
  202. }
  203. for i := l; i < lB; i++ {
  204. diffs = append(diffs, diff{path: path.Index(i), a: nil, b: b.Index(i)})
  205. }
  206. return diffs
  207. case reflect.Map:
  208. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  209. return nil
  210. }
  211. aKeys := make(map[interface{}]interface{})
  212. for _, key := range a.MapKeys() {
  213. aKeys[key.Interface()] = a.MapIndex(key).Interface()
  214. }
  215. var missing []diff
  216. for _, key := range b.MapKeys() {
  217. if _, ok := aKeys[key.Interface()]; ok {
  218. delete(aKeys, key.Interface())
  219. if reflect.DeepEqual(a.MapIndex(key).Interface(), b.MapIndex(key).Interface()) {
  220. continue
  221. }
  222. missing = append(missing, objectReflectDiff(path.Key(fmt.Sprintf("%s", key.Interface())), a.MapIndex(key), b.MapIndex(key))...)
  223. continue
  224. }
  225. missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key.Interface())), a: nil, b: b.MapIndex(key).Interface()})
  226. }
  227. for key, value := range aKeys {
  228. missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key)), a: value, b: nil})
  229. }
  230. if len(missing) == 0 {
  231. missing = append(missing, diff{path: path, a: a.Interface(), b: b.Interface()})
  232. }
  233. sort.Sort(orderedDiffs(missing))
  234. return missing
  235. default:
  236. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  237. return nil
  238. }
  239. if !a.CanInterface() {
  240. return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
  241. }
  242. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  243. }
  244. }
  245. // ObjectGoPrintSideBySide prints a and b as textual dumps side by side,
  246. // enabling easy visual scanning for mismatches.
  247. func ObjectGoPrintSideBySide(a, b interface{}) string {
  248. s := spew.ConfigState{
  249. Indent: " ",
  250. // Extra deep spew.
  251. DisableMethods: true,
  252. }
  253. sA := s.Sdump(a)
  254. sB := s.Sdump(b)
  255. linesA := strings.Split(sA, "\n")
  256. linesB := strings.Split(sB, "\n")
  257. width := 0
  258. for _, s := range linesA {
  259. l := len(s)
  260. if l > width {
  261. width = l
  262. }
  263. }
  264. for _, s := range linesB {
  265. l := len(s)
  266. if l > width {
  267. width = l
  268. }
  269. }
  270. buf := &bytes.Buffer{}
  271. w := tabwriter.NewWriter(buf, width, 0, 1, ' ', 0)
  272. max := len(linesA)
  273. if len(linesB) > max {
  274. max = len(linesB)
  275. }
  276. for i := 0; i < max; i++ {
  277. var a, b string
  278. if i < len(linesA) {
  279. a = linesA[i]
  280. }
  281. if i < len(linesB) {
  282. b = linesB[i]
  283. }
  284. fmt.Fprintf(w, "%s\t%s\n", a, b)
  285. }
  286. w.Flush()
  287. return buf.String()
  288. }