Debian Codegraph @

internal/cli/variable.go

raw symbols SCIP
1 package cli
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "reflect"
8 "strings"
9
10 "github.com/alecthomas/kong"
11 "github.com/tomwright/dasel/v3/execution"
12 "github.com/tomwright/dasel/v3/model"
13 "github.com/tomwright/dasel/v3/parsing"
14 )
15
16 type variable struct {
17 Name string
18 Value *model.Value
19 }
20
21 type variables *[]variable
22
23 func variableOptions(vars variables) []execution.ExecuteOptionFn {
24 var opts []execution.ExecuteOptionFn
25 if vars != nil {
26 for _, v := range *vars {
27 opts = append(opts, execution.WithVariable(v.Name, v.Value))
28 }
29 }
30 return opts
31 }
32
33 type variableMapper struct {
34 }
35
36 // Decode decodes a variable from a flag.
37 // E.g. --var foo=bar
38 // E.g. --var foo=json:{"bar":"baz"}
39 // E.g. --var foo=json:file:/path/to/file.json
40 func (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 }