Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix:(issue_2030) Add support for trailing hypen for short options #2031

Merged
merged 2 commits into from
Dec 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3841,6 +3841,51 @@ func TestCommand_ParentCommand_Set(t *testing.T) {
assert.NoError(t, err)
}

func TestCommandStringDashOption(t *testing.T) {
tests := []struct {
name string
shortOptionHandling bool
args []string
}{
{
name: "double dash separate value",
args: []string{"foo", "--bar", "-", "test"},
},
{
name: "single dash separate value",
args: []string{"foo", "-bar", "-", "test"},
},
{
name: "single dash combined value",
args: []string{"foo", "-b-", "test"},
shortOptionHandling: true,
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
cmd := &Command{
Name: "foo",
UseShortOptionHandling: test.shortOptionHandling,
Flags: []Flag{
&StringFlag{
Name: "bar",
Aliases: []string{"b"},
},
},
Action: func(ctx context.Context, c *Command) error {
return nil
},
}

err := cmd.Run(buildTestContext(t), test.args)
assert.NoError(t, err)

assert.Equal(t, "-", cmd.String("b"))
})
}
}

func TestCommandReadArgsFromStdIn(t *testing.T) {
tests := []struct {
name string
Expand Down
11 changes: 9 additions & 2 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ func flagFromError(err error) (string, error) {

func splitShortOptions(set *flag.FlagSet, arg string) []string {
shortFlagsExist := func(s string) bool {
for _, c := range s[1:] {
for index, c := range s[1:] {
if index == (len(s[1:])-1) && c == '-' {
break
}
if f := set.Lookup(string(c)); f == nil {
return false
}
Expand All @@ -107,7 +110,11 @@ func splitShortOptions(set *flag.FlagSet, arg string) []string {

separated := make([]string, 0, len(arg)-1)
for _, flagChar := range arg[1:] {
separated = append(separated, "-"+string(flagChar))
if flagChar != '-' {
separated = append(separated, "-"+string(flagChar))
} else {
separated = append(separated, "-")
}
}

return separated
Expand Down
Loading