Skip to content

Commit

Permalink
Add case sensitive support to flagset
Browse files Browse the repository at this point in the history
  • Loading branch information
RamanaReddy0M committed Jun 15, 2023
1 parent cfd5bff commit 20fb594
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
16 changes: 12 additions & 4 deletions goflags.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (

// FlagSet is a list of flags for an application
type FlagSet struct {
CaseSensitive bool
Marshal bool
description string
flagKeys InsertionOrderedMap
Expand Down Expand Up @@ -536,7 +537,7 @@ func (flagSet *FlagSet) usageFunc() {
flagSet.displayGroupUsageFunc(newUniqueDeduper(), group, cliOutput, writer)
return
}
flag := flagSet.getFlagByName(strings.ToLower(os.Args[2]))
flag := flagSet.getFlagByName(os.Args[2])
if flag != nil {
flagSet.displaySingleFlagUsageFunc(os.Args[2], flag, cliOutput, writer)
return
Expand All @@ -562,9 +563,16 @@ func (flagSet *FlagSet) getGroupbyName(name string) groupData {
func (flagSet *FlagSet) getFlagByName(name string) *FlagData {
var flagData *FlagData
flagSet.flagKeys.forEach(func(key string, data *FlagData) {
if strings.EqualFold(data.long, name) || strings.EqualFold(data.short, name) {
flagData = data
return
if flagSet.CaseSensitive {
if data.long == name || data.short == name {
flagData = data
return
}
} else {
if strings.EqualFold(data.long, name) || strings.EqualFold(data.short, name) {
flagData = data
return
}
}
})
return flagData
Expand Down
38 changes: 38 additions & 0 deletions goflags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,44 @@ func TestSetDefaultStringSliceValue(t *testing.T) {
tearDown(t.Name())
}

func TestCaseSensitiveFlagSet(t *testing.T) {
flagSet := NewFlagSet()
flagSet.CaseSensitive = true
var verbose, keyVal bool
flagSet.CreateGroup("Test", "Test",
flagSet.BoolVarP(&verbose, "verbose", "v", false, "show verbose output"),
flagSet.BoolVarP(&keyVal, "var", "V", false, "custom vars in key=value format"),
)
output := &bytes.Buffer{}
flagSet.CommandLine.SetOutput(output)

os.Args = []string{
os.Args[0],
"-h",
"V",
}
flagSet.usageFunc()

resultOutput := output.String()
actual := resultOutput[strings.Index(resultOutput, "Flags:\n"):]
expected := "Flags:\n -V, -var custom vars in key=value format\n"
assert.Equal(t, expected, actual)

output = &bytes.Buffer{}
flagSet.CommandLine.SetOutput(output)
os.Args = []string{
os.Args[0],
"-h",
"v",
}
flagSet.usageFunc()

resultOutput = output.String()
actual = resultOutput[strings.Index(resultOutput, "Flags:\n"):]
expected = "Flags:\n -v, -verbose show verbose output\n"
assert.Equal(t, expected, actual)
}

func tearDown(uniqueValue string) {
flag.CommandLine = flag.NewFlagSet(uniqueValue, flag.ContinueOnError)
flag.CommandLine.Usage = flag.Usage
Expand Down

0 comments on commit 20fb594

Please sign in to comment.