Debian Codegraph @

opt.go

raw symbols SCIP
1 package opt
2
3 /*
4 Example use:
5
6 ```go
7 package main
8
9 import (
10 "fmt"
11 "log"
12
13 "git.sr.ht/~rjarry/go-opt/v2"
14 )
15
16 type Foo struct {
17 Delay time.Duration `opt:"-t" action:"ParseDelay" default:"1s"`
18 Force bool `opt:"-f"`
19 Name string `opt:"name" required:"false" metavar:"FOO"`
20 Cmd []string `opt:"..."`
21 }
22
23 func (f *Foo) ParseDelay(arg string) error {
24 d, err := time.ParseDuration(arg)
25 if err != nil {
26 return err
27 }
28 f.Delay = d
29 return nil
30 }
31
32 func main() {
33 var foo Foo
34 err := opt.CmdlineToStruct("foo -f bar baz 'xy z' ", &foo)
35 if err != nil {
36 log.Fatalf("error: %s\n", err)
37 }
38 fmt.Printf("%#v\n", foo)
39 }
40 ```
41
42 ```console
43 $ foo -f bar baz 'xy z'
44 Foo{Delay: 1000000000, Force: true, Name: "bar", Cmd: []string{"baz", "xy z"}}
45 $ foo -t
46 error: -t takes a value. Usage: foo [-t <delay>] [-f] [<name>] <cmd>...
47 ```
48
49 ## Supported tags
50
51 There is a set of tags that can be set on struct fields:
52
53 ### `opt:"-f"`
54
55 Registers that this field is associated to the specified flag. Unless a custom
56 `action` method is specified, the flag value will be automatically converted
57 from string to the field type (only basic scalar types are supported: all
58 integers (both signed and unsigned), all floats and strings. If the field type
59 is `bool`, the flag will take no value. Only supports short flags for now.
60
61 ### `opt:"blah"`
62
63 Field is associated to a positional argument.
64
65 ### `opt:"..."`
66
67 Field will be mapped to all remaining arguments. If the field is `string`, the
68 raw command line will be stored preserving any shell quoting, otherwise the
69 field needs to be `[]string` and will receive the remaining arguments after
70 interpreting shell quotes.
71
72 ### `opt:"-"`
73
74 Special value to indicate that this command will accept any argument without
75 any check nor parsing. The field on which it is set will not be updated and
76 should be called `Unused struct{}` as a convention. The field name must start
77 with an upper case to avoid linter warnings because of unused fields.
78
79 ### `action:"ParseFoo"`
80
81 Custom method to be used instead of the default automatic conversion. Needs to
82 be a method with a pointer receiver to the struct itself, takes a single
83 `string` argument and may return an `error` to abort parsing. The `action`
84 method is responsible of updating the struct.
85
86 ### `description:"foobaz"` or `desc:"foobaz"`
87
88 A description that is returned alongside arguments during autocompletion.
89
90 ### `default:"foobaz"`
91
92 Default `string` value if not specified by the user. Will be processed by the
93 same conversion/parsing as any other argument.
94
95 ### `metavar:"foo|bar|baz"`
96
97 Displayed name for argument values in the generated usage help.
98
99 ### `required:"true|false"`
100
101 By default, flag arguments are optional and positional arguments are required.
102 Using this tag allows changing that default behaviour. If an argument is not
103 required, it will be surrounded by square brackets in the generated usage help.
104
105 ### `aliases:"cmd1,cmd2"`
106
107 By default, arguments are interpreted for all command aliases. If this is
108 specified, this field/option will only be applicable to the specified command
109 aliases.
110
111 ### `complete:"CompleteFoo"`
112
113 Custom method to return the valid completions for the annotated option
114 / argument. Needs to be a method with a pointer receiver to the struct itself,
115 takes a single `string` argument and must return a `[]string` slice containing
116 the valid completions.
117
118 ## Caveats
119
120 Depending on field types, the argument string values are parsed using the
121 appropriate conversion function.
122
123 If no `opt` tag is set on a field, it will be excluded from automated argument
124 parsing. It can still be updated indirectly via a custom `action` method.
125
126 Short flags can be combined like with `getopt(3)`:
127
128 * Flags with no value: `-abc` is equivalent to `-a -b -c`
129 * Flags with a value (options): `-j9` is equivalent to `-j 9`
130 */
131
132 import (
133 "errors"
134 "fmt"
135 )
136
137 func CmdlineToStruct(cmdline string, v any) error {
138 args := LexArgs(cmdline)
139 return ArgsToStruct(args, v)
140 }
141
142 func ArgsToStruct(args *Args, v any) error {
143 if args.Count() == 0 {
144 return errors.New("empty command")
145 }
146
147 cmd := NewCmdSpec(args.Arg(0), v)
148 if err := cmd.ParseArgs(args); err != nil {
149 return fmt.Errorf("%w. Usage: %s", err, cmd.Usage())
150 }
151
152 return nil
153 }
154
155 func GetCompletions(cmdline string, v any) (completions []Completion, prefix string) {
156 args := LexArgs(cmdline)
157 if args.Count() == 0 {
158 return nil, ""
159 }
160 spec := NewCmdSpec(args.Arg(0), v)
161 return spec.GetCompletions(args)
162 }