| 1 | # GNU command line argument parser |
| 2 | Command line argument parser following the GNU standard. |
| 3 | |
| 4 | ./test -vo out.png --size 256 input.txt |
| 5 | |
| 6 | with the following features: |
| 7 | |
| 8 | - build-in help (`-h` and `--help`) message |
| 9 | - scan arguments into struct fields with configuration in tags |
| 10 | - scan into composite field types (arrays, slices, structs) |
| 11 | - allow for nested sub commands |
| 12 | |
| 13 | GNU command line argument rules: |
| 14 | |
| 15 | - arguments are options when they begin with a hyphen `-` |
| 16 | - multiple options can be combined: `-abc` is the same as `-a -b -c` |
| 17 | - long options start with two hyphens: `--abc` is one option |
| 18 | - option names are alphanumeric characters |
| 19 | - options can have a value: `-a 1` means that `a` has value `1` |
| 20 | - option values can be separated by a space, equal sign, or nothing: `-a1 -a=1 -a 1` are all equal |
| 21 | - options and non-options can be interleaved |
| 22 | - options may appear in any order |
| 23 | - the argument `--` terminates all options so that all following arguments are treated as non-options |
| 24 | - an argument value of `-` is allowed, usually used to mean standard in or out streams |
| 25 | - options may be specified multiple times, only the last one determines its value |
| 26 | |
| 27 | Additional features: |
| 28 | |
| 29 | - counting options: `-vvv` sets `v = 3` |
| 30 | - appending options: `-v 1 -v 2` sets `v = []int{1, 2}` |
| 31 | - boolean options: `--var` enables and `--no-var` disables a boolean |
| 32 | - options can be composite types, such as structs, slices, or maps: |
| 33 | - `-v 1,2,3` sets `v = []int{1, 2, 3}` |
| 34 | - `-v [1 2 3]` sets `v = []int{1, 2, 3}` |
| 35 | - `-v {1:one 2:two}` sets `map[int]string{1:"one", 2:"two"}` |
| 36 | - `-v {string 42 [0 1]}` sets `struct{S string, I int, B [2]bool}{"string", 42, false, true}` |
| 37 | - options can retrieve their list/dict values from a source (such as SQL): |
| 38 | - `-v file:email-addresses.txt` sets `v = []string{ /* lines in email-addresses.txt */ }` |
| 39 | - `-v file:email-addresses.txt` sets `v = map[string]string{ /* key=value in email-addresses.txt lines */ }` |
| 40 | |
| 41 | *See also [github.com/tdewolff/prompt](https://github.com/tdewolff/prompt) for a command line prompter.* |
| 42 | |
| 43 | ## Installation |
| 44 | Make sure you have [Git](https://git-scm.com/) and [Go](https://golang.org/dl/) (1.22 or higher) installed, run |
| 45 | ``` |
| 46 | mkdir Project |
| 47 | cd Project |
| 48 | go mod init |
| 49 | go get -u github.com/tdewolff/argp |
| 50 | ``` |
| 51 | |
| 52 | Then add the following import |
| 53 | ``` go |
| 54 | import ( |
| 55 | "github.com/tdewolff/argp" |
| 56 | ) |
| 57 | ``` |
| 58 | |
| 59 | ## Examples |
| 60 | ### Default usage |
| 61 | A regular command with short and long options. |
| 62 | See [`cmd/test/main.go`](cmd/test/main.go). |
| 63 | |
| 64 | ```go |
| 65 | package main |
| 66 | |
| 67 | import "github.com/tdewolff/argp" |
| 68 | |
| 69 | func main() { |
| 70 | var verbose int |
| 71 | var input string |
| 72 | var output string |
| 73 | var files []string |
| 74 | size := 512 // default value |
| 75 | |
| 76 | cmd := argp.New("CLI tool description") |
| 77 | cmd.AddOpt(argp.Count{&verbose}, "v", "verbose", "Increase verbosity, eg. -vvv") |
| 78 | cmd.AddOpt(&output, "o", "output", "Output file name") |
| 79 | cmd.AddOpt(&size, "", "size", "Image size") |
| 80 | cmd.AddArg(&input, "input", "Input file name") |
| 81 | cmd.AddRest(&files, "files", "Additional files") |
| 82 | cmd.Parse() |
| 83 | |
| 84 | // ... |
| 85 | } |
| 86 | ``` |
| 87 | |
| 88 | with help output |
| 89 | |
| 90 | ``` |
| 91 | Usage: test [options] input files... |
| 92 | |
| 93 | Options: |
| 94 | -h, --help Help |
| 95 | -o, --output string Output file name |
| 96 | --size=512 int Image size |
| 97 | -v, --verbose int Increase verbosity, eg. -vvv |
| 98 | |
| 99 | Arguments: |
| 100 | input Input file name |
| 101 | files Additional files |
| 102 | ``` |
| 103 | |
| 104 | ### Sub commands |
| 105 | Example with sub commands using a main command for when no sub command is used, and a sub command named "cmd". For the main command we can also use `New` and `AddOpt` instead and process the command after `argp.Parse()`. |
| 106 | |
| 107 | ```go |
| 108 | package main |
| 109 | |
| 110 | import "github.com/tdewolff/argp" |
| 111 | |
| 112 | func main() { |
| 113 | cmd := argp.NewCmd(&Main{}, "CLI tool description") |
| 114 | cmd.AddCmd(&Command{}, "cmd", "Sub command") |
| 115 | cmd.Parse() |
| 116 | } |
| 117 | |
| 118 | type Main struct { |
| 119 | Version bool `short:"v"` |
| 120 | } |
| 121 | |
| 122 | func (cmd *Main) Run() error { |
| 123 | // ... |
| 124 | } |
| 125 | |
| 126 | type Command struct { |
| 127 | Verbose bool `short:"v" name:""` |
| 128 | Output string `short:"o" desc:"Output file name"` |
| 129 | Size int `default:"512" desc:"Image size"` |
| 130 | } |
| 131 | |
| 132 | func (cmd *Command) Run() error { |
| 133 | // ... |
| 134 | } |
| 135 | ``` |
| 136 | |
| 137 | ### Arguments |
| 138 | ```go |
| 139 | var input string |
| 140 | cmd.AddArg(&input, "input", "Input file name") |
| 141 | |
| 142 | var files []string |
| 143 | cmd.AddRest(&files, "files", "Additional input files") |
| 144 | ``` |
| 145 | |
| 146 | ### Options |
| 147 | Basic types |
| 148 | ```go |
| 149 | var v string = "default" |
| 150 | cmd.AddOpt(&v, "v", "var", "description") |
| 151 | |
| 152 | var v bool = true |
| 153 | cmd.AddOpt(&v, "v", "var", "description") |
| 154 | |
| 155 | var v int = 42 // also: int8, int16, int32, int64 |
| 156 | cmd.AddOpt(&v, "v", "var", "description") |
| 157 | |
| 158 | var v uint = 42 // also: uint8, uint16, uint32, uint64 |
| 159 | cmd.AddOpt(&v, "v", "var", "description") |
| 160 | |
| 161 | var v float64 = 4.2 // also: float32 |
| 162 | cmd.AddOpt(&v, "v", "var", "description") |
| 163 | ``` |
| 164 | |
| 165 | Composite types |
| 166 | ```go |
| 167 | v := [2]int{4, 2} // element can be any valid basic or composite type |
| 168 | cmd.AddOpt(&v, "v", "var", "description") |
| 169 | // --var [4 2] => [2]int{4, 2} |
| 170 | // or: --var 4,2 => [2]int{4, 2} |
| 171 | |
| 172 | v := []int{4, 2, 1} // element can be any valid basic or composite type |
| 173 | cmd.AddOpt(&v, "v", "var", "description") |
| 174 | // --var [4 2 1] => []int{4, 2, 1} |
| 175 | // or: --var 4,2,1 => []int{4, 2, 1} |
| 176 | |
| 177 | v := map[int]string{1:"one", 2:"two"} // key and value can be any valid basic or composite type |
| 178 | cmd.AddOpt(&v, "v", "var", "description") |
| 179 | // --var {1:one 2:two} => map[int]string{1:"one", 2:"two"} |
| 180 | |
| 181 | v := struct { // fields can be any valid basic or composite type |
| 182 | S string |
| 183 | I int |
| 184 | B [2]bool |
| 185 | }{"string", 42, [2]bool{0, 1}} |
| 186 | cmd.AddOpt(&v, "v", "var", "description") |
| 187 | // --var {string 42 [0 1]} => struct{S string, I int, B [2]bool}{"string", 42, false, true} |
| 188 | ``` |
| 189 | |
| 190 | #### Count |
| 191 | Count the number of time a flag has been passed. |
| 192 | |
| 193 | ```go |
| 194 | var c int |
| 195 | cmd.AddOpt(argp.Count{&c}, "c", "count", "Count") |
| 196 | // Count the number of times flag is present |
| 197 | // -c -c / -cc / --count --count => 2 |
| 198 | // or: -c 5 => 5 |
| 199 | ``` |
| 200 | |
| 201 | #### Append |
| 202 | Append each flag to a list. |
| 203 | |
| 204 | ```go |
| 205 | var v []int |
| 206 | cmd.AddOpt(argp.Append{&v}, "v", "value", "Values") |
| 207 | // Append values for each flag |
| 208 | // -v 1 -v 2 => [1 2] |
| 209 | ``` |
| 210 | |
| 211 | #### Config |
| 212 | Load all arguments from a configuration file. Currently only TOML is supported. |
| 213 | |
| 214 | ```go |
| 215 | cmd.AddOpt(&argp.Config{cmd, "config.toml"}, "", "config", "Configuration file") |
| 216 | ``` |
| 217 | |
| 218 | #### List |
| 219 | Use a list source specified as type:list. Default supported types are: inline. |
| 220 | - Inline takes a []string, e.g. `inline:[foo bar]` |
| 221 | |
| 222 | ```go |
| 223 | list := argp.NewList(il) |
| 224 | defer list.Close() |
| 225 | |
| 226 | cmd.AddOpt(&list, "", "list", "List") |
| 227 | ``` |
| 228 | |
| 229 | You can add a MySQL source: |
| 230 | ``` |
| 231 | type mysqlList struct { |
| 232 | Hosts string |
| 233 | User string |
| 234 | Password string |
| 235 | Dbname string |
| 236 | Query string |
| 237 | } |
| 238 | |
| 239 | func newMySQLList(s []string) (argp.ListSource, error) { |
| 240 | if len(s) != 1 { |
| 241 | return nil, fmt.Errorf("invalid path") |
| 242 | } |
| 243 | |
| 244 | t := mysqlList{} |
| 245 | if err := argp.LoadConfigFile(&t, s[0]); err != nil { |
| 246 | return nil, err |
| 247 | } |
| 248 | |
| 249 | uri := fmt.Sprintf("%s:%s@%s/%s", t.User, t.Password, t.Hosts, t.Dbname) |
| 250 | db, err := sqlx.Open("mysql", uri) |
| 251 | if err != nil { |
| 252 | return nil, err |
| 253 | } |
| 254 | db.SetConnMaxLifetime(time.Minute) |
| 255 | db.SetConnMaxIdleTime(time.Minute) |
| 256 | db.SetMaxOpenConns(10) |
| 257 | db.SetMaxIdleConns(10) |
| 258 | return argp.NewSQLList(db, t.Query, "") |
| 259 | } |
| 260 | |
| 261 | // ... |
| 262 | list.AddSource("mysql", newMySQLList) |
| 263 | // ... |
| 264 | ``` |
| 265 | Use as `./bin -list mysql:list-config.toml`. |
| 266 | |
| 267 | #### Dict |
| 268 | Use a dict source specified as type:dict. Default supported types are: static and inline. |
| 269 | - Static takes a string and will return that as a value for all keys, e.g. `static:foobar` |
| 270 | - Inline takes a map[string]string, e.g. `inline:{foo:1 bar:2}` |
| 271 | |
| 272 | ```go |
| 273 | dict := argp.NewDict([]string{"static:value"}) |
| 274 | defer dict.Close() |
| 275 | |
| 276 | cmd.AddOpt(&dict, "", "dict", "Dict") |
| 277 | ``` |
| 278 | |
| 279 | You can add custom sources must like the mysqlList example above. |
| 280 | |
| 281 | ### Option tags |
| 282 | The following struct will accept the following options and arguments: |
| 283 | - `-v` or `--var` with a default value of 42 |
| 284 | - The first argument called `first` with a default value of 4.2 |
| 285 | - The other arguments called `rest` |
| 286 | |
| 287 | ```go |
| 288 | type Command struct { |
| 289 | Var1 int `short:"v" name:"var" default:"42" desc:"Description"` |
| 290 | Var2 float64 `name:"first" index:"0" default:"4.2"` |
| 291 | Var3 []string `name:"rest" index:"*"` |
| 292 | } |
| 293 | |
| 294 | func (cmd *Command) Run() error { |
| 295 | // run command |
| 296 | return nil |
| 297 | } |
| 298 | ``` |
| 299 | |
| 300 | ## License |
| 301 | Released under the [MIT license](LICENSE.md). |