-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch.go
More file actions
406 lines (363 loc) · 12.4 KB
/
Copy pathpatch.go
File metadata and controls
406 lines (363 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Package jsonpatch implements RFC 6902 JSON Patch operations.
//
// JSON Patch defines a JSON document structure for expressing a sequence of
// operations to apply to a JSON document. This package provides two main
// capabilities:
//
// - Apply: Apply a JSON Patch document to a target JSON document
// - CreatePatch: Generate a JSON Patch by comparing two JSON documents (diff)
//
// Usage:
//
// // Apply a patch
// patched, err := jsonpatch.Apply(originalJSON, patchJSON)
//
// // Create a patch by comparing two documents
// patch, err := jsonpatch.CreatePatch(originalJSON, modifiedJSON)
package jsonpatch
import (
"encoding/json"
"fmt"
"sync"
)
// Document defines the supported document types for JSON Patch operations.
// It accepts raw JSON as []byte or string, as well as custom types with those
// underlying types (e.g., type JSONDoc []byte).
//
// All generic functions that accept Document will preserve the caller's type in
// the return value — pass a string, get a string back.
type Document interface {
~[]byte | ~string
}
// toBytes converts a Document value to []byte for internal processing.
func toBytes[D Document](d D) []byte {
return []byte(d)
}
// fromBytes converts raw JSON bytes back to the caller's Document type.
func fromBytes[D Document](b []byte) D {
return D(b)
}
// OpType represents the type of JSON Patch operation.
type OpType string
const (
// OpAdd represents the "add" operation.
OpAdd OpType = "add"
// OpRemove represents the "remove" operation.
OpRemove OpType = "remove"
// OpReplace represents the "replace" operation.
OpReplace OpType = "replace"
// OpMove represents the "move" operation.
OpMove OpType = "move"
// OpCopy represents the "copy" operation.
OpCopy OpType = "copy"
// OpTest represents the "test" operation.
OpTest OpType = "test"
)
// operationCache holds pre-parsed fields for an Operation.
// It is heap-allocated only when the operation has been validated via
// Validate or DecodePatch, so operations produced internally by CreatePatch
// carry zero extra overhead.
type operationCache struct {
parsedPath Pointer
parsedFrom Pointer
parsedValue any
parsedValueOK bool // true once parsedValue is set (distinguishes cached-nil from not-yet-cached)
mu sync.Mutex
}
// Operation represents a single JSON Patch operation as defined in RFC 6902.
type Operation struct {
// Op is the operation to perform. It MUST be one of "add", "remove",
// "replace", "move", "copy", or "test".
Op OpType `json:"op"`
// Path is a JSON Pointer (RFC 6901) string that references the target
// location where the operation is performed.
Path string `json:"path"`
// Value specifies the value to be used by the operation.
// Required for "add", "replace", and "test" operations.
Value *json.RawMessage `json:"value,omitempty"`
// From is a JSON Pointer string that references the source location.
// Required for "move" and "copy" operations.
From string `json:"from,omitempty"`
// hasPath tracks whether the "path" key was present in the original JSON.
hasPath bool
// hasFrom tracks whether the "from" key was present in the original JSON,
// distinguishing between an absent key and an explicit empty string (root pointer).
hasFrom bool
// hasValue tracks whether the "value" key was present in the original JSON,
// distinguishing between an absent key and an explicit null.
hasValue bool
// cache holds pre-parsed and pre-decoded fields when populated via
// Validate or DecodePatch. It is nil for operations that have not been
// validated (e.g., ops built by CreatePatch).
cache *operationCache
}
// UnmarshalJSON implements custom JSON unmarshaling for Operation to properly
// distinguish between an absent "value" field and a "value" field set to null.
func (o *Operation) UnmarshalJSON(data []byte) error {
// First, unmarshal into a raw map to detect key presence
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
// rejectNull returns an error if the raw JSON value is "null".
// This prevents json.Unmarshal from silently accepting null into a string.
rejectNull := func(raw json.RawMessage, field string) error {
if string(raw) == "null" {
return fmt.Errorf("invalid %q field: must be a string", field)
}
return nil
}
if opRaw, ok := raw["op"]; ok {
if err := rejectNull(opRaw, "op"); err != nil {
return err
}
var op string
if err := json.Unmarshal(opRaw, &op); err != nil {
return fmt.Errorf("invalid \"op\" field: must be a string")
}
o.Op = OpType(op)
}
if pathRaw, ok := raw["path"]; ok {
o.hasPath = true
if err := rejectNull(pathRaw, "path"); err != nil {
return err
}
var path string
if err := json.Unmarshal(pathRaw, &path); err != nil {
return fmt.Errorf("invalid \"path\" field: must be a string")
}
o.Path = path
}
if fromRaw, ok := raw["from"]; ok {
o.hasFrom = true
if err := rejectNull(fromRaw, "from"); err != nil {
return err
}
var from string
if err := json.Unmarshal(fromRaw, &from); err != nil {
return fmt.Errorf("invalid \"from\" field: must be a string")
}
o.From = from
}
if valRaw, ok := raw["value"]; ok {
o.hasValue = true
v := json.RawMessage(valRaw)
o.Value = &v
}
return nil
}
// HasValue reports whether the operation has a "value" field
// (including explicit null).
func (o Operation) HasValue() bool {
return o.hasValue || o.Value != nil
}
// HasFrom reports whether the operation has a "from" field
// (including an explicit empty string meaning root pointer).
func (o Operation) HasFrom() bool {
return o.hasFrom
}
// Validate validates the operation, checking that all required fields are
// present and that pointer strings are well-formed. It also caches parsed
// pointers and values for efficient subsequent application.
//
// For struct-literal operations (not created via NewOperation / DecodePatch),
// Validate infers field presence: if Op is a recognised operation type then
// hasPath is assumed true (root "" is a valid path for all RFC 6902 ops);
// hasFrom is inferred only when From is non-empty. For move/copy operations
// using the root pointer as the source (From == ""), use
// NewMoveOperation/NewCopyOperation so that hasFrom is set explicitly.
func (o *Operation) Validate() error {
// Infer hasPath for recognised ops when not already set (struct literal).
if !o.hasPath && o.Op != "" {
switch o.Op {
case OpAdd, OpRemove, OpReplace, OpMove, OpCopy, OpTest:
o.hasPath = true
}
}
// Infer hasFrom only when From is non-empty. Callers who intend the root
// pointer as the source must use NewMoveOperation/NewCopyOperation, which
// set hasFrom explicitly, to avoid silently treating a forgotten From field
// as a valid root-pointer source.
if !o.hasFrom && o.From != "" {
o.hasFrom = true
}
// Infer hasValue when Value is non-nil.
if !o.hasValue && o.Value != nil {
o.hasValue = true
}
return validateAndCacheOperation(o)
}
// Patch represents a JSON Patch document — an ordered list of operations.
type Patch []Operation
// NewOperation creates a new Operation with the given parameters.
// Pass a non-nil pointer to indicate the value is present (including JSON null).
// To create an operation without a value (e.g., remove), pass nil.
func NewOperation(op OpType, path string, value any) (Operation, error) {
o := Operation{
Op: op,
Path: path,
hasPath: true,
hasValue: true,
}
// Always marshal the value — json.Marshal(nil) produces "null", which is valid.
b, err := json.Marshal(value)
if err != nil {
return Operation{}, fmt.Errorf("failed to marshal value: %w", err)
}
raw := json.RawMessage(b)
o.Value = &raw
return o, nil
}
// NewMoveOperation creates a new move Operation.
func NewMoveOperation(from, path string) Operation {
return Operation{
Op: OpMove,
Path: path,
From: from,
hasPath: true,
hasFrom: true,
}
}
// NewCopyOperation creates a new copy Operation.
func NewCopyOperation(from, path string) Operation {
return Operation{
Op: OpCopy,
Path: path,
From: from,
hasPath: true,
hasFrom: true,
}
}
// NewRemoveOperation creates a new remove Operation.
func NewRemoveOperation(path string) Operation {
return Operation{
Op: OpRemove,
Path: path,
hasPath: true,
}
}
// GetValue returns the operation's value. If the value has been pre-cached
// (e.g. via DecodePatch or a previous apply), the cached value is returned
// directly; otherwise it is parsed from the raw JSON and, when a cache is
// present, stored for future calls (lazy caching).
func (o *Operation) GetValue() (any, error) {
if !o.HasValue() {
return nil, fmt.Errorf("operation has no value")
}
if o.cache != nil {
o.cache.mu.Lock()
defer o.cache.mu.Unlock()
if o.cache.parsedValueOK {
return o.cache.parsedValue, nil
}
// Lazy-cache the value so repeated apply calls don't re-unmarshal.
var v any
if err := json.Unmarshal(*o.Value, &v); err != nil {
return nil, fmt.Errorf("failed to unmarshal value: %w", err)
}
o.cache.parsedValue = v
o.cache.parsedValueOK = true
return v, nil
}
var v any
if err := json.Unmarshal(*o.Value, &v); err != nil {
return nil, fmt.Errorf("failed to unmarshal value: %w", err)
}
return v, nil
}
// DecodePatch parses a JSON Patch document from raw JSON.
// The input can be []byte or string (or any type with one of those underlying types).
func DecodePatch[D Document](patchJSON D) (Patch, error) {
var patch Patch
if err := json.Unmarshal(toBytes(patchJSON), &patch); err != nil {
return nil, fmt.Errorf("failed to decode patch document: %w", err)
}
// Validate and cache parsed pointer fields for each operation.
// Value fields are cached lazily on the first GetValue call.
for i := range patch {
if err := validateAndCachePointersOnly(&patch[i]); err != nil {
return nil, fmt.Errorf("invalid operation at index %d: %w", i, err)
}
}
return patch, nil
}
// MarshalPatch serializes a Patch to JSON bytes.
func MarshalPatch(patch Patch) ([]byte, error) {
return json.Marshal(patch)
}
// validateAndCacheOperation validates the operation and eagerly caches all
// parsed fields (pointers and unmarshaled value) for apply reuse.
func validateAndCacheOperation(op *Operation) error {
return validateAndCache(op, true, true)
}
// validateAndCachePointersOnly validates the operation and caches only the
// parsed Pointer values. The value field is lazily parsed on the first
// GetValue call. This keeps DecodePatch cheap while preserving apply
// performance for repeated Apply on the same Patch.
func validateAndCachePointersOnly(op *Operation) error {
return validateAndCache(op, true, false)
}
// validateAndCache is the shared core for all three entry points above.
// When cacheResult is false, pointers are parsed for validation only — no
// allocation occurs. When cacheResult is true, parsed pointers are stored on
// op.cache; if eagerValue is also true, the value JSON is unmarshaled and
// cached as well.
func validateAndCache(op *Operation, cacheResult, eagerValue bool) error {
// All operations MUST have exactly one "op" member (RFC 6902 Section 4).
if op.Op == "" {
return fmt.Errorf("operation must contain a non-empty \"op\" member")
}
// All operations MUST have a "path" member (RFC 6902 Section 4).
if !op.hasPath {
return fmt.Errorf("%q operation must contain a \"path\" member", op.Op)
}
var pathPtr Pointer
var fromPtr Pointer
var err error
switch op.Op {
case OpAdd, OpReplace, OpTest:
if !op.HasValue() {
return fmt.Errorf("%q operation must contain a \"value\" member", op.Op)
}
pathPtr, err = ParsePointer(op.Path)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
case OpRemove:
pathPtr, err = ParsePointer(op.Path)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
case OpMove, OpCopy:
if !op.hasFrom {
return fmt.Errorf("%q operation must contain a \"from\" member", op.Op)
}
pathPtr, err = ParsePointer(op.Path)
if err != nil {
return fmt.Errorf("invalid path: %w", err)
}
fromPtr, err = ParsePointer(op.From)
if err != nil {
return fmt.Errorf("invalid from: %w", err)
}
default:
return fmt.Errorf("unknown operation %q", op.Op)
}
if !cacheResult {
return nil
}
c := &operationCache{
parsedPath: pathPtr,
parsedFrom: fromPtr,
}
if eagerValue && op.HasValue() {
var v any
if err := json.Unmarshal(*op.Value, &v); err != nil {
return fmt.Errorf("failed to unmarshal value: %w", err)
}
c.parsedValue = v
c.parsedValueOK = true
}
op.cache = c
return nil
}