Add an "embed" tag.

This commit is contained in:
Alec Thomas
2018-09-19 13:23:18 +10:00
parent 0ba159f97d
commit 54338bd8b1
5 changed files with 31 additions and 1 deletions
+1
View File
@@ -414,6 +414,7 @@ Tag | Description
`group:"X"` | Logical group for a flag or command.
`prefix:"X"` | Prefix for all sub-flags.
`set:"K=V"` | Set a variable for expansion by child elements. Multiples can occur.
`embed` | If present, this field's children will be embedded in the parent. Useful for composition.
<a id="markdown-variable-interpolation" name="variable-interpolation"></a>
## Variable interpolation
+1 -1
View File
@@ -52,7 +52,7 @@ func flattenedFields(v reflect.Value) (out []flattenedField) {
if tag.Ignored {
continue
}
if ft.Anonymous {
if ft.Anonymous || tag.Embed {
if fv.Kind() == reflect.Interface {
fv = fv.Elem()
}
+16
View File
@@ -626,3 +626,19 @@ func TestExcludedField(t *testing.T) {
_, err = p.Parse([]string{"--excluded=foo"})
require.Error(t, err)
}
func TestUnnamedFieldEmbeds(t *testing.T) {
type Embed struct {
Flag string
}
var cli struct {
One Embed `prefix:"one-" embed:""`
Two Embed `prefix:"two-" embed:""`
}
buf := &strings.Builder{}
p := mustNew(t, &cli, kong.Writers(buf, buf), kong.Exit(func(int) {}))
_, err := p.Parse([]string{"--help"})
require.NoError(t, err)
require.Contains(t, buf.String(), `--one-flag=STRING`)
require.Contains(t, buf.String(), `--two-flag=STRING`)
}
+2
View File
@@ -29,6 +29,7 @@ type Tag struct {
Group string
Vars Vars
Prefix string // Optional prefix on anonymous structs. All sub-flags will have this prefix.
Embed bool
// Storage for all tag keys for arbitrary lookups.
items map[string][]string
@@ -151,6 +152,7 @@ func parseTag(fv reflect.Value, ft reflect.StructField) *Tag {
t.Sep, _ = t.GetRune("sep")
t.Group = t.Get("group")
t.Prefix = t.Get("prefix")
t.Embed = t.Has("embed")
if t.Sep == 0 {
if t.Get("sep") == "none" {
t.Sep = -1
+11
View File
@@ -138,3 +138,14 @@ func TestTagSetOnCommand(t *testing.T) {
require.NoError(t, err)
require.Contains(t, buf.String(), `A key from somewhere.`)
}
func TestTagSetOnFlag(t *testing.T) {
var cli struct {
Flag string `set:"where=somewhere" help:"A key from ${where}."`
}
buf := &strings.Builder{}
p := mustNew(t, &cli, kong.Writers(buf, buf), kong.Exit(func(int) {}))
_, err := p.Parse([]string{"--help"})
require.NoError(t, err)
require.Contains(t, buf.String(), `A key from somewhere.`)
}