diff.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. for {
  100. switch {
  101. case len(a) > max && len(a) > 4 && len(b) > 4 && a[:4] == b[:4]:
  102. // a is too long, b has data, and the first several characters are the same
  103. elidedPrefix = "..."
  104. a = a[2:]
  105. b = b[2:]
  106. case len(b) > max && len(b) > 4 && len(a) > 4 && a[:4] == b[:4]:
  107. // b is too long, a has data, and the first several characters are the same
  108. elidedPrefix = "..."
  109. a = a[2:]
  110. b = b[2:]
  111. case len(a) > max:
  112. a = a[:max]
  113. elidedASuffix = "..."
  114. case len(b) > max:
  115. b = b[:max]
  116. elidedBSuffix = "..."
  117. default:
  118. // both are short enough
  119. return elidedPrefix + a + elidedASuffix, elidedPrefix + b + elidedBSuffix
  120. }
  121. }
  122. }
  123. func public(s string) bool {
  124. if len(s) == 0 {
  125. return false
  126. }
  127. return s[:1] == strings.ToUpper(s[:1])
  128. }
  129. type diff struct {
  130. path *field.Path
  131. a, b interface{}
  132. }
  133. type orderedDiffs []diff
  134. func (d orderedDiffs) Len() int { return len(d) }
  135. func (d orderedDiffs) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
  136. func (d orderedDiffs) Less(i, j int) bool {
  137. a, b := d[i].path.String(), d[j].path.String()
  138. if a < b {
  139. return true
  140. }
  141. return false
  142. }
  143. func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff {
  144. switch a.Type().Kind() {
  145. case reflect.Struct:
  146. var changes []diff
  147. for i := 0; i < a.Type().NumField(); i++ {
  148. if !public(a.Type().Field(i).Name) {
  149. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  150. continue
  151. }
  152. return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
  153. }
  154. if sub := objectReflectDiff(path.Child(a.Type().Field(i).Name), a.Field(i), b.Field(i)); len(sub) > 0 {
  155. changes = append(changes, sub...)
  156. }
  157. }
  158. return changes
  159. case reflect.Ptr, reflect.Interface:
  160. if a.IsNil() || b.IsNil() {
  161. switch {
  162. case a.IsNil() && b.IsNil():
  163. return nil
  164. case a.IsNil():
  165. return []diff{{path: path, a: nil, b: b.Interface()}}
  166. default:
  167. return []diff{{path: path, a: a.Interface(), b: nil}}
  168. }
  169. }
  170. return objectReflectDiff(path, a.Elem(), b.Elem())
  171. case reflect.Chan:
  172. if !reflect.DeepEqual(a.Interface(), b.Interface()) {
  173. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  174. }
  175. return nil
  176. case reflect.Slice:
  177. lA, lB := a.Len(), b.Len()
  178. l := lA
  179. if lB < lA {
  180. l = lB
  181. }
  182. if lA == lB && lA == 0 {
  183. if a.IsNil() != b.IsNil() {
  184. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  185. }
  186. return nil
  187. }
  188. var diffs []diff
  189. for i := 0; i < l; i++ {
  190. if !reflect.DeepEqual(a.Index(i), b.Index(i)) {
  191. diffs = append(diffs, objectReflectDiff(path.Index(i), a.Index(i), b.Index(i))...)
  192. }
  193. }
  194. for i := l; i < lA; i++ {
  195. diffs = append(diffs, diff{path: path.Index(i), a: a.Index(i), b: nil})
  196. }
  197. for i := l; i < lB; i++ {
  198. diffs = append(diffs, diff{path: path.Index(i), a: nil, b: b.Index(i)})
  199. }
  200. return diffs
  201. case reflect.Map:
  202. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  203. return nil
  204. }
  205. aKeys := make(map[interface{}]interface{})
  206. for _, key := range a.MapKeys() {
  207. aKeys[key.Interface()] = a.MapIndex(key).Interface()
  208. }
  209. var missing []diff
  210. for _, key := range b.MapKeys() {
  211. if _, ok := aKeys[key.Interface()]; ok {
  212. delete(aKeys, key.Interface())
  213. if reflect.DeepEqual(a.MapIndex(key).Interface(), b.MapIndex(key).Interface()) {
  214. continue
  215. }
  216. missing = append(missing, objectReflectDiff(path.Key(fmt.Sprintf("%s", key.Interface())), a.MapIndex(key), b.MapIndex(key))...)
  217. continue
  218. }
  219. missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key.Interface())), a: nil, b: b.MapIndex(key).Interface()})
  220. }
  221. for key, value := range aKeys {
  222. missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key)), a: value, b: nil})
  223. }
  224. if len(missing) == 0 {
  225. missing = append(missing, diff{path: path, a: a.Interface(), b: b.Interface()})
  226. }
  227. sort.Sort(orderedDiffs(missing))
  228. return missing
  229. default:
  230. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  231. return nil
  232. }
  233. if !a.CanInterface() {
  234. return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
  235. }
  236. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  237. }
  238. }
  239. // ObjectGoPrintSideBySide prints a and b as textual dumps side by side,
  240. // enabling easy visual scanning for mismatches.
  241. func ObjectGoPrintSideBySide(a, b interface{}) string {
  242. s := spew.ConfigState{
  243. Indent: " ",
  244. // Extra deep spew.
  245. DisableMethods: true,
  246. }
  247. sA := s.Sdump(a)
  248. sB := s.Sdump(b)
  249. linesA := strings.Split(sA, "\n")
  250. linesB := strings.Split(sB, "\n")
  251. width := 0
  252. for _, s := range linesA {
  253. l := len(s)
  254. if l > width {
  255. width = l
  256. }
  257. }
  258. for _, s := range linesB {
  259. l := len(s)
  260. if l > width {
  261. width = l
  262. }
  263. }
  264. buf := &bytes.Buffer{}
  265. w := tabwriter.NewWriter(buf, width, 0, 1, ' ', 0)
  266. max := len(linesA)
  267. if len(linesB) > max {
  268. max = len(linesB)
  269. }
  270. for i := 0; i < max; i++ {
  271. var a, b string
  272. if i < len(linesA) {
  273. a = linesA[i]
  274. }
  275. if i < len(linesB) {
  276. b = linesB[i]
  277. }
  278. fmt.Fprintf(w, "%s\t%s\n", a, b)
  279. }
  280. w.Flush()
  281. return buf.String()
  282. }