{"id":22758647,"url":"https://github.com/mjpclab/gonixargparser","last_synced_at":"2025-03-30T08:25:38.356Z","repository":{"id":61628235,"uuid":"214598982","full_name":"mjpclab/goNixArgParser","owner":"mjpclab","description":"Unix/Linux style cli args parser for Go","archived":false,"fork":false,"pushed_at":"2024-06-01T14:10:39.000Z","size":89,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-02-05T10:30:57.945Z","etag":null,"topics":["arg","cli","go","golang","parser"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mjpclab.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"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}},"created_at":"2019-10-12T07:20:50.000Z","updated_at":"2024-06-01T14:10:42.000Z","dependencies_parsed_at":"2024-06-01T15:52:00.912Z","dependency_job_id":"6f620cfd-7606-468a-a9c7-bc66a38f5e09","html_url":"https://github.com/mjpclab/goNixArgParser","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mjpclab%2FgoNixArgParser","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mjpclab%2FgoNixArgParser/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mjpclab%2FgoNixArgParser/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mjpclab%2FgoNixArgParser/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mjpclab","download_url":"https://codeload.github.com/mjpclab/goNixArgParser/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246292924,"owners_count":20754143,"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":["arg","cli","go","golang","parser"],"created_at":"2024-12-11T08:15:09.062Z","updated_at":"2025-03-30T08:25:38.334Z","avatar_url":"https://github.com/mjpclab.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# goNixArgParser - Unix/Linux style cli args parser for Go\n\n## Pre-requirement\nMinimal required Go version is 1.16.\n\n## Concepts\nCommand line arguments may contains several kinds of parts:\n- Command and Sub Command\n- Option\n    - Flag\n    - Value\n- Rest\n\n## Example\nHere is an example for command `git remote`:\n```\n| Command | Sub Command | Sub Command |    Option     | Option |  Rest   |                Rest                 |\n|         |             |             | Flag | Value  |  Flag  |         |                                     |\n----------------------------------------------------------------------------------------------------------------\n    git       remote          add        -t    master     -f      origin    https://repo.server.com/project.git\n----------------------------------------------------------------------------------------------------------------\n```\n\n# Step 1 - Define Schema\n## Root Command\n```go\ncmdGit := goNixArgParser.NewSimpleCommand(\"git\", \"A version control tool\")\n```\n\n## Sub Commands\n```go\ncmdRemote := cmdGit.NewSimpleSubCommand(\"remote\", \"manage remotes\")\ncmdAdd := cmdRemote.NewSimpleSubCommand(\"add\", \"add a remote repository\")\n```\n\nCommand alias names can be specified as additional arguments:\n```go\n// \"co\" and \"ckout\" are alias names of \"checkout\" command\ncmdCheckout := cmdGit.NewSimpleSubCommand(\"checkout\", \"checkout branches or files\", \"co\", \"ckout\")\n```\n\n## Options\nHere we want to define options on `cmdAdd` for `git remote add`. But if no sub command is needed, then just define them on root Command.\nGet `*OptionSet` of the command first:\n```go\naddOpts := cmdAdd.Options()\n```\n\nAvailable methods on `*OptionSet`:\n- `AddFlag(key, flag, envVar, summary string)`  // single flag, without values\n- `AddFlags(key string, flags []string, envVar, summary string)`  // multiple flag, without values\n- `AddFlagValue(key, flag, envVar, defaultValue, summary string)`  // single flag, single value\n- `AddFlagValues(key, flag, envVar string, defaultValues []string, summary string)`  // single flag, multiple values\n- `AddFlagsValue(key string, flags []string, envVar, defaultValue, summary string)` // multiple flags, single value\n- `AddFlagsValues(key string, flags []string, envVar string, defaultValues []string, summary string)`  / multiple flags, multiple values\n\n`key` is a unique option name in `Options`.\n\n```go\naddOpts.AddFlagValue(\"track\", \"-t\", \"\", \"\", \"only track specified branch\")\naddOpts.AddFlag(\"fetch\", \"-f\", \"\", \"fetch after added\")\n```\n\n# Step 2 - Parse\n```go\n// os.Args == []string{\"git\", \"remote\", \"add\", \"-t\", \"master\", \"-f\", \"origin\", \"https://repo.server.com/project.git\"}\nresults := cmdGit.Parse(os.Args, nil)\n```\n# Step 3 - Get Results\nThere are several methods on parsed result to get final values:\n- `HasKey(key string) bool`\n- `GetString(key string) (value string, found bool)`\n- `GetBool(key string) (value bool, found bool)`\n- `GetInt(key string) (value int, found bool)`\n- `GetInt64(key string) (value int64, found bool)`\n- `GetUint64(key string) (value uint64, found bool)`\n- `GetFloat64(key string) (value float64, found bool)`\n- `GetStrings(key string) (values []string, found bool)`\n- `GetBools(key string) (values []bool, found bool)`\n- `GetInts(key string) (values []int, found bool)`\n- `GetInt64s(key string) (values []int64, found bool)`\n- `GetUint64s(key string) (values []uint64, found bool)`\n- `GetFloat64s(key string) (values []float64, found bool)`\n- `GetRests() (rests []string)`\n- `HasAmbigu() bool`\n- `GetAmbigus() []string`\n- `HasUndef() bool`\n- `GetUndefs() []string`\n\nGetting value for the example above:\n```go\ncmdPath := results.GetCommands()\nif cmdPath[1] == \"remote\" \u0026\u0026 cmdPath[2] == \"add\" {\n    if track, _ := results.GetString(\"track\"); track != \"\" {\n      // \"-t\" is supplied\n    }\n    if results.HasKey(\"fetch\") {\n      // \"-f\" is supplied\n    }\n}\n```\n\n# Configs\nOne application may have external config file. When application starts, it reads both command line args and config file.\nGenerally, the command line args is prior than config file.\nThe parser provides a quick and easy way to deal with this situation on parsing, if the contents of config are a list of arguments,\nsimilar to the form of command line args.\nThe root command of config args can be omitted.\n\n```go\ncliArgs := []string{\"cmd\", \"subCmd\", \"subSubCmd\", \"--option1\", \"value1\"}\nconfigArgs := []string{\"cmd\", \"subCmd\", \"subSubCmd\", \"--option1\", \"value1FromConfig\", \"--option2\", \"value2FromConfig\"}\n// configArgs = configArgs[1:]  // omit root command\nresult := cmd.Parse(cliArgs, configArgs)\n\noption1 := result.GetString(\"option1\")  // \"value1\"\noption2 := result.GetString(\"option2\")  // \"value2FromConfig\"\n```\n\n# Env Var \u0026 Default Value\nAn option value can be set by Env var if it is not specified by other ways.\nAn option's related Env var can be specified when defining schema.\n\nAn option value can be set by default value if it is not specified by other ways.\nAn option's related default value can be specified when defining schema.\n\n# Priority\nThe priority of getting an option's value is:\n- input arg\n- Env var\n- config item\n- default value\n\n# Arg Groups\nSometimes a command may do tasks for multiple targets of a kind, e.g. start multiple spare services with different options.\nBy default, the parser treat `,,` as the separator of arg groups. Use `ParseGroups` instead of `Parse`,\nReturns slice of parsed result for each group.\n```go\ncliArgs := []string{\"cmd\", \"subCmd\", \"subSubCmd\", \"--option\", \"value1\", \",,\", \"--option\",\"value2\"}\nresults := cmd.ParseGroups(cliArgs, nil)\n\nservice0option := results[0].GetString(\"optionKey\")  // \"value1\"\nservice1option := results[1].GetString(\"optionKey\")  // \"value2\"\n```\n\nSimilar to `Parse`, The second parameter of `ParseGroups` is groups of config args, each group is related to its input arg groups by index,\nand root command can be omitted.\n```go\ncliArgs := []string{\"cmd\", \"subCmd\", \"subSubCmd\", \"--optionX\", \"valueX1\", \",,\", \"--optionY\",\"valueY2\"}\nconfigArgs := []string{\"cmd\", \"subCmd\", \"subSubCmd\", \"--optionX\", \"valueX1FromConfig\", \",,\", \"--optionX\", \"valueX2FromConfig\"}\n// configArgs = configArgs[1:]  // omit root command\nresults := cmd.ParseGroups(cliArgs, nil)\n\nservice0option := results[0].GetString(\"optionXKey\")  // \"valueX1\"\nservice1option := results[1].GetString(\"optionXKey\")  // \"valueX2FromConfig\"\n```\n\nif arg group separator is the last arg, then there is an empty option set follows.\n\n# Control the Detail\nWhen defining schemas, methods like `NewSimpleXXX` on command, or `AddXXX` on options,\nare shortcuts that hides detail of bottom layer.\nIf you want to control or customize on more detail level, then the following part explains.\n- Use `NewCommand` to create command schema manually.\n- Use `command.Options()` go get `*OptionSet`\n- Create Option value manually\n- use `*OptionSet.Add(Option)` to add option schema manually. \n- use `NewFlag` to create flag schema manually, and add to `Option.Flags`.\n\n## Command struct\nBoth root command and sub commands are of type `*Command`. Initial parameters:\n\n### `name`\nCommand or sub command name used for parsing\n\n### `summary`\nSummary about the command, which will be shown when invoking `OutputHelp(io.Writer)` method\n\n## OptionSet struct\nOne OptionSet manages all options supported by its command or sub command. Initial parameters:\n\n### `mergeFlagPrefix`\nSpecify the prefix of flag that can be merged together. For example, following commands are equal:\n```sh\nls -a -l\nls -al\n```\nThe `-a` and `-l` are merged with the same prefix `-`.\nFlag names which has only 1 suffix character can be merged.\n\n### `restsSigns`\nSometimes we want to specify rest args explicitly, e.g. for \"git checkout\":\n```sh\ngit checkout -- file1 file2 file3\n```\nHere `--` is a rests sign. It can be specified by other values when initializing an OptionSet.\n\n### `groupSeps`\n`groupSeps` is the separator to split \"Arg Groups\". Can be customized when initializing an OptionSet.\n\n### `assignSigns`\nSpecify symbols (e.g `=`) as assign symbols, separate value to its flag. Example for `=` assign:\n```sh\nls --hide='*.go'\n```\n\n### `undefFlagPrefixes`\nIf an argument is not a flag, and begin with one of the `undefFlagPrefixes`, treat it as an undefined flag.\nOtherwise, treat this argument as previous flag's value or rests value.\nUseful if end user inputs an undefined flag\n\n## Option struct\n`Option` represents an individual option. Some initial parameter:\n\n### `AcceptValue`\nSpecifies if this option is flag only or can receive values.\n\n### `MultiValues`\nFor option that can receive values, specify if it accepts multiple values.\n\n### `OverridePrev`\nFor option that accepts values, when it is supplied by multiple times, specify if the later one will override the previous one.\nFor multiple-value option, if `OverridePrev` is `false`, then later items will be appended to previous.\n\n### `Delimiters`\nA multiple-value option's values can be supplied as a string separated by `Delimiters`.\nFollowing args have the same effect if delimiter is `,`:\n```sh\ncmd subCmd --option value1,value2,value3\ncmd subCmd --option value1 --option value2 --option value3\n```\n\n### `UniqueValues`\nRemove duplicated values for parsed result automatically if true.\n\n### `EnvVars`\nEnv var names for the option as fallback if option is not supplied.\nWill look into it one by one util find a non-empty value.\nMultiple-value option's value should be separated by `Delimiters`.\n\n### `DefaultValues`\nDefault values for the option as fallback if option is not supplied.\nFor option that only accepts single value, only first element is valid.\n\n### Shortcut functions to create Option with flags:\n- `NewFlagOption(key, flag, envVar, summary string) Option`  // single flag, without values\n- `NewFlagsOption(key string, flags []string, envVar, summary string) Option`  // multiple flag, without values\n- `NewFlagValueOption(key, flag, envVar, defaultValue, summary string) Option`  // single flag, single value\n- `NewFlagValuesOption(key, flag, envVar string, defaultValues []string, summary string) Option`  // single flag, multiple values\n- `NewFlagsValueOption(key string, flags []string, envVar, defaultValue, summary string) Option` // multiple flags, single value\n- `NewFlagsValuesOption(key string, flags []string, envVar string, defaultValues []string, summary string) Option`  / multiple flags, multiple values\n\n## Flag struct\n`Flag` represents a flag of option. Some initial parameter:\n\n### `Name`\nName of the flag, e.g. `--option-name`.\n\n### `canMerge`\nSpecify if this flag can be merged with others when the name starts with OptionSet's `mergeFlagPrefix` and suffix has only 1 character.\n\n### `prefixMatchLen`\nSpecify if can use at least `prefixMatchLen` chars to figure out unique flag instead of full name.\nif value is `0`, prefix match is disabled.\n\n### `canFollowAssign`\nSpecify if treat args that follow after a flag as option values. Example for follow assign:\n```sh\nls --hide '*.go'\n```\n\n### `canConcatAssign`\nSpecify if option value can be concatenated after flag name, like `mysql` client tool:\n```sh\nmysql -uroot\n# same as:\nmysql -u root\n```\n\n## Creating Custom Command Schema\nUse `NewCommand` to create a customized Command, instead of `NewSimpleCommand`:\n```go\nfunc NewCommand(\n\tnames []string,\n\tsummary, mergeFlagPrefix string,\n\trestsSigns, groupSeps, assignSigns, undefFlagPrefixes []string,\n) *Command\n```\n\nSimilarly, use `NewSubCommand` instead of `NewSimpleSubCommand` to create a sub command:\n```go\nfunc (c *Command) NewSubCommand(\n\tnames []string,\n\tsummary, mergeFlagPrefix string,\n\trestsSigns, groupSeps, assignSigns, undefFlagPrefixes []string,\n) *Command\n```\n\n## Creating Custom Option Schema\nOption is defined on `*OptionSet`, which can be got by `*Command.Options()`.\nUse `*OptionSet.Append` to create a customized option, instead of the `AddXXX` method:\n```go\nfunc (s *OptionSet) Append(opt *Option) error\n\ntype Option struct {\n\tKey           string\n\tSummary       string\n\tDescription   string\n\tFlags         []*Flag\n\tAcceptValue   bool\n\tMultiValues   bool\n\tOverridePrev  bool\n\tDelimiters    []rune\n\tUniqueValues  bool\n\tEnvVars       []string\n\tDefaultValues []string\n}\n```\n\n## Creating Custom Flag Schema\n`Option.Flags` is a slice of `*Flag`, Some useful functions to create them:\n```go\nfunc NewFlag(name string, canMerge, canFollowAssign, canConcatAssign bool) *Flag\nfunc NewSimpleFlag(name string) *Flag\nfunc NewSimpleFlags(names []string) []*Flag\n```\n\n## Helper funcs\n### func SplitToArgs(input string) (args []string)\nSplit string into args.\n\n### func LoadConfigArgs(filename string) (args []string, err error)\nLoad config from file and split into args. Use \"-\" for standard input.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmjpclab%2Fgonixargparser","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmjpclab%2Fgonixargparser","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmjpclab%2Fgonixargparser/lists"}