Debian Codegraph @

api.go

raw symbols SCIP
1 // Package dasel contains everything you'll need to use dasel from a go application.
2 package dasel
3
4 import (
5 "context"
6 "github.com/tomwright/dasel/v3/execution"
7 "github.com/tomwright/dasel/v3/model"
8 )
9
10 // Query queries the data using the selector and returns the results.
11 func Query(ctx context.Context, data any, selector string, opts ...execution.ExecuteOptionFn) ([]*model.Value, int, error) {
12 options := execution.NewOptions(opts...)
13 val := model.NewValue(data)
14 out, err := execution.ExecuteSelector(ctx, selector, val, options)
15 if err != nil {
16 return nil, 0, err
17 }
18
19 if out.IsBranch() || out.IsSpread() {
20 res := make([]*model.Value, 0)
21 if err := out.RangeSlice(func(i int, v *model.Value) error {
22 res = append(res, v)
23 return nil
24 }); err != nil {
25 return nil, 0, err
26 }
27 return res, len(res), nil
28 }
29
30 return []*model.Value{out}, 1, nil
31 }
32
33 // Select queries the data using the selector and returns the results as native Go types.
34 // Ordering within maps is not guaranteed.
35 func Select(ctx context.Context, data any, selector string, opts ...execution.ExecuteOptionFn) (any, int, error) {
36 res, count, err := Query(ctx, data, selector, opts...)
37 if err != nil {
38 return nil, 0, err
39 }
40 out := make([]any, 0)
41 for _, v := range res {
42 goValue, err := v.GoValue()
43 if err != nil {
44 return nil, 0, err
45 }
46 out = append(out, goValue)
47 }
48 return out, count, err
49 }
50
51 // Modify runs the query against the given data and updates it in-place.
52 // Given data must be a pointer to a mutable data structure.
53 func Modify(ctx context.Context, data any, selector string, newValue any, opts ...execution.ExecuteOptionFn) (int, error) {
54 res, count, err := Query(ctx, data, selector, opts...)
55 if err != nil {
56 return 0, err
57 }
58 for _, v := range res {
59 if err := v.Set(model.NewValue(newValue)); err != nil {
60 return 0, err
61 }
62 }
63 return count, nil
64 }