MCPcopy Create free account
hub / github.com/cli/cli / setAtPath

Function setAtPath

script/ghmock/set.go:369–389  ·  view source on GitHub ↗

setAtPath puts a JSON value at a dotted path inside a JSON body. Numeric segments index arrays. Missing objects along the way are created.

(body json.RawMessage, path, value string)

Source from the content-addressed store, hash-verified

367// setAtPath puts a JSON value at a dotted path inside a JSON body. Numeric
368// segments index arrays. Missing objects along the way are created.
369func setAtPath(body json.RawMessage, path, value string) (json.RawMessage, error) {
370 var root any = map[string]any{}
371 if len(bytes.TrimSpace(body)) > 0 {
372 if err := decodeJSON(body, &root); err != nil {
373 return nil, fmt.Errorf("current body is not valid JSON: %w", err)
374 }
375 }
376 var val any
377 if err := decodeJSON([]byte(value), &val); err != nil {
378 return nil, fmt.Errorf("--json is not valid JSON: %w", err)
379 }
380 segments := strings.Split(path, ".")
381 if slices.Contains(segments, "") {
382 return nil, fmt.Errorf("--at %q has an empty segment", path)
383 }
384 root, err := setPath(root, segments, val, "")
385 if err != nil {
386 return nil, err
387 }
388 return json.Marshal(root)
389}
390
391func setPath(node any, segments []string, val any, walked string) (any, error) {
392 if len(segments) == 0 {

Callers 1

applySetFunction · 0.85

Calls 4

setPathFunction · 0.85
ContainsMethod · 0.80
decodeJSONFunction · 0.70
ErrorfMethod · 0.65

Tested by

no test coverage detected