Skip to content

Commit

Permalink
Handle applying to the whole doc. Fixes #142
Browse files Browse the repository at this point in the history
  • Loading branch information
evanphx committed Oct 20, 2021
1 parent df14171 commit 5561fe0
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
42 changes: 42 additions & 0 deletions v5/patch.go
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,29 @@ func (p Patch) replace(doc *container, op Operation, options *ApplyOptions) erro
return errors.Wrapf(err, "replace operation failed to decode path")
}

if path == "" {
val := op.value()

if val.which == eRaw {
if !val.tryDoc() {
if !val.tryAry() {
return errors.Wrapf(err, "replace operation value must be object or array")
}
}
}

switch val.which {
case eAry:
*doc = &val.ary
case eDoc:
*doc = val.doc
case eRaw:
return errors.Wrapf(err, "replace operation hit impossible case")
}

return nil
}

con, key := findObject(doc, path, options)

if con == nil {
Expand Down Expand Up @@ -911,6 +934,25 @@ func (p Patch) test(doc *container, op Operation, options *ApplyOptions) error {
return errors.Wrapf(err, "test operation failed to decode path")
}

if path == "" {
var self lazyNode

switch sv := (*doc).(type) {
case *partialDoc:
self.doc = sv
self.which = eDoc
case *partialArray:
self.ary = *sv
self.which = eAry
}

if self.equal(op.value()) {
return nil
}

return errors.Wrapf(ErrTestFailed, "testing value %s failed", path)
}

con, key := findObject(doc, path, options)

if con == nil {
Expand Down
31 changes: 31 additions & 0 deletions v5/patch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,37 @@ var Cases = []Case{
false,
true,
},
{
`{
"id": "00000000-0000-0000-0000-000000000000",
"parentID": "00000000-0000-0000-0000-000000000000"
}`,
`[
{
"op": "test",
"path": "",
"value": {
"id": "00000000-0000-0000-0000-000000000000",
"parentID": "00000000-0000-0000-0000-000000000000"
}
},
{
"op": "replace",
"path": "",
"value": {
"id": "759981e8-ec68-4639-a83e-513225914ecb",
"originalID": "bar",
"parentID": "00000000-0000-0000-0000-000000000000"
}
}
]`,
`{
"id" : "759981e8-ec68-4639-a83e-513225914ecb",
"originalID" : "bar",
"parentID" : "00000000-0000-0000-0000-000000000000"
}`,
false, true,
},
}

type BadCase struct {
Expand Down

0 comments on commit 5561fe0

Please sign in to comment.