Debian Codegraph @

README.md

raw symbols SCIP
1 # go-opt
2
3 [![builds.sr.ht status](https://builds.sr.ht/~rjarry/go-opt.svg)](https://builds.sr.ht/~rjarry/go-opt)
4
5 [go-opt](https://git.sr.ht/~rjarry/go-opt) is a library to parse command line
6 arguments based on tag annotations on struct fields. It came as a spin-off from
7 [aerc](https://git.sr.ht/~rjarry/aerc) to deal with its internal commands.
8
9 This project is a scaled down version of
10 [go-arg](https://github.com/alexflint/go-arg) with different usage patterns in
11 mind: command parsing and argument completion for internal application
12 commands.
13
14 ## License
15
16 [MIT](https://git.sr.ht/~rjarry/go-opt/tree/main/item/LICENSE)
17
18 The `shlex.go` file has been inspired from the [github.com/google/shlex](
19 https://github.com/google/shlex/blob/master/shlex.go) package which is licensed
20 under the Apache 2.0 license.
21
22 ## Contributing
23
24 Set patches via email to
25 [~rjarry/[email protected]](mailto:~rjarry/[email protected]) or
26 alternatively to
27 [~rjarry/[email protected]](mailto:~rjarry/[email protected]) with
28 the `PATCH go-opt` subject prefix.
29
30 ```sh
31 git config format.subjectPrefix "PATCH go-opt"
32 git config sendemail.to "~rjarry/[email protected]"
33 ```
34
35 ## Usage
36
37 ### Shell command line splitting
38
39 ```go
40 package main
41
42 import (
43 "log"
44
45 "git.sr.ht/~rjarry/go-opt/v2"
46 )
47
48 func main() {
49 args, err := opt.LexArgs(`foo 'bar baz' -f\ boz -- " yolo "`)
50 if err != nil {
51 log.Fatalf("error: %s\n", err)
52 }
53
54 fmt.Printf("count: %d\n", args.Count())
55 fmt.Printf("args: %#v\n", args.Args())
56 fmt.Printf("raw: %q\n", args.String())
57
58 fmt.Println("shift 2")
59 args.Shift(2)
60
61 fmt.Printf("count: %d\n", args.Count())
62 fmt.Printf("args: %#v\n", args.Args())
63 fmt.Printf("raw: %q\n", args.String())
64 }
65 ```
66
67 ```console
68 $ go run main.go
69 count: 5
70 args: []string{"foo", "bar baz", "-f boz", "--", " yolo "}
71 raw: "foo 'bar baz' -f\\ boz -- \" yolo \""
72 shift 2
73 count: 3
74 args: []string{"-f boz", "--", " yolo "}
75 raw: "-f\\ boz -- \" yolo \""
76 ```
77
78 ### Argument parsing
79
80
81 ```go
82 package main
83
84 import (
85 "fmt"
86 "log"
87
88 "git.sr.ht/~rjarry/go-opt/v2"
89 )
90
91 type Foo struct {
92 Delay time.Duration `opt:"-t,--delay" action:"ParseDelay" default:"1s"`
93 Force bool `opt:"--force"`
94 Name string `opt:"name" required:"false" metavar:"FOO"`
95 Cmd []string `opt:"..."`
96 }
97
98 func (f *Foo) ParseDelay(arg string) error {
99 d, err := time.ParseDuration(arg)
100 if err != nil {
101 return err
102 }
103 f.Delay = d
104 return nil
105 }
106
107 func main() {
108 var foo Foo
109 err := opt.CmdlineToStruct("foo -f bar baz 'xy z' ", &foo)
110 if err != nil {
111 log.Fatalf("error: %s\n", err)
112 }
113 fmt.Printf("%#v\n", foo)
114 }
115 ```
116
117 ```console
118 $ foo --force bar baz 'xy z'
119 main.Foo{Delay:1000000000, Force:true, Name:"bar", Cmd:[]string{"baz", "xy z"}}
120 $ foo -t
121 error: -t takes a value. Usage: foo [-t <delay>] [--force] [<name>] <cmd>...
122 ```
123
124 ### Argument completion
125
126 ```go
127 package main
128
129 import (
130 "fmt"
131 "log"
132 "os"
133 "strings"
134
135 "git.sr.ht/~rjarry/go-opt/v2"
136 )
137
138 type CompleteStruct struct {
139 Name string `opt:"-n,--name" required:"true" complete:"CompleteName"`
140 Delay float64 `opt:"--delay"`
141 Zero bool `opt:"-z"`
142 Backoff bool `opt:"-B,--backoff"`
143 Tags []string `opt:"..." complete:"CompleteTag"`
144 }
145
146 func (c *CompleteStruct) CompleteName(arg string) []string {
147 return []string{"leonardo", "michelangelo", "rafaelo", "donatello"}
148 }
149
150 func (c *CompleteStruct) CompleteTag(arg string) []string {
151 var results []string
152 prefix := ""
153 if strings.HasPrefix(arg, "-") {
154 prefix = "-"
155 } else if strings.HasPrefix(arg, "+") {
156 prefix = "+"
157 }
158 tags := []string{"unread", "sent", "important", "inbox", "trash"}
159 for _, t := range tags {
160 t = prefix + t
161 if strings.HasPrefix(t, arg) {
162 results = append(results, t)
163 }
164 }
165 return results
166 }
167
168 func main() {
169 args, err := opt.QuoteArgs(os.Args...)
170 if err != nil {
171 log.Fatalf("error: %s\n", err)
172 }
173 var s CompleteStruct
174 completions, _ := opt.GetCompletions(args.String(), &s)
175 for _, c := range completions {
176 fmt.Println(c.Value)
177 }
178 }
179 ```
180
181 ```console
182 $ foo i
183 important
184 inbox
185 $ foo -
186 --backoff
187 --delay
188 --name
189 -B
190 -important
191 -inbox
192 -n
193 -sent
194 -trash
195 -unread
196 -z
197 $ foo +
198 +important
199 +inbox
200 +sent
201 +trash
202 +unread
203 ```
204
205 ## Supported tags
206
207 There is a set of tags that can be set on struct fields:
208
209 ### `opt:"-f,--foo"`
210
211 Registers that this field is associated to the specified flag(s). Unless
212 a custom `action` method is specified, the flag value will be automatically
213 converted from string to the field type (only basic scalar types are supported:
214 all integers (both signed and unsigned), all floats and strings. If the field
215 type is `bool`, the flag will take no value.
216
217 ### `opt:"blah"`
218
219 Field is associated to a positional argument.
220
221 ### `opt:"..."`
222
223 Field will be mapped to all remaining arguments. If the field is `string`, the
224 raw command line will be stored preserving any shell quoting, otherwise the
225 field needs to be `[]string` and will receive the remaining arguments after
226 interpreting shell quotes.
227
228 ### `opt:":blah:"`
229
230 The field is associated to a positional argument which maps to a nested
231 sub-command. The field must be an interface and must have a defined `action`
232 method (see below). The `action` must set the field value to the appropriate
233 structure pointer.
234
235 ### `opt:"-"`
236
237 Special value to indicate that this command will accept any argument without
238 any check nor parsing. The field on which it is set will not be updated and
239 should be called `Unused struct{}` as a convention. The field name must start
240 with an upper case to avoid linter warnings because of unused fields.
241
242 ### `action:"ParseFoo"`
243
244 Custom method to be used instead of the default automatic conversion. Needs to
245 be a method with a pointer receiver to the struct itself, takes a single
246 `string` argument and may return an `error` to abort parsing. The `action`
247 method is responsible of updating the struct.
248
249 ### `description:"foobaz"` or `desc:"foobaz"`
250
251 A description that is returned alongside arguments during autocompletion.
252
253 ### `default:"foobaz"`
254
255 Default `string` value if not specified by the user. Will be processed by the
256 same conversion/parsing as any other argument.
257
258 ### `metavar:"foo|bar|baz"`
259
260 Displayed name for argument values in the generated usage help.
261
262 ### `required:"true|false"`
263
264 By default, flag arguments are optional and positional arguments are required.
265 Using this tag allows changing that default behaviour. If an argument is not
266 required, it will be surrounded by square brackets in the generated usage help.
267
268 ### `minus:"true|false"`
269
270 By default, any argument starting with `-` or `--` will be interpreted as
271 a short or long flag, respectively. If no matching flag is found, an error will
272 be returned.
273
274 Setting `minus:"true"` allows changing that default behaviour. If no matching
275 flag is found, instead of throwing an error, the argument will be considered as
276 positional.
277
278 ### `aliases:"cmd1,cmd2"`
279
280 By default, arguments are interpreted for all command aliases. If this is
281 specified, this field/option will only be applicable to the specified command
282 aliases.
283
284 ### `complete:"CompleteFoo"`
285
286 Custom method to return the valid completions for the annotated option
287 / argument. Needs to be a method with a pointer receiver to the struct itself,
288 takes a single `string` argument and must return a `[]string` slice containing
289 the valid completions.
290
291 By default, completion items will use the description of the field (if
292 `description` is defined). Each completion may contain an optional newline
293 character `\n` followed by its own description that will be used instead of the
294 default.
295
296 ## Caveats
297
298 Depending on field types, the argument string values are parsed using the
299 appropriate conversion function.
300
301 If no `opt` tag is set on a field, it will be excluded from automated argument
302 parsing. It can still be updated indirectly via a custom `action` method.
303
304 Short flags can be combined like with `getopt(3)`:
305
306 * Flags with no value: `-abc` is equivalent to `-a -b -c`
307 * Flags with a value (options): `-j9` is equivalent to `-j 9`
308
309 The special argument `--` forces an end to the flag parsing. The remaining
310 arguments are interpreted as positional arguments (see `getopt(3)`).