Debian Codegraph @

providers/cliflagv3/cliflagv3.go

raw
1 // Package cliflagv3 implements a koanf.Provider that reads commandline
2 // parameters as conf maps using urfave/cli/v3 flag.
3 package cliflagv3
4
5 import (
6 "errors"
7 "slices"
8 "strings"
9
10 "github.com/knadh/koanf/maps"
11 "github.com/urfave/cli/v3"
12 )
13
14 // CliFlag implements a cli.Flag command line provider.
15 type CliFlag struct {
16 cmd *cli.Command
17 delim string
18 config *Config
19 }
20
21 // KoanfIntf is an interface that represents a small subset of methods
22 // used by this package from Koanf{}.
23 // When using this in ProviderWithConfig, a live instance of Koanf{} should be passed.
24 type KoanfIntf interface {
25 Exists(string) bool
26 }
27
28 type Config struct {
29 Defaults []string
30
31 // KeyMap is an optional live Koanf instance used to check whether keys already
32 // exist from a previously loaded provider (e.g. a config file). When set,
33 // unset flag defaults are merged only if the key does not already exist in the given instance,
34 // preventing flag defaults from being overwritten by sources with lower precedence.
35 KeyMap KoanfIntf
36 }
37
38 // Provider returns a commandline flags provider that returns
39 // a nested map[string]any of environment variable where the
40 // nesting hierarchy of keys are defined by delim. For instance, the
41 // delim "." will convert the key `parent.child.key: 1`
42 // to `{parent: {child: {key: 1}}}`.
43 func Provider(f *cli.Command, delim string) *CliFlag {
44 return &CliFlag{
45 cmd: f,
46 delim: delim,
47 config: &Config{
48 Defaults: []string{},
49 },
50 }
51 }
52
53 // ProviderWithConfig returns a commandline flags provider with a
54 // Configuration struct attached.
55 func ProviderWithConfig(f *cli.Command, delim string, config *Config) *CliFlag {
56 return &CliFlag{
57 cmd: f,
58 delim: delim,
59 config: config,
60 }
61 }
62
63 // ReadBytes is not supported by the cliflagv3 provider.
64 func (p *CliFlag) ReadBytes() ([]byte, error) {
65 return nil, errors.New("cliflagv3 provider does not support this method")
66 }
67
68 // Read reads the flag variables and returns a nested conf map.
69 func (p *CliFlag) Read() (map[string]any, error) {
70 out := make(map[string]any)
71
72 // Get command lineage (from root to current command)
73 lineage := p.cmd.Lineage()
74 if len(lineage) > 0 {
75 // Build command path and process flags for each level
76 var cmdPath []string
77 for i := len(lineage) - 1; i >= 0; i-- {
78 cmd := lineage[i]
79 cmdPath = append(cmdPath, cmd.Name)
80 prefix := strings.Join(cmdPath, p.delim)
81 p.processFlags(cmd.Flags, prefix, out)
82 }
83 }
84
85 if p.delim == "" {
86 return out, nil
87 }
88
89 return maps.Unflatten(out, p.delim), nil
90 }
91
92 func (p *CliFlag) processFlags(flags []cli.Flag, prefix string, out map[string]any) {
93 for _, flag := range flags {
94 name := flag.Names()[0]
95
96 // Build the full path for the flag.
97 fullPath := name
98 if prefix != "global" {
99 fullPath = prefix + p.delim + name
100 }
101
102 if !p.cmd.IsSet(name) && !slices.Contains(p.config.Defaults, name) {
103 // Flag was not explicitly set and is not in Defaults.
104 // If a KeyMap is provided and the key already exists, skip it
105 // so we lower-priority sources' values aren't used.
106 // If no KeyMap is provided, skip it altogether.
107 if p.config.KeyMap == nil || p.config.KeyMap.Exists(fullPath) {
108 continue
109 }
110 }
111
112 value := p.getFlagValue(name)
113 if value != nil {
114 p.setNestedValue(fullPath, value, out)
115 }
116 }
117 }
118
119 // setNestedValue sets a value in the nested configuration structure
120 func (p *CliFlag) setNestedValue(path string, value any, out map[string]any) {
121 parts := strings.Split(path, p.delim)
122 current := out
123
124 // Navigate/create the nested structure
125 for i := 0; i < len(parts)-1; i++ {
126 if _, exists := current[parts[i]]; !exists {
127 current[parts[i]] = make(map[string]any)
128 }
129 current = current[parts[i]].(map[string]any)
130 }
131
132 // Set the final value
133 current[parts[len(parts)-1]] = value
134 }
135
136 // getFlagValue extracts the typed value from the flag.
137 func (p *CliFlag) getFlagValue(name string) any {
138 // Find the flag definition
139 flag := p.findFlag(name)
140 if flag == nil {
141 return nil
142 }
143 return flag.Get()
144 }
145
146 // findFlag looks up a flag by name
147 func (p *CliFlag) findFlag(name string) cli.Flag {
148 // Check global flags
149 for _, f := range p.cmd.Flags {
150 if slices.Contains(f.Names(), name) {
151 return f
152 }
153 }
154
155 return nil
156 }