Skip to content

Commit

Permalink
Merge pull request #6 from rsteube/optarg
Browse files Browse the repository at this point in the history
optarg support
  • Loading branch information
rsteube authored May 1, 2022
2 parents a98f1a6 + 783384c commit c75b153
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 2 additions & 0 deletions example/example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ commands:
flags:
-s, --styled=: styled values
-r, --repeatable*: repeatable flag
-o, --optarg=?: optarg flag
--dynamic=: dynamic value
--env=: env
--novalue: no value
Expand All @@ -25,6 +26,7 @@ commands:
- "unstyled\tunstyled with description"
dynamic: ["$(git branch --all | cut -c 3- | sed 's/$/\t\tblue/')", "static value"]
env: ["$(env)"]
optarg: ["first", "second", "third"]
positional:
- ["pos1", "pos2"]
- ["$_files"]
Expand Down
12 changes: 11 additions & 1 deletion spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,14 @@ func (c *Command) ToCobra() *cobra.Command {
}

func parseFlag(flagSet *pflag.FlagSet, id, description string) error {
r := regexp.MustCompile(`^(?P<shorthand>-[^-])?(, *)?(?P<longhand>--[^ =*]*)?(?P<modifier>[=*]*)$`)
r := regexp.MustCompile(`^(?P<shorthand>-[^-])?(, *)?(?P<longhand>--[^ =*]*)?(?P<modifier>[=*?]*)$`)
matches := findNamedMatches(r, id)

longhand := strings.TrimPrefix(matches["longhand"], "--")
shorthand := strings.TrimPrefix(matches["shorthand"], "-")
slice := strings.Contains(matches["modifier"], "*")
value := strings.Contains(matches["modifier"], "=")
optarg := strings.Contains(matches["modifier"], "?")

if longhand != "" && shorthand != "" {
if value {
Expand Down Expand Up @@ -125,6 +126,15 @@ func parseFlag(flagSet *pflag.FlagSet, id, description string) error {
} else {
return fmt.Errorf("malformed flag: %v", id)
}

if optarg {
if longhand != "" {
flagSet.Lookup(longhand).NoOptDefVal = " "
} else {
flagSet.Lookup(shorthand).NoOptDefVal = " "
}
}

return nil
}

Expand Down

0 comments on commit c75b153

Please sign in to comment.