diff --git a/pkg/operations/delete.go b/pkg/operations/delete.go index 2c63fa8..1cecf5b 100644 --- a/pkg/operations/delete.go +++ b/pkg/operations/delete.go @@ -11,7 +11,9 @@ func Delete(root types.Node, path []string, args ...any) error { node, err := root.Visit(path[0]) - if err != nil { + if err == types.ErrFieldMissing { + return nil + } else if err != nil { return err } diff --git a/pkg/operations/delete_test.go b/pkg/operations/delete_test.go new file mode 100644 index 0000000..9aaf060 --- /dev/null +++ b/pkg/operations/delete_test.go @@ -0,0 +1,46 @@ +package operations + +import ( + "testing" + + "github.com/alecthomas/assert/v2" + "github.com/can3p/sackmesser/pkg/traverse/simplejson" +) + +func TestDeleteOperation(t *testing.T) { + jstr := `{ "abc": { "def": [ 1, 2, 3 ] } }` + + examples := []struct { + description string + path []string + expected string + isErr bool + }{ + { + description: "delete existing field", + path: []string{"abc"}, + expected: `{}`, + }, + { + description: "delete missing field is fine, it was deleted already", + path: []string{"nonexistant"}, + expected: jstr, + }, + } + + for idx, ex := range examples { + node := simplejson.MustParse([]byte(jstr)) + + err := Delete(node, ex.path) + + if ex.isErr { + assert.Error(t, err, "[Ex %d - %s]", idx+1, ex.description) + continue + } + + expected := simplejson.MustParse([]byte(ex.expected)) + + assert.Equal(t, expected.Value(), node.Value(), "[Ex %d - %s]", idx+1, ex.description) + } + +} diff --git a/pkg/traverse/simplejson/simplejson.go b/pkg/traverse/simplejson/simplejson.go index 903087b..c20bd8b 100644 --- a/pkg/traverse/simplejson/simplejson.go +++ b/pkg/traverse/simplejson/simplejson.go @@ -224,6 +224,16 @@ func Parse(b []byte) (types.Node, error) { }, nil } +func MustParse(b []byte) types.Node { + n, err := Parse(b) + + if err != nil { + panic(err) + } + + return n +} + func FromNode(n types.Node) types.Node { j := n.Value()