Fixes #125: Support custom per-mapper placeholder text (#169)

This commit is contained in:
andrewbaxter
2021-05-17 20:31:07 +09:00
committed by GitHub
parent 9c81441ae0
commit b3bdeb18e2
4 changed files with 42 additions and 0 deletions
+5
View File
@@ -65,6 +65,11 @@ type HelpProvider interface {
Help() string
}
// PlaceHolderProvider can be implemented by mappers to provide custom placeholder text.
type PlaceHolderProvider interface {
PlaceHolder(flag *Flag) string
}
// HelpIndenter is used to indent new layers in the help tree.
type HelpIndenter func(prefix string) string
+1
View File
@@ -43,6 +43,7 @@ func (r *DecodeContext) WithScanner(scan *Scanner) *DecodeContext {
}
// MapperValue may be implemented by fields in order to provide custom mapping.
// Mappers may additionally implement PlaceHolderProvider to provide custom placeholder text.
type MapperValue interface {
Decode(ctx *DecodeContext) error
}
+32
View File
@@ -420,3 +420,35 @@ func TestPathMapper(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "-", cli.Path)
}
func TestMapperPlaceHolder(t *testing.T) {
var cli struct {
Flag string
}
b := bytes.NewBuffer(nil)
k := mustNew(
t,
&cli,
kong.Writers(b, b),
kong.ValueMapper(&cli.Flag, testMapperWithPlaceHolder{}),
kong.Exit(func(int) { panic("exit") }),
)
// Ensure that --help
require.Panics(t, func() {
_, err := k.Parse([]string{"--help"})
require.NoError(t, err)
})
require.Contains(t, b.String(), "--flag=/a/b/c")
}
type testMapperWithPlaceHolder struct {
}
func (t testMapperWithPlaceHolder) Decode(ctx *kong.DecodeContext, target reflect.Value) error {
target.SetString("hi")
return nil
}
func (t testMapperWithPlaceHolder) PlaceHolder(flag *kong.Flag) string {
return "/a/b/c"
}
+4
View File
@@ -397,6 +397,10 @@ func (f *Flag) String() string {
// FormatPlaceHolder formats the placeholder string for a Flag.
func (f *Flag) FormatPlaceHolder() string {
placeholderHelper, ok := f.Value.Mapper.(PlaceHolderProvider)
if ok {
return placeholderHelper.PlaceHolder(f)
}
tail := ""
if f.Value.IsSlice() && f.Value.Tag.Sep != -1 {
tail += string(f.Value.Tag.Sep) + "..."