A collection of CLI argument types for the flag package.
import "github.com/sgreben/flagvar"Or just copy & paste what you need. It's public domain.
package main
import (
"flag"
"fmt"
"github.com/sgreben/flagvar"
)
var (
fruit = flagvar.Enum{Choices: []string{"apple", "banana"}}
urls flagvar.URLs
settings flagvar.Assignments
)
func main() {
flag.Var(&fruit, "fruit", fmt.Sprintf("set a fruit (%s)", fruit.Help()))
flag.Var(&urls, "url", "add a URL")
flag.Var(&settings, "set", fmt.Sprintf("specify a setting (%s)", settings.Help()))
flag.Parse()
}$ go run main.go -set abc=xyz -url https://github.com
# no error
$ go run main.go -set abc=xyz -url ://github.com
invalid value "://github.com" for flag -url: parse ://github.com: missing protocol scheme
$ go run main.go -fruit kiwi
invalid value "kiwi" for flag -fruit: "kiwi" must be one of [apple banana]
$ go run main.go -h
Usage:
-fruit value
set a fruit (one of [apple banana])
-set value
specify a setting (a key/value pair KEY=VALUE)
-url value
add a URL- Pluralized argument types (e.g.
Strings,Assignments) can be specified repeatedly, the values are collected in a slice. - The resulting value is stored in
.Valuefor singular types and in.Valuesfor plural types - The original argument string is stored in
.Textfor singular types and in.Textsfor plural types - -Set types (
EnumSet,StringSet) de-duplicate provided values. - -CSV types (
IntsCSV,EnumsCSV) accept comma-separated values and accumulate values across flag instances if their.Accumulatefield is set totrue. - Most types implement
interface{ Help() string }, which produces a string suitable for inclusion in a help message.
Here's a compact overview:
- Help avoid dependencies
- Self-contained > DRY
- Explicitly support copy & paste workflow
- Copyable units should be easy to determine
- Anonymous structs > shared types
- "Code-you-own" feeling, even when imported as a package
- No private fields / methods
- No magic
- Simple built-in types used wherever possible
- Avoid introducing new concepts
- Support "blind" usage
- Zero values should be useful
- Avoid introducing failure cases, handle any combination of parameters gracefully.
- All "obvious things to try" should work.
