{"id":13410513,"url":"https://github.com/DavidGamba/go-getoptions","last_synced_at":"2025-03-14T16:32:16.398Z","repository":{"id":50246305,"uuid":"48209526","full_name":"DavidGamba/go-getoptions","owner":"DavidGamba","description":"Fully featured Go (golang) command line option parser with built-in auto-completion support.","archived":false,"fork":false,"pushed_at":"2024-06-19T04:21:16.000Z","size":768,"stargazers_count":56,"open_issues_count":2,"forks_count":10,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-07-31T20:43:01.045Z","etag":null,"topics":["argument-parser","autocomplete","cli","command-line","flag","getopt","golang","hacktoberfest","option-parser"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/DavidGamba.png","metadata":{"files":{"readme":"README.adoc","changelog":"changelog.adoc","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["DavidGamba"]}},"created_at":"2015-12-18T02:21:14.000Z","updated_at":"2024-03-23T12:09:45.000Z","dependencies_parsed_at":"2024-01-08T14:30:54.162Z","dependency_job_id":"6cd1d240-8b4c-4741-b009-778fc4a01755","html_url":"https://github.com/DavidGamba/go-getoptions","commit_stats":{"total_commits":327,"total_committers":2,"mean_commits":163.5,"dds":0.003058103975535187,"last_synced_commit":"e79193431d22bf842b23d9702f3fe49167941ef1"},"previous_names":[],"tags_count":29,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavidGamba%2Fgo-getoptions","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavidGamba%2Fgo-getoptions/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavidGamba%2Fgo-getoptions/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/DavidGamba%2Fgo-getoptions/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/DavidGamba","download_url":"https://codeload.github.com/DavidGamba/go-getoptions/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243610227,"owners_count":20318928,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["argument-parser","autocomplete","cli","command-line","flag","getopt","golang","hacktoberfest","option-parser"],"created_at":"2024-07-30T20:01:07.413Z","updated_at":"2025-03-14T16:32:16.078Z","avatar_url":"https://github.com/DavidGamba.png","language":"Go","funding_links":["https://github.com/sponsors/DavidGamba"],"categories":["命令行工具### 标准 CLI`用于创建一个标准命令行应用程序的库`","命令行","Command Line","命令行工具","Build Automation"],"sub_categories":["标准CLI","Standard CLI","标准 CLI"],"readme":"= go-getoptions\nDavid Gamba, https://github.com/DavidGamba\n:idprefix:\n:name: go-getoptions\n:toc: macro\n:toclevels: 4\n\nFully featured Go (golang) command line option parser with built-in auto-completion support.\n\nimage:https://pkg.go.dev/badge/github.com/DavidGamba/go-getoptions.svg[\"Go Reference\", link=\"https://pkg.go.dev/github.com/DavidGamba/go-getoptions\"]\nimage:https://github.com/DavidGamba/go-getoptions/actions/workflows/test.yml/badge.svg?branch=master[\"Build Status\", link=\"https://github.com/DavidGamba/go-getoptions/actions/workflows/test.yml?query=branch:master\"]\nimage:https://codecov.io/github/DavidGamba/go-getoptions/coverage.svg?branch=master[\"Coverage via Codecov\", link=\"https://codecov.io/github/DavidGamba/go-getoptions?branch=release\"]\n\nVideo Demo: https://youtu.be/1ZGyIkC5shM\n\ntoc::[]\n\n[[quick_overview]]\n== Quick overview\n\n. See a detailed video demonstration: https://youtu.be/1ZGyIkC5shM\n\n. Define your command line specification:\n+\n[source,go]\n----\npackage main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"os\"\n\n\t\"github.com/DavidGamba/go-getoptions\"\n)\n\nvar Logger = log.New(os.Stderr, \"\", log.LstdFlags)\n\nfunc main() {\n\tos.Exit(program(os.Args))\n}\n\nfunc program(args []string) int {\n\tctx, cancel, done := getoptions.InterruptContext()\n\tdefer func() { cancel(); \u003c-done }()\n\n\topt := getoptions.New()\n\topt.Self(\"myscript\", \"Simple demo script\")\n\topt.Bool(\"debug\", false, opt.GetEnv(\"DEBUG\"))\n\topt.Int(\"greet\", 0, opt.Required(), opt.Description(\"Number of times to greet.\"))\n\topt.StringMap(\"list\", 1, 99, opt.Description(\"Greeting list by language.\"))\n\topt.Bool(\"quiet\", false, opt.GetEnv(\"QUIET\"))\n\topt.HelpSynopsisArg(\"\u003cname\u003e\", \"Name to greet.\")\n\topt.SetCommandFn(Run)\n\topt.HelpCommand(\"help\", opt.Alias(\"?\"))\n\tremaining, err := opt.Parse(args[1:])\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %s\\n\", err)\n\t\treturn 1\n\t}\n\tif opt.Called(\"quiet\") {\n\t\tLogger.SetOutput(io.Discard)\n\t}\n\n\terr = opt.Dispatch(ctx, remaining)\n\tif err != nil {\n\t\tif errors.Is(err, getoptions.ErrorHelpCalled) {\n\t\t\treturn 1\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %s\\n\", err)\n\t\tif errors.Is(err, getoptions.ErrorParsing) {\n\t\t\tfmt.Fprintf(os.Stderr, \"\\n\"+opt.Help())\n\t\t}\n\t\treturn 1\n\t}\n\treturn 0\n}\n\nfunc Run(ctx context.Context, opt *getoptions.GetOpt, args []string) error {\n\t// Get arguments and options\n\tname, _, err := opt.GetRequiredArg(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgreetCount := opt.Value(\"greet\").(int)\n\tlist := opt.Value(\"list\").(map[string]string)\n\n\tLogger.Printf(\"Running: %v\", args)\n\n\t// Use the int variable\n\tfor i := 0; i \u003c greetCount; i++ {\n\t\tfmt.Printf(\"Hello %s, from go-getoptions!\\n\", name)\n\t}\n\n\t// Use the map[string]string variable\n\tif len(list) \u003e 0 {\n\t\tfmt.Printf(\"Greeting List:\\n\")\n\t\tfor k, v := range list {\n\t\t\tfmt.Printf(\"\\t%s=%s\\n\", k, v)\n\t\t}\n\t}\n\n\treturn nil\n}\n----\n\n. Call it:\n+\n.Show help\n----\n$ ./myscript help\nNAME:\n    myscript - Simple demo script\n\nSYNOPSIS:\n    myscript --greet \u003cint\u003e [--debug] [--help|-?] [--list \u003ckey=value\u003e...]...\n             [--quiet] \u003cname\u003e\n\nARGUMENTS:\n    \u003cname\u003e                   Name to greet.\n\nREQUIRED PARAMETERS:\n    --greet \u003cint\u003e            Number of times to greet.\n\nOPTIONS:\n    --debug                  (default: false, env: DEBUG)\n\n    --help|-?                (default: false)\n\n    --list \u003ckey=value\u003e...    Greeting list by language. (default: {})\n\n    --quiet                  (default: false, env: QUIET)\n----\n+\n.Show errors\n----\n$ ./myscript\nERROR: Missing required parameter 'greet'\n----\n+\n.Show errors\n----\n$ ./myscript -g\nERROR: Missing argument for option 'greet'!\n----\n+\n.Show errors\n----\n$ ./myscript -g 3\nERROR: Missing \u003cname\u003e\nSYNOPSIS:\n    myscript --greet \u003cint\u003e [--debug] [--help|-?] [--list \u003ckey=value\u003e...]...\n             [--quiet] \u003cname\u003e\n----\n+\n.Use of int option\n----\n$ ./myscript -g 3 David\n2024/01/04 23:25:14 Running: [David]\nHello David, from go-getoptions!\nHello David, from go-getoptions!\nHello David, from go-getoptions!\n----\n+\n.Use of bool option\n----\n$ ./myscript -g 1 David --quiet\nHello David, from go-getoptions!\n----\n+\n.Use of map option\n----\n$ ./myscript -g 0 David -l en='Hello World' es='Hola Mundo'\n2024/01/04 23:27:00 Running: [David]\nGreeting List:\n\ten=Hello World\n\tes=Hola Mundo\n----\n\nNOTE: If you are starting a new project, instead of copying the example code from above, use the code from the link:./docs/new-project-templates.adoc[New Project Templates].\n\n== Examples\n\n=== Simple script\n\nA simple script link:./examples/myscript/main.go[]\n\nTo use the autocompletion, cd to the link:./examples/myscript[] dir and run: `source sourceme.bash`\nThe run `go build` and `./myscript`.\n\nTab completion for this script is triggered for options only, so you need to have a dash `-` to trigger it: `./myscript -\u003ctab\u003e\u003ctab\u003e`\n\n=== Program with multiple commands separated in multiple packages\n\nThis is the other extreme, a large program that can separate each command in a separate go package.\n\nThe base is located at link:./examples/complex/main.go[]\n\nThe commands are located at:\n\n* link:./examples/complex/greet/greet.go[]\n* link:./examples/complex/log/log.go[]\n* link:./examples/complex/show/show.go[]\n* link:./examples/complex/slow/slow.go[]\n\nTo use the autocompletion, cd to the link:./examples/complex[] dir and run: `source sourceme.bash`\nThe run `go build` and `./complex`.\n\nTab completion without arguments triggers completion for commands, for option completion add a dash `-` and trigger it: `./complex -\u003ctab\u003e\u003ctab\u003e`\n\nThe link:./examples/complex/slow/slow.go[slow] command shows an example of an slow command that can be cancelled with `Ctrl+C`.\nThe cancellation is passed to the command through `context.Context` and it is handled at the command to stop taking new work and trigger a cleanup routine.\nRunning `Ctrl+C` twice cancels the cancellation routine and fully cancels the program.\n\nThe link:./examples/complex/greet/greet.go[greet] command shows an example of using commands and subcommands.\n\n=== Directed Acyclic Graph Build System\n\nThis example shows task dependency orchestration and parallelization link:./examples/dag/main.go[].\n\nTo use the autocompletion, cd to the link:./examples/dag[] dir and run: `source sourceme.bash`\nThe run `go build` and `./dag`.\n\nTab completion without arguments triggers completion for commands, for option completion add a dash `-` and trigger it: `./dag -\u003ctab\u003e\u003ctab\u003e`\n\n== DAG Build System\n\nFor an overview of the Directed Acyclic Graph Build System see link:./dag/README.adoc[]\n\nNOTE: The DAG code is in a separate package so it is not pulled in by default.\n\n== Features\n\n• Built in auto completion.\nA single line of bash is all it takes.\n+\n[source,bash]\n----\ncomplete -o default -C my-go-program my-go-program\n----\n+\nZshell is also supported, by exporting `ZSHELL=true` in your environment and using `bashcompinit`.\n\n• Allow passing options and non-options (arguments) in any order.\n\n• Support for `--long` options.\n\n• Support for short (`-s`) options with flexible behaviour (see the \u003c\u003coperation_modes\u003e\u003e section for details):\n\n  - Normal (default)\n  - Bundling\n  - SingleDash\n\n• `Called()` method indicates if the option was passed on the command line.\n\n• Multiple aliases for the same option. e.g. `help`, `man`.\n\n• `CalledAs()` method indicates what alias was used to call the option on the command line.\n\n• Synopsis and option list automated help.\n\n• Boolean, String, Int, Float64, Slice and Map type options.\n\n• Options with Array arguments.\nThe same option can be used multiple times with different arguments.\nThe list of arguments will be saved into an Slice.\n\n• Options with array arguments and multiple entries.\n+\nFor example, instead of writing:\n`color --r 10 --g 20 --b 30 --next-option`\nor\n`color --rgb 10 --rgb 20 --rgb 30 --next-option`\nthe input could be:\n`color --rgb 10 20 30 --next-option`\n\n• When using integer array options with multiple arguments, positive integer ranges are allowed.\n+\nFor example, Instead of writing:\n`csv --columns 1 2 3`\nor\n`csv --columns 1 --columns 2 --columns 3`\nThe input could be:\n`csv --columns 1..3`\n\n• Options with Key Value arguments.\nThis allows the same option to be used multiple times with arguments of key value type.\n+\nFor example: `rpmbuild --define name=myrpm --define version=123`\n\n• Options with key value arguments and multiple entries.\n+\nFor example, instead of writing:\n`connection --server hostname=serverIP --server port=123 --client hostname=localhost --client port=456`\nthe input could be:\n`connection --server hostname=serverIP port=123 --client hostname=localhost port=456`\n\n• Supports command line options with '='.\n+\nFor example: You can use `--string=mystring` and `--string mystring`.\n\n• Allows passing arguments to options that start with dash `-` when passed after equal.\n+\nFor example: `--string=--hello` and `--int=-123`.\n\n• Supports passing `--` to stop parsing arguments (everything after will be left in the `remaining []string`).\n\n• Options with optional arguments.\nIf the default argument is not passed the default is set.\n+\nFor example: You can call `--int 123` which yields `123` or `--int` which yields the given default.\n\n• Allows abbreviations when the provided option is not ambiguous.\n+\nFor example: An option called `build` can be called with `--b`, `--bu`, `--bui`, `--buil` and `--build` as long as there is no ambiguity.\nIn the case of ambiguity, the shortest non ambiguous combination is required.\n\n• Support for the lonesome dash \"-\".\nTo indicate, for example, when to read input from STDIO.\n\n• Incremental options.\nAllows the same option to be called multiple times to increment a counter.\n\n• Supports case sensitive options.\nFor example, you can use `v` to define `verbose` and `V` to define `Version`.\n\n• Support indicating if an option is required and allows overriding the default error message.\n\n• Errors and Help Strings exposed as public variables to allow overriding them for internationalization.\n\n• Supports program commands and subcommands (when a command is passed a command function is triggered to handle the command logic).\n\n• Built in `opt.Dispatch` function calls commands and propagates context, options, arguments and cancellation signals.\n\n• Multiple ways of managing unknown options:\n  - Fail on unknown (default).\n  - Warn on unknown.\n  - Pass through, allows for commands and can be combined with Require Order.\n\n• Require order: Allows for commands. Stop parsing arguments when the first non-option is found.\nWhen mixed with Pass through, it also stops parsing arguments when the first unmatched option is found.\n\n• Set options by reading Environment Variables.\nPrecedence is CLI option over Env Var over Default.\n\n== How to install it\n\n. Get it from github:\n+\n`go get github.com/DavidGamba/go-getoptions`\n\n. Then import it:\n+\n`import \"github.com/DavidGamba/go-getoptions\" // As getoptions`\n\n. Enjoy!\n\n== Dependencies\n\nGo 1.16+\n\nOnly the last two versions of Go will be supported.\n\n== Introduction\n\nNOTE: For a \u003c\u003cquick_overview\u003e\u003e, jump to that section in the TOC or review the http://godoc.org/github.com/DavidGamba/go-getoptions[GoDoc Documentation].\n\nOption parsing is the act of taking command line (CLI) arguments and converting them into meaningful structures within the program.\n\nFirst declare a `getoptions` instance:\n\n[source, go]\n----\nopt := getoptions.New()\n----\n\nThen declare the options you want to parse:\n\n[source, go]\n----\nopt.String(\"string\", \"default_value\")\n----\n\nOptionally, define option modifiers:\n\n[source, go]\n----\nopt.String(\"string\", \"default_value\",\n\n\topt.Alias(\"s\"),                             // Allow -s as an alias for --string\n\topt.Description(\"This is a string option\"), // Add a description to the option\n\topt.Required(),                             // Mark the option as required\n\topt.GetEnv(\"STRING\"),                       // Set the environment variable to read the option from\n\topt.ArgName(\"mystring\"),                    // Set the argument name for the help output\n\t                                            //   The help with show --string \u003cmystring\u003e instead of --string \u003cstring\u003e\n\topt.ValidValues(\"value1\", \"value2\"),        // Set the valid values for the option, these are used for autocompletion too\n\topt.SetCalled(true),                        // Forcefully set the option as if called in the CLI\n)\n----\n\nYou can also define arguments:\n\n[source, go]\n----\nopt.HelpSynopsisArg(\"\u003carg1\u003e\", \"arg1 description\")\nopt.HelpSynopsisArg(\"\u003carg2\u003e\", \"arg2 description\")\n----\n\nDefine the function for the program:\n\n----\nopt.SetCommandFn(Run)\n----\n\nIf no function is defined and `opt.Dispatch` is called, the program will show a help message with any commands or subcommands.\n\nDefine any commands and their options, arguments and functions:\n\n[source, go]\n----\ncmd := opt.NewCommand(\"command\", \"command description\")\ncmd.String(\"int\", 123)\ncmd.HelpSynopsisArg(\"\u003carg1\u003e\", \"arg1 description\")\ncmd.SetCommandFn(CommandRun)\n----\n\nNOTE: Options defined at a parent level will be inherited by the command unless `cmd.UnsetOptions()` is called.\n\nAfter defining options and commands declare the help command, it must be the last one defined.\n\n[source, go]\n----\nopt.HelpCommand(\"help\", opt.Alias(\"?\"))\n----\n\nParse the CLI arguments (or any `[]string`):\n\n[source, go]\n----\nremaining, err := opt.Parse(os.Args[1:])\n----\n\nFinally, call dispatch which will call the proper command function for the given arguments:\n\n[source, go]\n----\nerr = opt.Dispatch(ctx, remaining)\n----\n\nDispatch requires a `context.Context` to be passed which can be used to propagate cancellation signals or configuration values.\n\nA built in helper to create a context with cancellation support (`os.Interrupt`, `syscall.SIGHUP`, `syscall.SIGTERM`) is provided:\n\n[source, go]\n----\nctx, cancel, done := getoptions.InterruptContext()\ndefer func() { cancel(); \u003c-done }()\n\nerr = opt.Dispatch(ctx, remaining)\n----\n\nThe actual functions running the business logic are the `CommandFn` functions set with the `SetCommandFn`.\n\nThe `CommandFn` function signature is:\n\n[source, go]\n----\nfunc Name(ctx context.Context, opt *getoptions.GetOpt, args []string) error {\n\treturn nil\n}\n----\n\nThis function will receive the context, the parsed options and the remaining arguments.\n\nRead the received options from the `opt` variable.\n\n[source, go]\n----\nfunc Name(ctx context.Context, opt *getoptions.GetOpt, args []string) error {\n\tfile := opt.Value(\"file\").(string)\n\tcount := opt.Value(\"count\").(int)\n\ttags := opt.Value(\"tags\").(map[string]string)\n\n\t// logic\n\n\treturn nil\n}\n----\n\nNOTE: The `opt.Value` function returns an `interface{}` so it needs to be type casted to the proper type.\nThe type cast will panic if trying to read an option that is not defined.\n\nRead the received arguments from the `args` slice.\nAdditionally, use the `opt.GetRequiredArg` (with int and float64 variants) to simplify handling required arguments and providing error messages.\n\n[source, go]\n----\nfunc Name(ctx context.Context, opt *getoptions.GetOpt, args []string) error {\n\targ1, args, err := opt.GetRequiredArgInt(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// logic\n\n\treturn nil\n}\n----\n\n== Automatically generate help\n\nFor a proper extended man page for your program consider link:http://asciidoctor.org/[asciidoctor] that can generate manpages written in the Asciidoc markup.\n\nFor the built-in help, you can add a description to your program:\n\n- `opt.Self(\"\", \"This is a program description\")`\n\nNOTE: When the first argument is empty, it will use the program name from `os.Args[0]`.\n\nFor options help ensure you add option descriptions and argument names.\n\n- `opt.Description(\"This is a string option\")`\n- `opt.ArgName(\"mystring\")`\n\nThe help command needs to be defined after all options, commands and subcommands.\n\n`opt.HelpCommand(\"help\", opt.Alias(\"?\"))`\n\nWhen calling the help command, you get the full help.\nOptionally you can print only given sections of the Help.\n\nFor example:\n\n[source, go]\n----\nfmt.Fprintf(os.Stderr, \"%s\", opt.Help(getoptions.HelpSynopsis))\n----\n\nOr through a helper:\n\n[source, go]\n----\nfunc ForceUnlock(ctx context.Context, opt *getoptions.GetOpt, args []string) error {\n\tlockID, args, err := opt.GetRequiredArg(args)\n\tif err != nil {\n\t\treturn err\n\t}\n----\n\nIn the code above, if there is no argument passed, the `GetRequiredArg` will print an error plus the synopsis:\n\n----\nERROR: Missing \u003clock-id\u003e\nSYNOPSIS:\n    program [--help] \u003clock-id\u003e\n----\n\nThe error return is `getoptions.ErrorHelpCalled` which signals the help is already printed.\nThe dispatch error handling can handle this error and not print and additional error message.\n\n\n[source, go]\n----\n\terr = opt.Dispatch(ctx, remaining)\n\tif err != nil {\n\t\tif errors.Is(err, getoptions.ErrorHelpCalled) {\n\t\t\treturn 1\n\t\t}\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %s\\n\", err)\n\t\tif errors.Is(err, getoptions.ErrorParsing) {\n\t\t\tfmt.Fprintf(os.Stderr, \"\\n\"+opt.Help())\n\t\t}\n\t\treturn 1\n\t}\n\treturn 0\n----\n\nAnother helpful error to check for is `getoptions.ErrorParsing`, as shown above, which indicates there was a problem parsing the CLI arguments.\nThis can be used, to print the help only in cases where the user didn't enter valid CLI options or arguments.\n\nThe built in help shows default values and environment variables when available.\n\nIt separates _COMMANDS_, _ARGUMENTS_, _REQUIRED PARAMETERS_ and _OPTIONS_ into separate sections.\n\nFor example, the following is a script using the built in help:\n\n----\n$ bt terraform force-unlock help\nNAME:\n    bt terraform force-unlock\n\nSYNOPSIS:\n    bt terraform force-unlock [--help|-?] [--profile \u003cstring\u003e] [--quiet]\n                              [--ws \u003cstring\u003e] \u003clock-id\u003e\n\nARGUMENTS:\n    \u003clock-id\u003e             Lock ID\n\nOPTIONS:\n    --help|-?             (default: false)\n\n    --profile \u003cstring\u003e    BT Terraform Profile to use (default: \"default\", env: AWS_PROFILE)\n\n    --quiet               (default: false, env: QUIET)\n\n    --ws \u003cstring\u003e         Workspace to use (default: \"\")\n----\n\nAnd below is the output of the automated help of a program with multiple commands:\n\n----\n$ tz help\nSYNOPSIS:\n    tz [--config|-c \u003cstring\u003e] [--format-standard|--format-12-hour|--format-12h]\n       [--group \u003cstring\u003e] [--help|-?] [--short|-s] [--verbose] \u003ccommand\u003e [\u003cargs\u003e]\n\nCOMMANDS:\n    cities     filter cities list\n    list       list all timezones\n    version    show version\n\nOPTIONS:\n    --config|-c \u003cstring\u003e                               Config file (default: \"\")\n\n    --format-standard|--format-12-hour|--format-12h    Use standard 12 hour AM/PM time format (default: false)\n\n    --group \u003cstring\u003e                                   Group to show (default: \"\")\n\n    --help|-?                                          (default: false)\n\n    --short|-s                                         Don't show timezone bars (default: false)\n\n    --verbose                                          Enable logging (default: false, env: TZ_VERBOSE)\n\nUse 'tz help \u003ccommand\u003e' for extra details.\n----\n\nAny built-in string in `go-getoptions`, like titles, is exposed as a public variable so it can be overridden for internationalization.\n\n== Autocompletion\n\nTo enable bash autocompletion, add the following line to your bash profile:\n\n[source,bash]\n----\ncomplete -o default -C my-go-program my-go-program\n----\n\nFor the above to work, the program must be in the PATH.\nOtherwise:\n\n[source,bash]\n----\ncomplete -o default -C \"$HOME/go/bin/my-go-program\" my-go-program\n----\n\nTo enable zsh autocompletion, add the following line to your zsh profile:\n\n[source,zsh]\n----\nexport ZSHELL=\"true\"\nautoload -U +X compinit \u0026\u0026 compinit\nautoload -U +X bashcompinit \u0026\u0026 bashcompinit\ncomplete -o default -C my-go-program my-go-program\n----\n\nThe `ZSHELL=\"true\"` export is required because bash and zsh have different ways of handling autocompletion and there is no reliable way to detect which shell is being used.\n\nIf testing completion in the CLI, you might require to first clean the completion entry that `complete` auto generates when hitting `Tab` twice:\n\n`complete -r ./my-go-program 2\u003e/dev/null`\n\nWhen providing these as scripts that users source but not add into their profile you can use the following `sourceme.bash` script:\n\n.sourceme.bash\n[source,bash]\n----\n#!/bin/bash\n\n# Remove existing entries to ensure the right one is loaded\n# This is not required when the completion one liner is loaded in your bashrc.\ncomplete -r ./my-go-program 2\u003e/dev/null\n\ncomplete -o default -C \"$PWD/my-go-program\" my-go-program\n----\n\nThen when the users go into the directory and run `source sourceme.bash` the autocompletion will be enabled.\n\n== Options\n\n=== Boolean options\n\nOpposite of default when passed on the command line.\n\n- `ptr := opt.Bool(name, false)`\n- `opt.BoolVar(\u0026ptr, name, false)`\n- Additionally, if all you want to know is if the option was passed you can use: `opt.Bool(name, false)` (without capturing its return value) and then check `opt.Called(name)`.\n- Also, you can get the value with `v, ok := opt.Value(name).(bool)`.\n\nFor example:\n\n`ls --all`\n\n=== Options with String arguments\n\nThe option will accept a string argument.\n\n- `ptr := opt.String(name, \"default\")`.\n- `opt.StringVar(\u0026ptr, name, \"default\")`.\n\nFor example:\n\n`grepp --ignore .txt`\n\nAdditionally, arguments to options can be passed with the `=` symbol.\n\n`grepp --ignore=.txt` or `count --from=-123`\n\n=== Options with Integer arguments\n\nParse an option string argument into an Integer and provide an user error if the string provided is not an integer.\n\n- `ptr := opt.Int(name, 0)`.\n- `opt.IntVar(\u0026ptr, name, 0)`.\n\nFor example:\n\n`grepp --contex-lines 3`\n\nand:\n\n`grepp --context-lines string`\n\n  Error: 'string' is not a valid integer.\n\n=== Options with Floating point arguments\n\nParse an option string argument into a Floating point value and provide an user error if the string provided is not a valid floating point.\n\n- `ptr := opt.Float64(name, 3.14)`.\n- `opt.Float64Var(\u0026ptr, name, 3.14)`.\n\nFor example:\n\n`program --approximation 3.5`\n\nand:\n\n----\n$ program --approximation string\n\nError: 'string' is not a valid floating point value.\n----\n\n=== Options with array arguments\n\nThis allows the same option to be used multiple times with different arguments.\nThe list of arguments will be saved into a Slice inside the program.\n\n- `ptr := opt.StringSlice(name, 1, 99)`.\n- `opt.StringSliceVar(\u0026ptr, name, 1, 99)`.\n- `ptr := opt.IntSlice(name, 1, 99)`.\n- `opt.IntSliceVar(\u0026ptr, name, 1, 99)`.\n- `ptr := opt.Float64Slice(name, 1, 99)`.\n- `opt.Float64SliceVar(\u0026ptr, name, 1, 99)`.\n\nFor example:\n\n`list-files --exclude .txt --exclude .html --exclude .pdf`\n\nor:\n\n`list-files --exclude .txt .html .pdf`\n\nThe setup for this feature should allow for the user to continue using both versions of the input, that is passing one argument at a time or passing the 3 arguments at once, or allow the setup to force the user to have to use the 3 arguments at once version.\nThis is accomplished with the minimum and maximum setup parameters.\n\nThe minimum setup parameter indicates the minimum amount of parameters the user can pass at a time.\nFor the example above, the parameter could be set to 3 to force the user to have to pass the 3 arguments at once.\nWhen set to 1, the user will be able to pass a single parameter per option call.\n\nThe maximum setup parameter indicates the maximum amount of parameters the user can pass at a time.\nThe option parser will leave any non option argument after the maximum in the `remaining` slice.\n\nGood defaults are `1` and `99`.\n\nAdditionally, in the case of integers, positive integer ranges are allowed.\nFor example:\n\nInstead of writing: `csv --columns 1 2 3` or `csv --columns 1 --columns 2 --columns 3`\n\nThe input could be: `csv --columns 1..3`.\n\n=== Options with Key Value arguments\n\nThis allows the same option to be used multiple times with arguments of key value type.\n\n- `strMap := opt.StringMap(name, 1, 99)`.\n- `opt.StringMapVar(\u0026ptr, name, 1, 99)`.\n\nFor example:\n\n`rpmbuild --define name=myrpm --define version=123`\n\nor:\n\n`rpmbuild --define name=myrpm version=123`\n\nAlso, instead of writing: `connection --server hostname=serverIP --server port=123 --client hostname=localhost --client port=456`\n\nThe input could be: `connection --server hostname=serverIP port=123 --client hostname=localhost port=456`\n\n=== Incremental option\n\n- `ptr := opt.Increment(name, default_value)`.\n- `opt.IncrementVar(\u0026ptr, name, default_value)`.\n\nSome options can be passed more than once to increment an internal counter.\nFor example:\n\n`command --v --v --v`\n\nCould increase the verbosity level each time the option is passed.\n\n=== Options with optional arguments\n\n- `ptr := opt.StringOptional(name, default_value)`.\n- `ptr := opt.IntOptional(name, default_value)`.\n- `ptr := opt.Float64Optional(name, default_value)`.\n- The above should be used in combination with `opt.Called(name)`.\n\nWith regular options, when the argument is not passed (for example: `--level` instead of `--level=debug`) you will get a _Missing argument_ error.\nWhen using options with optional arguments, If the argument is not passed, the option will set the default value for the option type.\nFor this feature to be fully effective in strong typed languages where types have defaults, there must be a means to query the option parser to determine whether or not the option was called.\n\nFor example, for the following definition:\n\n`ptr := opt.StringOptional(\"level\", \"info\")`\n\n* If the option `level` is called with just `--level`, the value of `*ptr` is the default `\"info\"` and querying `opt.Called(\"level\")` returns `true`.\n* If the option `level` is called with `--level=debug`, the value of `*ptr` is `\"debug\"` and querying `opt.Called(\"level\")` returns `true`.\n* Finally, If the option `level` is not called, the value of `*ptr` is the default `\"info\"` and querying `opt.Called(\"level\")` returns `false`.\n\n=== Stop parsing options when `--` is passed\n\nUseful when arguments start with dash `-` and you don't want them interpreted as options.\n\n=== Allow passing options and non-options in any order\n\nSome option parsers force you to put the options before or after the arguments.\nThat is really annoying!\n\nThe `go-getoptions` parser knows when to expect arguments for an option so they can be intermixed with arguments without issues.\n\n=== Allow pass through\n\n- `opt.SetUnknownMode(getoptions.Pass)`.\n\nHave an option to pass through unmatched options.\nUseful when writing programs with multiple options depending on the main arguments.\nThe initial parser will only capture the help or global options and pass through everything else.\nAdditional argument parsing calls are invoked on the remaining arguments based on the initial input.\n\n=== Fail on unknown\n\nThe opposite of the above option.\nUseful if you want to ensure there are no input mistakes and force the application to stop.\n\nIn `go-getoptions` this is the default behaviour.\n\nIt can be explicitly set with:\n\n`opt.SetUnknownMode(getoptions.Fail)`.\n\n=== Warn on unknown\n\nLess strict parsing of options.\nThis will warn the user that the option used is not a valid option but it will not stop the rest of the program.\n\nIn `go-getoptions` this is accomplished with:\n\n- `opt.SetUnknownMode(getoptions.Warn)`.\n\n=== Option Modifiers (ModifyFn)\n\n==== Aliases\n\n`opt.BoolVar(\u0026flag, \"flag\", false, opt.Alias(\"alias\", \"alias-2\"))`\n\nUse `opt.CalledAs(\u003cname\u003e)` to determine the alias used to call the option.\n\n==== Description\n\n`opt.BoolVar(\u0026flag, \"flag\", false, opt.Description(\"This is a flag\"))`\n\nAdd a description to the option.\n\n==== Required options\n\n`opt.BoolVar(\u0026flag, \"flag\", false, opt.Required())`\n\nMark an option as required.\nReturn an error if the option is not called.\n\nOptionally, override the default error message with `opt.Required(msg)`.\nFor example:\n\n`opt.BoolVar(\u0026flag, \"flag\", false, opt.Required(\"Missing --flag!\"))`\n\n==== Read option value from environment variable\n\n`opt.BoolVar(\u0026flag, \"flag\", false, opt.GetEnv(\"FLAG\"))`\n\nPrecedence is CLI option over Env Var over Default.\n\nSupported for the following types:\n- `opt.Bool` and `opt.BoolVar`\n- `opt.String`, `opt.StringVar`, `opt.StringOptional`, and `opt.StringVarOptional`\n- `opt.Int`, `opt.IntVar`, `opt.IntOptional`, and `opt.IntVarOptional`\n- `opt.Float64`, `opt.Float64Var`, `opt.Float64Optional`, and `opt.Float64VarOptional`\n\nNOTE: Non supported option types behave with a No-Op when `opt.GetEnv` is defined.\n\nWhen using `opt.GetEnv` with `opt.Bool` or `opt.BoolVar`, only the words \"true\" or \"false\" are valid.\nThey can be provided in any casing, for example: \"true\", \"True\" or \"TRUE\".\n\nNOTE: For numeric values, `opt.Int` and `opt.Float64` and their derivatives, environment variable string conversion errors are ignored and the default value is assigned.\n\n==== Help argument name hint\n\n`opt.StringVar(\u0026str, \"str\", false, opt.ArgName(\"my_arg_name\"))`\n\nThe default help string for an option is:\n\n- string: \"\u003cstring\u003e\"\n- int: \"\u003cint\u003e\"\n- float64: \"\u003cfloat64\u003e\"\n\nOverride it with `opt.ArgName(\"my_arg_name\")`.\nIt additionally shows in the autocompletion hints.\n\n==== Suggested values\n\n`opt.StringVar(\u0026str, \"str\", false, opt.SuggestedValues(\"value1\", \"value2\"))`\n\nThis list will be added to the autocompletion engine.\n\n==== Valid values\n\n`opt.StringVar(\u0026str, \"str\", false, opt.ValidValues(\"value1\", \"value2\"))`\n\nLimit the list of valid values for the option.\nThis list will be added to the autocompletion engine.\n\n==== Set option as called\n\n`opt.StringVar(\u0026str, \"str\", false, opt.SetCalled(true))`\n\nWhen calling `CommandFn` directly, it is sometimes useful to set the option as called.\nUse cases are for testing and wrappers.\n\n[[operation_modes]]\n== Operation Modes: How to handle single dash '-' options\n\nNotice how so far only long options (options starting with double dash `--`) have been mentioned.\nThere are 3 main ways to handle short options (options starting with only one dash `-`).\n\nThe behaviour for long options (options starting with double dash `--`) is consistent across operation modes.\nThe behaviour for short options (options starting with only one dash `-`) depends on the _operation mode_.\nThe sections below show the different operation modes.\n\n=== Normal Mode (default)\n\n|===\n|Given argument |Interpretation\n\n|--opt\na|option: `\"opt\"`,  argument: `nil`\n\n|--opt=arg\na|option: `\"opt\"`, argument: `\"arg\"` footnote:[Argument gets type casted depending on option definition.]\n\n|-opt\na|option: `\"opt\"`, argument: `nil`\n\n|-opt=arg\na|option: `\"opt\"`, argument: `\"arg\"` footnote:[Argument gets type casted depending on option definition.]\n\n|===\n\n=== Bundling Mode\n\nSet by defining `opt.SetMode(getoptions.Bundling)`.\n\n|===\n|Given option |Interpretation\n\n|--opt\na|option: `\"opt\"`,  argument: `nil`\n\n|--opt=arg\na|option: `\"opt\"`, argument: `\"arg\"` footnote:[Argument gets type casted depending on option definition.]\n\n|-opt\na|option: `\"o\"`, argument: `nil` +\noption: `\"p\"`, argument: `nil` +\noption: `\"t\"`, argument: `nil`\n\n|-opt=arg\na|option: `\"o\"`, argument: `nil` +\noption: `\"p\"`, argument: `nil` +\noption: `\"t\"`, argument: `\"arg\"` footnote:[Argument gets type casted depending on option definition.]\n\n|===\n\n=== Enforce Single Dash Mode\n\nSet by defining `opt.SetMode(getoptions.SingleDash)`.\n\n|===\n|Given option |Interpretation\n\n|--opt\na|option: `\"opt\"`,  argument: `nil`\n\n|--opt=arg\na|option: `\"opt\"`, argument: `\"arg\"` footnote:[Argument gets type casted depending on option definition.]\n\n|-opt\na|option: `\"o\"`, argument: `\"pt\"` footnote:[Argument gets type casted depending on option definition.]\n\n|-opt=arg\na|option: `\"o\"`, argument: `\"pt=arg\"` footnote:[Argument gets type casted depending on option definition.]\n\n|===\n\n== Command behaviour\n\nThis section describes how the parser resolves ambiguities between the program and the command.\n\nGiven a definition like:\n\n[source, go]\n----\nfunc main() {\n\tvar profile, password string\n\topt := New()\n\topt.SetUnknownMode(Pass)\n\topt.StringVar(\u0026profile, \"profile\", \"\")\n\tcommand := NewCommand()\n\tcommand.StringVar(\u0026password, \"password\", \"\")\n\topt.Command(command.Self(\"command\", \"\").SetCommandFn(commandFn))\n\tremaining, err := opt.Parse(os.Args[1:])\n\t...\n\terr = opt.Dispatch(\"help\", remaining)\n\t...\n}\n\nfunc commandFn(opt *getoptions.GetOpt, args []string) error {\n\targs, err := opt.Parse(remaining)\n\t...\n}\n----\n\nThere is an option at the parent, `profile` and one at the command, `password`.\nPassing `--p \u003carg\u003e` is ambiguous and results in an error.\nAt minimum, `--pr \u003carg\u003e` and `--pa \u003carg\u003e` are required.\n\nGiven a definition like:\n\n[source, go]\n----\nfunc main() {\n\tvar profile, password string\n\topt := New()\n\topt.SetUnknownMode(Pass)\n\topt.StringVar(\u0026profile, \"profile\", \"\")\n\tcommand := NewCommand()\n\tcommand.StringVar(\u0026password, \"password\", \"\", opt.Alias(\"p\"))\n\topt.Command(command.Self(\"command\", \"\").SetCommandFn(commandFn))\n\tremaining, err := opt.Parse(os.Args[1:])\n\t...\n\terr = opt.Dispatch(\"help\", remaining)\n\t...\n}\n\nfunc commandFn(opt *getoptions.GetOpt, args []string) error {\n\targs, err := opt.Parse(remaining)\n\t...\n}\n----\n\nThere is an option at the parent, `profile` and one at the command, `password` with alias `p`.\nPassing `--p \u003carg\u003e` at the parent results in the parent `opt.Parse` call to leave the `--p \u003carg\u003e` option unhandled and leave it in the remaining slice.\nThe `opt.Dispatch` call gets the `-p \u003carg\u003e` option and throws an error.\nAt minimum, `--pr \u003carg\u003e` is required to call `profile` at the parent and command options must be passed after the command declaration.\n\nFor example, the calls below is correct:\n\n\t$ ./program -pr \u003cprofile\u003e command -p \u003cpassword\u003e\n\n\t$ ./program command -pr \u003cprofile\u003e -p \u003cpassword\u003e\n\nBut the following one is incorrect:\n\n\t./program -pr \u003cprofile\u003e -p \u003cpassword\u003e command\n\n[[roadmap]]\n== ROADMAP\n\n* Generate compilation errors for commands without a defined `CommandFn`.\n\n* Create new error description for errors when parsing integer ranges (`1..3`).\n\n* Case insensitive matching.\n\n* prefix and prefix_pattern.\nThe string that starts options.\nDefaults to \"--\" and \"-\" but could include \"/\" to support Win32 style argument handling.\n\n* Allow grouping commands so they can have a different order other than alphabetical in the help output.\n\n* Some Windows tests fail because the binary name includes .exe at the end.\nUpdate test suite to accommodate for Windows.\n\n* Introduce a `opt.NoArgs` so there are no `[\u003cargs\u003e]` listed in the help output.\n\n* Add `CustomCompletionFn` before release figure out how to have ways to have custom completions with different engines for arg1 and arg2.\n\n* Figure out how to have custom completions for option values.\n\n* Add OptionGroup to allow grouping options in the help output.\n\n* Document CustomCompletion and ValidValues in autocompletion section.\n\n* Mark optional as required in subcommand.\n\n=== Possible Env Variable Roadmap\n\nThe Roadmap isn't clear given that there might not be enough value in implementing all of them.\n\n* Handle `opt.Int` and `opt.Float64` errors.\n\nStringSlice and StringSliceVar:: Comma separated? \u003c- Most likely\n+\nComma space separated?\nProper CSV parsing to allow comma escaping?\n\nIntSlice and IntSliceVar:: Comma separated?\n\nStringMap and StringMapVar:: Comma separated key=value?\n\n== License\n\nThis file is part of go-getoptions.\n\nCopyright (C) 2015-2024  David Gamba Rios\n\nThis Source Code Form is subject to the terms of the Mozilla Public\nLicense, v. 2.0. If a copy of the MPL was not distributed with this\nfile, You can obtain one at http://mozilla.org/MPL/2.0/.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDavidGamba%2Fgo-getoptions","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FDavidGamba%2Fgo-getoptions","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FDavidGamba%2Fgo-getoptions/lists"}