internal/diff: fix printing and top-level diffs
Print concrete values: before %-v was used, which would
print conjuncts, not evaluated expressions.
Top-level diffs were awkward, as it would not return an edit
script and the user would have to do their own printing.
This fixes that.
TODO: modify the API to not return the kind, only the
EditScript.
Change-Id: I7c9d0322fb5e6dac0f4668f14de8ae76bb614823
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/9342
Reviewed-by: CUE cueckoo <cueckoo@gmail.com>
Reviewed-by: Paul Jolly <paul@myitcv.org.uk>
diff --git a/internal/diff/diff.go b/internal/diff/diff.go
index d9c29ed..64db8ca 100644
--- a/internal/diff/diff.go
+++ b/internal/diff/diff.go
@@ -34,6 +34,8 @@
}
)
+// TODO: don't return Kind, which is always Modified or not.
+
// Diff is a shorthand for Schema.Diff.
func Diff(x, y cue.Value) (Kind, *EditScript) {
return Schema.Diff(x, y)
@@ -42,7 +44,11 @@
// Diff returns an edit script representing the difference between x and y.
func (p *Profile) Diff(x, y cue.Value) (Kind, *EditScript) {
d := differ{cfg: *p}
- return d.diffValue(x, y)
+ k, es := d.diffValue(x, y)
+ if k == Modified && es == nil {
+ es = &EditScript{x: x, y: y}
+ }
+ return k, es
}
// Kind identifies the kind of operation of an edit script.
diff --git a/internal/diff/diff_test.go b/internal/diff/diff_test.go
index 83aa395..1bfec73 100644
--- a/internal/diff/diff_test.go
+++ b/internal/diff/diff_test.go
@@ -61,6 +61,9 @@
x: `"foo"`,
y: `"bar"`,
kind: Modified,
+ diff: `- "foo",
++ "bar",
+`,
}, {
name: "basics",
x: `{
@@ -111,7 +114,7 @@
`,
kind: Modified,
diff: ` {
- ls: [2, 3, 4]
+ ls: [2,3,4]
- "foo-bar": 2
+ "foo-bar": 3
s: 4
@@ -125,7 +128,7 @@
lm2: [
- 6,
]
-+ la: [2, 3, 4]
++ la: [2,3,4]
}
`,
}, {
@@ -299,9 +302,7 @@
`,
kind: Modified,
diff: ` {
-- a: {
-- x: "hello"
-- }
+- a: {x:"hello"}
}
`,
}, {
diff --git a/internal/diff/print.go b/internal/diff/print.go
index a87832e..251d13f 100644
--- a/internal/diff/print.go
+++ b/internal/diff/print.go
@@ -98,7 +98,8 @@
case cue.ListKind:
p.printList(e)
default:
- p.printf("BadExpr")
+ p.printElem("-", e.x)
+ p.printElem("+", e.y)
}
}
@@ -194,7 +195,7 @@
func (p *printer) printValue(v cue.Value) {
// TODO: have indent option.
- s := fmt.Sprintf("%-v", v)
+ s := fmt.Sprintf("%+v", v)
io.WriteString(p, s)
}