Debian Codegraph @

v5/patch.go

raw symbols SCIP
1 package jsonpatch
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "strconv"
8 "strings"
9
10 "github.com/pkg/errors"
11 )
12
13 const (
14 eRaw = iota
15 eDoc
16 eAry
17 )
18
19 var (
20 // SupportNegativeIndices decides whether to support non-standard practice of
21 // allowing negative indices to mean indices starting at the end of an array.
22 // Default to true.
23 SupportNegativeIndices bool = true
24 // AccumulatedCopySizeLimit limits the total size increase in bytes caused by
25 // "copy" operations in a patch.
26 AccumulatedCopySizeLimit int64 = 0
27 startObject = json.Delim('{')
28 endObject = json.Delim('}')
29 startArray = json.Delim('[')
30 endArray = json.Delim(']')
31 )
32
33 var (
34 ErrTestFailed = errors.New("test failed")
35 ErrMissing = errors.New("missing value")
36 ErrUnknownType = errors.New("unknown object type")
37 ErrInvalid = errors.New("invalid state detected")
38 ErrInvalidIndex = errors.New("invalid index referenced")
39
40 rawJSONArray = []byte("[]")
41 rawJSONObject = []byte("{}")
42 rawJSONNull = []byte("null")
43 )
44
45 type lazyNode struct {
46 raw *json.RawMessage
47 doc *partialDoc
48 ary partialArray
49 which int
50 }
51
52 // Operation is a single JSON-Patch step, such as a single 'add' operation.
53 type Operation map[string]*json.RawMessage
54
55 // Patch is an ordered collection of Operations.
56 type Patch []Operation
57
58 type partialDoc struct {
59 keys []string
60 obj map[string]*lazyNode
61 }
62
63 type partialArray []*lazyNode
64
65 type container interface {
66 get(key string, options *ApplyOptions) (*lazyNode, error)
67 set(key string, val *lazyNode, options *ApplyOptions) error
68 add(key string, val *lazyNode, options *ApplyOptions) error
69 remove(key string, options *ApplyOptions) error
70 }
71
72 // ApplyOptions specifies options for calls to ApplyWithOptions.
73 // Use NewApplyOptions to obtain default values for ApplyOptions.
74 type ApplyOptions struct {
75 // SupportNegativeIndices decides whether to support non-standard practice of
76 // allowing negative indices to mean indices starting at the end of an array.
77 // Default to true.
78 SupportNegativeIndices bool
79 // AccumulatedCopySizeLimit limits the total size increase in bytes caused by
80 // "copy" operations in a patch.
81 AccumulatedCopySizeLimit int64
82 // AllowMissingPathOnRemove indicates whether to fail "remove" operations when the target path is missing.
83 // Default to false.
84 AllowMissingPathOnRemove bool
85 // EnsurePathExistsOnAdd instructs json-patch to recursively create the missing parts of path on "add" operation.
86 // Default to false.
87 EnsurePathExistsOnAdd bool
88 }
89
90 // NewApplyOptions creates a default set of options for calls to ApplyWithOptions.
91 func NewApplyOptions() *ApplyOptions {
92 return &ApplyOptions{
93 SupportNegativeIndices: SupportNegativeIndices,
94 AccumulatedCopySizeLimit: AccumulatedCopySizeLimit,
95 AllowMissingPathOnRemove: false,
96 EnsurePathExistsOnAdd: false,
97 }
98 }
99
100 func newLazyNode(raw *json.RawMessage) *lazyNode {
101 return &lazyNode{raw: raw, doc: nil, ary: nil, which: eRaw}
102 }
103
104 func newRawMessage(buf []byte) *json.RawMessage {
105 ra := make(json.RawMessage, len(buf))
106 copy(ra, buf)
107 return &ra
108 }
109
110 func (n *lazyNode) MarshalJSON() ([]byte, error) {
111 switch n.which {
112 case eRaw:
113 return json.Marshal(n.raw)
114 case eDoc:
115 return json.Marshal(n.doc)
116 case eAry:
117 return json.Marshal(n.ary)
118 default:
119 return nil, ErrUnknownType
120 }
121 }
122
123 func (n *lazyNode) UnmarshalJSON(data []byte) error {
124 dest := make(json.RawMessage, len(data))
125 copy(dest, data)
126 n.raw = &dest
127 n.which = eRaw
128 return nil
129 }
130
131 func (n *partialDoc) MarshalJSON() ([]byte, error) {
132 var buf bytes.Buffer
133 if _, err := buf.WriteString("{"); err != nil {
134 return nil, err
135 }
136 for i, k := range n.keys {
137 if i > 0 {
138 if _, err := buf.WriteString(", "); err != nil {
139 return nil, err
140 }
141 }
142 key, err := json.Marshal(k)
143 if err != nil {
144 return nil, err
145 }
146 if _, err := buf.Write(key); err != nil {
147 return nil, err
148 }
149 if _, err := buf.WriteString(": "); err != nil {
150 return nil, err
151 }
152 value, err := json.Marshal(n.obj[k])
153 if err != nil {
154 return nil, err
155 }
156 if _, err := buf.Write(value); err != nil {
157 return nil, err
158 }
159 }
160 if _, err := buf.WriteString("}"); err != nil {
161 return nil, err
162 }
163 return buf.Bytes(), nil
164 }
165
166 type syntaxError struct {
167 msg string
168 }
169
170 func (err *syntaxError) Error() string {
171 return err.msg
172 }
173
174 func (n *partialDoc) UnmarshalJSON(data []byte) error {
175 if err := json.Unmarshal(data, &n.obj); err != nil {
176 return err
177 }
178 buffer := bytes.NewBuffer(data)
179 d := json.NewDecoder(buffer)
180 if t, err := d.Token(); err != nil {
181 return err
182 } else if t != startObject {
183 return &syntaxError{fmt.Sprintf("unexpected JSON token in document node: %v", t)}
184 }
185 for d.More() {
186 k, err := d.Token()
187 if err != nil {
188 return err
189 }
190 key, ok := k.(string)
191 if !ok {
192 return &syntaxError{fmt.Sprintf("unexpected JSON token as document node key: %s", k)}
193 }
194 if err := skipValue(d); err != nil {
195 return err
196 }
197 n.keys = append(n.keys, key)
198 }
199 return nil
200 }
201
202 func skipValue(d *json.Decoder) error {
203 t, err := d.Token()
204 if err != nil {
205 return err
206 }
207 if t != startObject && t != startArray {
208 return nil
209 }
210 for d.More() {
211 if t == startObject {
212 // consume key token
213 if _, err := d.Token(); err != nil {
214 return err
215 }
216 }
217 if err := skipValue(d); err != nil {
218 return err
219 }
220 }
221 end, err := d.Token()
222 if err != nil {
223 return err
224 }
225 if t == startObject && end != endObject {
226 return &syntaxError{msg: "expected close object token"}
227 }
228 if t == startArray && end != endArray {
229 return &syntaxError{msg: "expected close object token"}
230 }
231 return nil
232 }
233
234 func deepCopy(src *lazyNode) (*lazyNode, int, error) {
235 if src == nil {
236 return nil, 0, nil
237 }
238 a, err := src.MarshalJSON()
239 if err != nil {
240 return nil, 0, err
241 }
242 sz := len(a)
243 return newLazyNode(newRawMessage(a)), sz, nil
244 }
245
246 func (n *lazyNode) intoDoc() (*partialDoc, error) {
247 if n.which == eDoc {
248 return n.doc, nil
249 }
250
251 if n.raw == nil {
252 return nil, ErrInvalid
253 }
254
255 err := json.Unmarshal(*n.raw, &n.doc)
256
257 if err != nil {
258 return nil, err
259 }
260
261 n.which = eDoc
262 return n.doc, nil
263 }
264
265 func (n *lazyNode) intoAry() (*partialArray, error) {
266 if n.which == eAry {
267 return &n.ary, nil
268 }
269
270 if n.raw == nil {
271 return nil, ErrInvalid
272 }
273
274 err := json.Unmarshal(*n.raw, &n.ary)
275
276 if err != nil {
277 return nil, err
278 }
279
280 n.which = eAry
281 return &n.ary, nil
282 }
283
284 func (n *lazyNode) compact() []byte {
285 buf := &bytes.Buffer{}
286
287 if n.raw == nil {
288 return nil
289 }
290
291 err := json.Compact(buf, *n.raw)
292
293 if err != nil {
294 return *n.raw
295 }
296
297 return buf.Bytes()
298 }
299
300 func (n *lazyNode) tryDoc() bool {
301 if n.raw == nil {
302 return false
303 }
304
305 err := json.Unmarshal(*n.raw, &n.doc)
306
307 if err != nil {
308 return false
309 }
310
311 n.which = eDoc
312 return true
313 }
314
315 func (n *lazyNode) tryAry() bool {
316 if n.raw == nil {
317 return false
318 }
319
320 err := json.Unmarshal(*n.raw, &n.ary)
321
322 if err != nil {
323 return false
324 }
325
326 n.which = eAry
327 return true
328 }
329
330 func (n *lazyNode) equal(o *lazyNode) bool {
331 if n.which == eRaw {
332 if !n.tryDoc() && !n.tryAry() {
333 if o.which != eRaw {
334 return false
335 }
336
337 return bytes.Equal(n.compact(), o.compact())
338 }
339 }
340
341 if n.which == eDoc {
342 if o.which == eRaw {
343 if !o.tryDoc() {
344 return false
345 }
346 }
347
348 if o.which != eDoc {
349 return false
350 }
351
352 if len(n.doc.obj) != len(o.doc.obj) {
353 return false
354 }
355
356 for k, v := range n.doc.obj {
357 ov, ok := o.doc.obj[k]
358
359 if !ok {
360 return false
361 }
362
363 if (v == nil) != (ov == nil) {
364 return false
365 }
366
367 if v == nil && ov == nil {
368 continue
369 }
370
371 if !v.equal(ov) {
372 return false
373 }
374 }
375
376 return true
377 }
378
379 if o.which != eAry && !o.tryAry() {
380 return false
381 }
382
383 if len(n.ary) != len(o.ary) {
384 return false
385 }
386
387 for idx, val := range n.ary {
388 if !val.equal(o.ary[idx]) {
389 return false
390 }
391 }
392
393 return true
394 }
395
396 // Kind reads the "op" field of the Operation.
397 func (o Operation) Kind() string {
398 if obj, ok := o["op"]; ok && obj != nil {
399 var op string
400
401 err := json.Unmarshal(*obj, &op)
402
403 if err != nil {
404 return "unknown"
405 }
406
407 return op
408 }
409
410 return "unknown"
411 }
412
413 // Path reads the "path" field of the Operation.
414 func (o Operation) Path() (string, error) {
415 if obj, ok := o["path"]; ok && obj != nil {
416 var op string
417
418 err := json.Unmarshal(*obj, &op)
419
420 if err != nil {
421 return "unknown", err
422 }
423
424 return op, nil
425 }
426
427 return "unknown", errors.Wrapf(ErrMissing, "operation missing path field")
428 }
429
430 // From reads the "from" field of the Operation.
431 func (o Operation) From() (string, error) {
432 if obj, ok := o["from"]; ok && obj != nil {
433 var op string
434
435 err := json.Unmarshal(*obj, &op)
436
437 if err != nil {
438 return "unknown", err
439 }
440
441 return op, nil
442 }
443
444 return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field")
445 }
446
447 func (o Operation) value() *lazyNode {
448 if obj, ok := o["value"]; ok {
449 return newLazyNode(obj)
450 }
451
452 return nil
453 }
454
455 // ValueInterface decodes the operation value into an interface.
456 func (o Operation) ValueInterface() (interface{}, error) {
457 if obj, ok := o["value"]; ok {
458 if obj == nil {
459 return nil, nil
460 }
461
462 var v interface{}
463
464 err := json.Unmarshal(*obj, &v)
465
466 if err != nil {
467 return nil, err
468 }
469
470 return v, nil
471 }
472
473 return nil, errors.Wrapf(ErrMissing, "operation, missing value field")
474 }
475
476 func isArray(buf []byte) bool {
477 Loop:
478 for _, c := range buf {
479 switch c {
480 case ' ':
481 case '\n':
482 case '\t':
483 continue
484 case '[':
485 return true
486 default:
487 break Loop
488 }
489 }
490
491 return false
492 }
493
494 func findObject(pd *container, path string, options *ApplyOptions) (container, string) {
495 doc := *pd
496
497 split := strings.Split(path, "/")
498
499 if len(split) < 2 {
500 return nil, ""
501 }
502
503 parts := split[1 : len(split)-1]
504
505 key := split[len(split)-1]
506
507 var err error
508
509 for _, part := range parts {
510
511 next, ok := doc.get(decodePatchKey(part), options)
512
513 if next == nil || ok != nil {
514 return nil, ""
515 }
516
517 if isArray(*next.raw) {
518 doc, err = next.intoAry()
519
520 if err != nil {
521 return nil, ""
522 }
523 } else {
524 doc, err = next.intoDoc()
525
526 if err != nil {
527 return nil, ""
528 }
529 }
530 }
531
532 return doc, decodePatchKey(key)
533 }
534
535 func (d *partialDoc) set(key string, val *lazyNode, options *ApplyOptions) error {
536 found := false
537 for _, k := range d.keys {
538 if k == key {
539 found = true
540 break
541 }
542 }
543 if !found {
544 d.keys = append(d.keys, key)
545 }
546 d.obj[key] = val
547 return nil
548 }
549
550 func (d *partialDoc) add(key string, val *lazyNode, options *ApplyOptions) error {
551 return d.set(key, val, options)
552 }
553
554 func (d *partialDoc) get(key string, options *ApplyOptions) (*lazyNode, error) {
555 v, ok := d.obj[key]
556 if !ok {
557 return v, errors.Wrapf(ErrMissing, "unable to get nonexistent key: %s", key)
558 }
559 return v, nil
560 }
561
562 func (d *partialDoc) remove(key string, options *ApplyOptions) error {
563 _, ok := d.obj[key]
564 if !ok {
565 if options.AllowMissingPathOnRemove {
566 return nil
567 }
568 return errors.Wrapf(ErrMissing, "unable to remove nonexistent key: %s", key)
569 }
570 idx := -1
571 for i, k := range d.keys {
572 if k == key {
573 idx = i
574 break
575 }
576 }
577 d.keys = append(d.keys[0:idx], d.keys[idx+1:]...)
578 delete(d.obj, key)
579 return nil
580 }
581
582 // set should only be used to implement the "replace" operation, so "key" must
583 // be an already existing index in "d".
584 func (d *partialArray) set(key string, val *lazyNode, options *ApplyOptions) error {
585 idx, err := strconv.Atoi(key)
586 if err != nil {
587 return err
588 }
589
590 if idx < 0 {
591 if !options.SupportNegativeIndices {
592 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
593 }
594 if idx < -len(*d) {
595 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
596 }
597 idx += len(*d)
598 }
599
600 (*d)[idx] = val
601 return nil
602 }
603
604 func (d *partialArray) add(key string, val *lazyNode, options *ApplyOptions) error {
605 if key == "-" {
606 *d = append(*d, val)
607 return nil
608 }
609
610 idx, err := strconv.Atoi(key)
611 if err != nil {
612 return errors.Wrapf(err, "value was not a proper array index: '%s'", key)
613 }
614
615 sz := len(*d) + 1
616
617 ary := make([]*lazyNode, sz)
618
619 cur := *d
620
621 if idx >= len(ary) {
622 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
623 }
624
625 if idx < 0 {
626 if !options.SupportNegativeIndices {
627 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
628 }
629 if idx < -len(ary) {
630 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
631 }
632 idx += len(ary)
633 }
634
635 copy(ary[0:idx], cur[0:idx])
636 ary[idx] = val
637 copy(ary[idx+1:], cur[idx:])
638
639 *d = ary
640 return nil
641 }
642
643 func (d *partialArray) get(key string, options *ApplyOptions) (*lazyNode, error) {
644 idx, err := strconv.Atoi(key)
645
646 if err != nil {
647 return nil, err
648 }
649
650 if idx < 0 {
651 if !options.SupportNegativeIndices {
652 return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
653 }
654 if idx < -len(*d) {
655 return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
656 }
657 idx += len(*d)
658 }
659
660 if idx >= len(*d) {
661 return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
662 }
663
664 return (*d)[idx], nil
665 }
666
667 func (d *partialArray) remove(key string, options *ApplyOptions) error {
668 idx, err := strconv.Atoi(key)
669 if err != nil {
670 return err
671 }
672
673 cur := *d
674
675 if idx >= len(cur) {
676 if options.AllowMissingPathOnRemove {
677 return nil
678 }
679 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
680 }
681
682 if idx < 0 {
683 if !options.SupportNegativeIndices {
684 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
685 }
686 if idx < -len(cur) {
687 if options.AllowMissingPathOnRemove {
688 return nil
689 }
690 return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
691 }
692 idx += len(cur)
693 }
694
695 ary := make([]*lazyNode, len(cur)-1)
696
697 copy(ary[0:idx], cur[0:idx])
698 copy(ary[idx:], cur[idx+1:])
699
700 *d = ary
701 return nil
702 }
703
704 func (p Patch) add(doc *container, op Operation, options *ApplyOptions) error {
705 path, err := op.Path()
706 if err != nil {
707 return errors.Wrapf(ErrMissing, "add operation failed to decode path")
708 }
709
710 if options.EnsurePathExistsOnAdd {
711 err = ensurePathExists(doc, path, options)
712
713 if err != nil {
714 return err
715 }
716 }
717
718 con, key := findObject(doc, path, options)
719
720 if con == nil {
721 return errors.Wrapf(ErrMissing, "add operation does not apply: doc is missing path: \"%s\"", path)
722 }
723
724 err = con.add(key, op.value(), options)
725 if err != nil {
726 return errors.Wrapf(err, "error in add for path: '%s'", path)
727 }
728
729 return nil
730 }
731
732 // Given a document and a path to a key, walk the path and create all missing elements
733 // creating objects and arrays as needed.
734 func ensurePathExists(pd *container, path string, options *ApplyOptions) error {
735 doc := *pd
736
737 var err error
738 var arrIndex int
739
740 split := strings.Split(path, "/")
741
742 if len(split) < 2 {
743 return nil
744 }
745
746 parts := split[1:]
747
748 for pi, part := range parts {
749
750 // Have we reached the key part of the path?
751 // If yes, we're done.
752 if pi == len(parts)-1 {
753 return nil
754 }
755
756 target, ok := doc.get(decodePatchKey(part), options)
757
758 if target == nil || ok != nil {
759
760 // If the current container is an array which has fewer elements than our target index,
761 // pad the current container with nulls.
762 if arrIndex, err = strconv.Atoi(part); err == nil {
763 pa, ok := doc.(*partialArray)
764
765 if ok && arrIndex >= len(*pa)+1 {
766 // Pad the array with null values up to the required index.
767 for i := len(*pa); i <= arrIndex-1; i++ {
768 doc.add(strconv.Itoa(i), newLazyNode(newRawMessage(rawJSONNull)), options)
769 }
770 }
771 }
772
773 // Check if the next part is a numeric index or "-".
774 // If yes, then create an array, otherwise, create an object.
775 if arrIndex, err = strconv.Atoi(parts[pi+1]); err == nil || parts[pi+1] == "-" {
776 if arrIndex < 0 {
777
778 if !options.SupportNegativeIndices {
779 return errors.Wrapf(ErrInvalidIndex, "Unable to ensure path for invalid index: %d", arrIndex)
780 }
781
782 if arrIndex < -1 {
783 return errors.Wrapf(ErrInvalidIndex, "Unable to ensure path for negative index other than -1: %d", arrIndex)
784 }
785
786 arrIndex = 0
787 }
788
789 newNode := newLazyNode(newRawMessage(rawJSONArray))
790 doc.add(part, newNode, options)
791 doc, _ = newNode.intoAry()
792
793 // Pad the new array with null values up to the required index.
794 for i := 0; i < arrIndex; i++ {
795 doc.add(strconv.Itoa(i), newLazyNode(newRawMessage(rawJSONNull)), options)
796 }
797 } else {
798 newNode := newLazyNode(newRawMessage(rawJSONObject))
799
800 doc.add(part, newNode, options)
801 doc, _ = newNode.intoDoc()
802 }
803 } else {
804 if isArray(*target.raw) {
805 doc, err = target.intoAry()
806
807 if err != nil {
808 return err
809 }
810 } else {
811 doc, err = target.intoDoc()
812
813 if err != nil {
814 return err
815 }
816 }
817 }
818 }
819
820 return nil
821 }
822
823 func validateOperation(op Operation) error {
824 switch op.Kind() {
825 case "add", "replace":
826 if _, err := op.ValueInterface(); err != nil {
827 return errors.Wrapf(err, "failed to decode 'value'")
828 }
829 case "move", "copy":
830 if _, err := op.From(); err != nil {
831 return errors.Wrapf(err, "failed to decode 'from'")
832 }
833 case "remove", "test":
834 default:
835 return fmt.Errorf("unsupported operation")
836 }
837
838 if _, err := op.Path(); err != nil {
839 return errors.Wrapf(err, "failed to decode 'path'")
840 }
841
842 return nil
843 }
844
845 func validatePatch(p Patch) error {
846 for _, op := range p {
847 if err := validateOperation(op); err != nil {
848 opData, infoErr := json.Marshal(op)
849 if infoErr != nil {
850 return errors.Wrapf(err, "invalid operation")
851 }
852
853 return errors.Wrapf(err, "invalid operation %s", opData)
854 }
855 }
856
857 return nil
858 }
859
860 func (p Patch) remove(doc *container, op Operation, options *ApplyOptions) error {
861 path, err := op.Path()
862 if err != nil {
863 return errors.Wrapf(ErrMissing, "remove operation failed to decode path")
864 }
865
866 con, key := findObject(doc, path, options)
867
868 if con == nil {
869 if options.AllowMissingPathOnRemove {
870 return nil
871 }
872 return errors.Wrapf(ErrMissing, "remove operation does not apply: doc is missing path: \"%s\"", path)
873 }
874
875 err = con.remove(key, options)
876 if err != nil {
877 return errors.Wrapf(err, "error in remove for path: '%s'", path)
878 }
879
880 return nil
881 }
882
883 func (p Patch) replace(doc *container, op Operation, options *ApplyOptions) error {
884 path, err := op.Path()
885 if err != nil {
886 return errors.Wrapf(err, "replace operation failed to decode path")
887 }
888
889 if path == "" {
890 val := op.value()
891
892 if val.which == eRaw {
893 if !val.tryDoc() {
894 if !val.tryAry() {
895 return errors.Wrapf(err, "replace operation value must be object or array")
896 }
897 }
898 }
899
900 switch val.which {
901 case eAry:
902 *doc = &val.ary
903 case eDoc:
904 *doc = val.doc
905 case eRaw:
906 return errors.Wrapf(err, "replace operation hit impossible case")
907 }
908
909 return nil
910 }
911
912 con, key := findObject(doc, path, options)
913
914 if con == nil {
915 return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing path: %s", path)
916 }
917
918 _, ok := con.get(key, options)
919 if ok != nil {
920 return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing key: %s", path)
921 }
922
923 err = con.set(key, op.value(), options)
924 if err != nil {
925 return errors.Wrapf(err, "error in remove for path: '%s'", path)
926 }
927
928 return nil
929 }
930
931 func (p Patch) move(doc *container, op Operation, options *ApplyOptions) error {
932 from, err := op.From()
933 if err != nil {
934 return errors.Wrapf(err, "move operation failed to decode from")
935 }
936
937 con, key := findObject(doc, from, options)
938
939 if con == nil {
940 return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing from path: %s", from)
941 }
942
943 val, err := con.get(key, options)
944 if err != nil {
945 return errors.Wrapf(err, "error in move for path: '%s'", key)
946 }
947
948 err = con.remove(key, options)
949 if err != nil {
950 return errors.Wrapf(err, "error in move for path: '%s'", key)
951 }
952
953 path, err := op.Path()
954 if err != nil {
955 return errors.Wrapf(err, "move operation failed to decode path")
956 }
957
958 con, key = findObject(doc, path, options)
959
960 if con == nil {
961 return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing destination path: %s", path)
962 }
963
964 err = con.add(key, val, options)
965 if err != nil {
966 return errors.Wrapf(err, "error in move for path: '%s'", path)
967 }
968
969 return nil
970 }
971
972 func (p Patch) test(doc *container, op Operation, options *ApplyOptions) error {
973 path, err := op.Path()
974 if err != nil {
975 return errors.Wrapf(err, "test operation failed to decode path")
976 }
977
978 if path == "" {
979 var self lazyNode
980
981 switch sv := (*doc).(type) {
982 case *partialDoc:
983 self.doc = sv
984 self.which = eDoc
985 case *partialArray:
986 self.ary = *sv
987 self.which = eAry
988 }
989
990 if self.equal(op.value()) {
991 return nil
992 }
993
994 return errors.Wrapf(ErrTestFailed, "testing value %s failed", path)
995 }
996
997 con, key := findObject(doc, path, options)
998
999 if con == nil {
1000 return errors.Wrapf(ErrMissing, "test operation does not apply: is missing path: %s", path)
1001 }
1002
1003 val, err := con.get(key, options)
1004 if err != nil && errors.Cause(err) != ErrMissing {
1005 return errors.Wrapf(err, "error in test for path: '%s'", path)
1006 }
1007
1008 if val == nil {
1009 if op.value() == nil || op.value().raw == nil {
1010 return nil
1011 }
1012 return errors.Wrapf(ErrTestFailed, "testing value %s failed", path)
1013 } else if op.value() == nil {
1014 return errors.Wrapf(ErrTestFailed, "testing value %s failed", path)
1015 }
1016
1017 if val.equal(op.value()) {
1018 return nil
1019 }
1020
1021 return errors.Wrapf(ErrTestFailed, "testing value %s failed", path)
1022 }
1023
1024 func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64, options *ApplyOptions) error {
1025 from, err := op.From()
1026 if err != nil {
1027 return errors.Wrapf(err, "copy operation failed to decode from")
1028 }
1029
1030 con, key := findObject(doc, from, options)
1031
1032 if con == nil {
1033 return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing from path: %s", from)
1034 }
1035
1036 val, err := con.get(key, options)
1037 if err != nil {
1038 return errors.Wrapf(err, "error in copy for from: '%s'", from)
1039 }
1040
1041 path, err := op.Path()
1042 if err != nil {
1043 return errors.Wrapf(ErrMissing, "copy operation failed to decode path")
1044 }
1045
1046 con, key = findObject(doc, path, options)
1047
1048 if con == nil {
1049 return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing destination path: %s", path)
1050 }
1051
1052 valCopy, sz, err := deepCopy(val)
1053 if err != nil {
1054 return errors.Wrapf(err, "error while performing deep copy")
1055 }
1056
1057 (*accumulatedCopySize) += int64(sz)
1058 if options.AccumulatedCopySizeLimit > 0 && *accumulatedCopySize > options.AccumulatedCopySizeLimit {
1059 return NewAccumulatedCopySizeError(options.AccumulatedCopySizeLimit, *accumulatedCopySize)
1060 }
1061
1062 err = con.add(key, valCopy, options)
1063 if err != nil {
1064 return errors.Wrapf(err, "error while adding value during copy")
1065 }
1066
1067 return nil
1068 }
1069
1070 // Equal indicates if 2 JSON documents have the same structural equality.
1071 func Equal(a, b []byte) bool {
1072 la := newLazyNode(newRawMessage(a))
1073 lb := newLazyNode(newRawMessage(b))
1074
1075 return la.equal(lb)
1076 }
1077
1078 // DecodePatch decodes the passed JSON document as an RFC 6902 patch.
1079 func DecodePatch(buf []byte) (Patch, error) {
1080 var p Patch
1081
1082 err := json.Unmarshal(buf, &p)
1083
1084 if err != nil {
1085 return nil, err
1086 }
1087
1088 if err := validatePatch(p); err != nil {
1089 return nil, err
1090 }
1091
1092 return p, nil
1093 }
1094
1095 // Apply mutates a JSON document according to the patch, and returns the new
1096 // document.
1097 func (p Patch) Apply(doc []byte) ([]byte, error) {
1098 return p.ApplyWithOptions(doc, NewApplyOptions())
1099 }
1100
1101 // ApplyWithOptions mutates a JSON document according to the patch and the passed in ApplyOptions.
1102 // It returns the new document.
1103 func (p Patch) ApplyWithOptions(doc []byte, options *ApplyOptions) ([]byte, error) {
1104 return p.ApplyIndentWithOptions(doc, "", options)
1105 }
1106
1107 // ApplyIndent mutates a JSON document according to the patch, and returns the new
1108 // document indented.
1109 func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) {
1110 return p.ApplyIndentWithOptions(doc, indent, NewApplyOptions())
1111 }
1112
1113 // ApplyIndentWithOptions mutates a JSON document according to the patch and the passed in ApplyOptions.
1114 // It returns the new document indented.
1115 func (p Patch) ApplyIndentWithOptions(doc []byte, indent string, options *ApplyOptions) ([]byte, error) {
1116 if len(doc) == 0 {
1117 return doc, nil
1118 }
1119
1120 var pd container
1121 if doc[0] == '[' {
1122 pd = &partialArray{}
1123 } else {
1124 pd = &partialDoc{}
1125 }
1126
1127 err := json.Unmarshal(doc, pd)
1128
1129 if err != nil {
1130 return nil, err
1131 }
1132
1133 err = nil
1134
1135 var accumulatedCopySize int64
1136
1137 for _, op := range p {
1138 switch op.Kind() {
1139 case "add":
1140 err = p.add(&pd, op, options)
1141 case "remove":
1142 err = p.remove(&pd, op, options)
1143 case "replace":
1144 err = p.replace(&pd, op, options)
1145 case "move":
1146 err = p.move(&pd, op, options)
1147 case "test":
1148 err = p.test(&pd, op, options)
1149 case "copy":
1150 err = p.copy(&pd, op, &accumulatedCopySize, options)
1151 default:
1152 err = fmt.Errorf("Unexpected kind: %s", op.Kind())
1153 }
1154
1155 if err != nil {
1156 return nil, err
1157 }
1158 }
1159
1160 if indent != "" {
1161 return json.MarshalIndent(pd, "", indent)
1162 }
1163
1164 return json.Marshal(pd)
1165 }
1166
1167 // From http://tools.ietf.org/html/rfc6901#section-4 :
1168 //
1169 // Evaluation of each reference token begins by decoding any escaped
1170 // character sequence. This is performed by first transforming any
1171 // occurrence of the sequence '~1' to '/', and then transforming any
1172 // occurrence of the sequence '~0' to '~'.
1173
1174 var (
1175 rfc6901Decoder = strings.NewReplacer("~1", "/", "~0", "~")
1176 )
1177
1178 func decodePatchKey(k string) string {
1179 return rfc6901Decoder.Replace(k)
1180 }