MCPcopy
hub / github.com/TomWright/dasel / Decode

Method Decode

internal/cli/variable.go:40–94  ·  view source on GitHub ↗

Decode decodes a variable from a flag. E.g. --var foo=bar E.g. --var foo=json:{"bar":"baz"} E.g. --var foo=json:file:/path/to/file.json

(ctx *kong.DecodeContext, target reflect.Value)

Source from the content-addressed store, hash-verified

38// E.g. --var foo=json:{"bar":"baz"}
39// E.g. --var foo=json:file:/path/to/file.json
40func (vm *variableMapper) Decode(ctx *kong.DecodeContext, target reflect.Value) error {
41 t := ctx.Scan.Pop()
42
43 strVal, ok := t.Value.(string)
44 if !ok {
45 return fmt.Errorf("expected string value for variable")
46 }
47
48 nameValueSplit := strings.SplitN(strVal, "=", 2)
49 if len(nameValueSplit) != 2 {
50 return fmt.Errorf("invalid variable format, expect foo=bar, or foo=format:file:path")
51 }
52
53 res := variable{
54 Name: nameValueSplit[0],
55 }
56
57 format := "dasel"
58 valueRaw := nameValueSplit[1]
59
60 firstSplit := strings.SplitN(valueRaw, ":", 2)
61 if len(firstSplit) == 2 {
62 format = firstSplit[0]
63 valueRaw = firstSplit[1]
64 }
65 if strings.HasPrefix(valueRaw, "file:") {
66 filePath := valueRaw[len("file:"):]
67
68 f, err := os.Open(filePath)
69 if err != nil {
70 return fmt.Errorf("failed to open file: %w", err)
71 }
72 defer func() {
73 _ = f.Close()
74 }()
75 contents, err := io.ReadAll(f)
76 if err != nil {
77 return fmt.Errorf("failed to read file contents: %w", err)
78 }
79 valueRaw = string(contents)
80 }
81
82 reader, err := parsing.Format(format).NewReader(parsing.DefaultReaderOptions())
83 if err != nil {
84 return fmt.Errorf("failed to create reader: %w", err)
85 }
86 res.Value, err = reader.Read([]byte(valueRaw))
87 if err != nil {
88 return fmt.Errorf("failed to read value: %w", err)
89 }
90
91 target.Elem().Set(reflect.Append(target.Elem(), reflect.ValueOf(res)))
92
93 return nil
94}

Callers 2

LoadConfigFunction · 0.45
ReadMethod · 0.45

Calls 6

ReadMethod · 0.95
FormatTypeAlias · 0.92
DefaultReaderOptionsFunction · 0.92
NewReaderMethod · 0.80
AppendMethod · 0.80
SetMethod · 0.45

Tested by

no test coverage detected