pflag icon indicating copy to clipboard operation
pflag copied to clipboard

Allow specifying custom string in value of usage

Open jtagcat opened this issue 3 years ago • 2 comments

(current output edited, actual: -C, -- string, https://github.com/spf13/pflag/issues/139)

Flags:
  -C string   Act on path instead of working directory.
  -h, --help      help for git-id

^ right now it says 'string', it'd be neet if I could say UsageValueName: "path", so it'd display like so:

Flags:
  -C path   Act on path instead of working directory.
  -h, --help      help for git-id

jtagcat avatar Jan 23 '22 14:01 jtagcat

Name for flag types is determined with the following function

// flag.go:566

// UnquoteUsage extracts a back-quoted name from the usage
// string for a flag and returns it and the un-quoted usage.
// Given "a `name` to show" it returns ("name", "a name to show").
// If there are no back quotes, the name is an educated guess of the
// type of the flag's value, or the empty string if the flag is boolean.
func UnquoteUsage(flag *Flag) (name string, usage string) {
	// Look for a back-quoted name, but avoid the strings package.
	usage = flag.Usage
	for i := 0; i < len(usage); i++ {
		if usage[i] == '`' {
			for j := i + 1; j < len(usage); j++ {
				if usage[j] == '`' {
					name = usage[i+1 : j]
					usage = usage[:i] + name + usage[j+1:]
					return name, usage
				}
			}
			break // Only one back quote; use type name.
		}
	}

	name = flag.Value.Type()
	switch name {
	case "bool":
		name = ""
	case "float64":
		name = "float"
	case "int64":
		name = "int"
	case "uint64":
		name = "uint"
	case "stringSlice":
		name = "strings"
	case "intSlice":
		name = "ints"
	case "uintSlice":
		name = "uints"
	case "boolSlice":
		name = "bools"
	}

	return
}

Meaning if you quote your desired usage value name/type with ` inside your usage string it will display correctly i.e.,:

flags.String("C", "", "Act on `path` instead of working directory.")

should turn to

Flags:
  -C path   Act on path instead of working directory.
  -h, --help      help for git-id

max-frank avatar Mar 25 '22 12:03 max-frank

indeed, leaving open for missing docs

jtagcat avatar Mar 25 '22 12:03 jtagcat