Skip to content

Commit

Permalink
feat!: use del() function instead of assigning null for ignoring member
Browse files Browse the repository at this point in the history
  • Loading branch information
aereal committed Jan 15, 2025
1 parent 1da1991 commit db907c8
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 8 deletions.
7 changes: 3 additions & 4 deletions cmd/jsondiff/testdata/ok_with_ignore_option.stdout.txt
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
--- from.json
+++ to.json
@@ -1,7 +1,7 @@
@@ -1,6 +1,6 @@
{
"a": 1,
- "b": 2,
- "c": 3,
- "c": 3
+ "b": 1,
+ "c": 2,
"d": null
+ "c": 2
}

14 changes: 13 additions & 1 deletion diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func Diff(from, to *Input, opts ...Option) (string, error) {
switch {
case o.ignore != nil:
var err error
q := WithUpdate(o.ignore)
q := deleting(o.ignore)
fromObj, err = ModifyValue(q, fromObj)
if err != nil {
return "", fmt.Errorf("modify(lhs): %v", err)
Expand Down Expand Up @@ -186,6 +186,18 @@ func WithUpdate(query *gojq.Query) *gojq.Query {
return ret
}

func deleting(query *gojq.Query) *gojq.Query {
return &gojq.Query{
Term: &gojq.Term{
Type: gojq.TermTypeFunc,
Func: &gojq.Func{
Name: "del",
Args: []*gojq.Query{query},
},
},
}
}

var nullRhs *gojq.Query

func init() {
Expand Down
22 changes: 22 additions & 0 deletions diff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,28 @@ func Test_withUpdate(t *testing.T) {
}
}

func Test_deleting(t *testing.T) {
queries := []struct {
query string
want string
}{
{".age", "del(.age)"},
{".age, .name", "del(.age, .name)"},
{".age, .name, .meta", "del(.age, .name, .meta)"},
{".meta[]", "del(.meta[])"},
{".meta[0:-1]", "del(.meta[0:-1])"},
}
for _, c := range queries {
t.Run(c.query, func(t *testing.T) {
want := parseQuery(t, c.want)
got := deleting(parseQuery(t, c.query))
if diff := cmp.Diff(want, got); diff != "" {
t.Errorf("-want, +got:\n%s", diff)
}
})
}
}

func parseQuery(t *testing.T, q string) *gojq.Query {
t.Helper()
parsed, err := gojq.Parse(q)
Expand Down
5 changes: 2 additions & 3 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,9 @@ func ExampleDiffFromObjects_ignore() {
// Output:
// --- from
// +++ to
// @@ -2,6 +2,6 @@
// @@ -1,5 +1,5 @@
// {
// "a": 1,
// "b": null,
// "c": null,
// - "d": 4
// + "d": 3
// }
Expand Down

0 comments on commit db907c8

Please sign in to comment.