Skip to content

Commit

Permalink
while print flag , the placeholder if need but not set.
Browse files Browse the repository at this point in the history
print flag type first.

Signed-off-by: jokemanfire <hu.dingyang@zte.com.cn>
  • Loading branch information
jokemanfire committed Jan 10, 2025
1 parent 7fc43e7 commit 166beb6
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 86 deletions.
2 changes: 1 addition & 1 deletion examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func ExampleCommand_Run_appHelp() {
// help, h Shows a list of commands or help for one command
//
// GLOBAL OPTIONS:
// --name value a name to say (default: "bob")
// --name string a name to say (default: "bob")
// --help, -h show help
// --version, -v print the version
}
Expand Down
14 changes: 12 additions & 2 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,11 @@ type LocalFlag interface {
IsLocal() bool
}

// FlagType is an interface to detect if a flag is a string, bool, etc.
type FlagType interface {
GetFlagType() string
}

func newFlagSet(name string, flags []Flag) (*flag.FlagSet, error) {
set := flag.NewFlagSet(name, flag.ContinueOnError)

Expand Down Expand Up @@ -304,9 +309,14 @@ func stringifyFlag(f Flag) string {
}
placeholder, usage := unquoteUsage(df.GetUsage())
needsPlaceholder := df.TakesValue()

// if needsPlaceholder is true, placeholder is empty
if needsPlaceholder && placeholder == "" {
placeholder = defaultPlaceholder
// try to get type from flag
if v1, ok := f.(FlagType); ok && v1.GetFlagType() != "" {
placeholder = v1.GetFlagType()
} else {
placeholder = defaultPlaceholder
}
}

defaultValueString := ""
Expand Down
15 changes: 15 additions & 0 deletions flag_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,21 @@ func (f *FlagBase[T, C, V]) GetValue() string {
return fmt.Sprintf("%v", f.Value)
}

// GetFlagType returns the type of the flag.
func (f *FlagBase[T, C, V]) GetFlagType() string {
ty := reflect.TypeOf(f.Value)
if ty == nil {
return ""
}
// if it is a Slice, then return the slice type. Will nested slices be used in the future?
if ty.Kind() == reflect.Slice {
elemType := ty.Elem()
return "[]" + elemType.Name()
}
//TODO. Hashmap is a bit difficult to judge, it will be fixed in the future
return ty.Name()
}

// Apply populates the flag given the flag set and environment
func (f *FlagBase[T, C, V]) Apply(set *flag.FlagSet) error {
tracef("apply (flag=%[1]q)", f.Name)
Expand Down
Loading

0 comments on commit 166beb6

Please sign in to comment.