diff.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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/kubernetes/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 ""
  78. }
  79. out := []string{""}
  80. for _, d := range diffs {
  81. out = append(out,
  82. fmt.Sprintf("%s:", d.path),
  83. limit(fmt.Sprintf(" a: %#v", d.a), 80),
  84. limit(fmt.Sprintf(" b: %#v", d.b), 80),
  85. )
  86. }
  87. return strings.Join(out, "\n")
  88. }
  89. func limit(s string, max int) string {
  90. if len(s) > max {
  91. return s[:max]
  92. }
  93. return s
  94. }
  95. func public(s string) bool {
  96. if len(s) == 0 {
  97. return false
  98. }
  99. return s[:1] == strings.ToUpper(s[:1])
  100. }
  101. type diff struct {
  102. path *field.Path
  103. a, b interface{}
  104. }
  105. type orderedDiffs []diff
  106. func (d orderedDiffs) Len() int { return len(d) }
  107. func (d orderedDiffs) Swap(i, j int) { d[i], d[j] = d[j], d[i] }
  108. func (d orderedDiffs) Less(i, j int) bool {
  109. a, b := d[i].path.String(), d[j].path.String()
  110. if a < b {
  111. return true
  112. }
  113. return false
  114. }
  115. func objectReflectDiff(path *field.Path, a, b reflect.Value) []diff {
  116. switch a.Type().Kind() {
  117. case reflect.Struct:
  118. var changes []diff
  119. for i := 0; i < a.Type().NumField(); i++ {
  120. if !public(a.Type().Field(i).Name) {
  121. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  122. return nil
  123. }
  124. return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
  125. }
  126. if sub := objectReflectDiff(path.Child(a.Type().Field(i).Name), a.Field(i), b.Field(i)); len(sub) > 0 {
  127. changes = append(changes, sub...)
  128. }
  129. }
  130. return changes
  131. case reflect.Ptr, reflect.Interface:
  132. if a.IsNil() || b.IsNil() {
  133. switch {
  134. case a.IsNil() && b.IsNil():
  135. return nil
  136. case a.IsNil():
  137. return []diff{{path: path, a: nil, b: b.Interface()}}
  138. default:
  139. return []diff{{path: path, a: a.Interface(), b: nil}}
  140. }
  141. }
  142. return objectReflectDiff(path, a.Elem(), b.Elem())
  143. case reflect.Chan:
  144. if !reflect.DeepEqual(a.Interface(), b.Interface()) {
  145. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  146. }
  147. return nil
  148. case reflect.Slice:
  149. if reflect.DeepEqual(a, b) {
  150. return nil
  151. }
  152. lA, lB := a.Len(), b.Len()
  153. l := lA
  154. if lB < lA {
  155. l = lB
  156. }
  157. for i := 0; i < l; i++ {
  158. if !reflect.DeepEqual(a.Index(i), b.Index(i)) {
  159. return objectReflectDiff(path.Index(i), a.Index(i), b.Index(i))
  160. }
  161. }
  162. var diffs []diff
  163. for i := l; i < lA; i++ {
  164. diffs = append(diffs, diff{path: path.Index(i), a: a.Index(i), b: nil})
  165. }
  166. for i := l; i < lB; i++ {
  167. diffs = append(diffs, diff{path: path.Index(i), a: nil, b: b.Index(i)})
  168. }
  169. return diffs
  170. case reflect.Map:
  171. if reflect.DeepEqual(a, b) {
  172. return nil
  173. }
  174. aKeys := make(map[interface{}]interface{})
  175. for _, key := range a.MapKeys() {
  176. aKeys[key.Interface()] = a.MapIndex(key).Interface()
  177. }
  178. var missing []diff
  179. for _, key := range b.MapKeys() {
  180. if _, ok := aKeys[key.Interface()]; ok {
  181. delete(aKeys, key.Interface())
  182. if reflect.DeepEqual(a.MapIndex(key).Interface(), b.MapIndex(key).Interface()) {
  183. continue
  184. }
  185. missing = append(missing, objectReflectDiff(path.Key(fmt.Sprintf("%s", key.Interface())), a.MapIndex(key), b.MapIndex(key))...)
  186. continue
  187. }
  188. missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key.Interface())), a: nil, b: b.MapIndex(key).Interface()})
  189. }
  190. for key, value := range aKeys {
  191. missing = append(missing, diff{path: path.Key(fmt.Sprintf("%s", key)), a: value, b: nil})
  192. }
  193. sort.Sort(orderedDiffs(missing))
  194. return missing
  195. default:
  196. if reflect.DeepEqual(a.Interface(), b.Interface()) {
  197. return nil
  198. }
  199. if !a.CanInterface() {
  200. return []diff{{path: path, a: fmt.Sprintf("%#v", a), b: fmt.Sprintf("%#v", b)}}
  201. }
  202. return []diff{{path: path, a: a.Interface(), b: b.Interface()}}
  203. }
  204. }
  205. // ObjectGoPrintSideBySide prints a and b as textual dumps side by side,
  206. // enabling easy visual scanning for mismatches.
  207. func ObjectGoPrintSideBySide(a, b interface{}) string {
  208. s := spew.ConfigState{
  209. Indent: " ",
  210. // Extra deep spew.
  211. DisableMethods: true,
  212. }
  213. sA := s.Sdump(a)
  214. sB := s.Sdump(b)
  215. linesA := strings.Split(sA, "\n")
  216. linesB := strings.Split(sB, "\n")
  217. width := 0
  218. for _, s := range linesA {
  219. l := len(s)
  220. if l > width {
  221. width = l
  222. }
  223. }
  224. for _, s := range linesB {
  225. l := len(s)
  226. if l > width {
  227. width = l
  228. }
  229. }
  230. buf := &bytes.Buffer{}
  231. w := tabwriter.NewWriter(buf, width, 0, 1, ' ', 0)
  232. max := len(linesA)
  233. if len(linesB) > max {
  234. max = len(linesB)
  235. }
  236. for i := 0; i < max; i++ {
  237. var a, b string
  238. if i < len(linesA) {
  239. a = linesA[i]
  240. }
  241. if i < len(linesB) {
  242. b = linesB[i]
  243. }
  244. fmt.Fprintf(w, "%s\t%s\n", a, b)
  245. }
  246. w.Flush()
  247. return buf.String()
  248. }