Skip to content

Commit b03afc3

Browse files
authored
treat single-character aliases as short flags (#605)
`aliases:"n,name"` set both n and name up as long flags, so the short form -n didn't match. Single-rune aliases now resolve as short flags instead, since that's clearly the intent and there's no other way to declare a short alias today. Closes #589 Signed-off-by: Charlie Tonneslan <cst0520@gmail.com>
1 parent 66d2f03 commit b03afc3

3 files changed

Lines changed: 21 additions & 3 deletions

File tree

build.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"reflect"
66
"strings"
7+
"unicode/utf8"
78
)
89

910
// Plugins are dynamically embedded command-line structures.
@@ -344,6 +345,9 @@ func buildField(k *Kong, node *Node, v reflect.Value, ft reflect.StructField, fv
344345
seenFlags["--"+value.Name] = true
345346
for _, alias := range tag.Aliases {
346347
aliasFlag := "--" + alias
348+
if utf8.RuneCountInString(alias) == 1 {
349+
aliasFlag = "-" + alias
350+
}
347351
if seenFlags[aliasFlag] {
348352
return failField(v, ft, "duplicate flag %s", aliasFlag)
349353
}

context.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"sort"
99
"strconv"
1010
"strings"
11+
"unicode/utf8"
1112
)
1213

1314
// Path records the nodes and parsed values from the current command-line.
@@ -746,9 +747,12 @@ func (c *Context) parseFlag(flags []*Flag, match string) (err error) {
746747
candidates = append(candidates, short)
747748
}
748749
for _, alias := range flag.Aliases {
749-
alias = "--" + alias
750-
matched = matched || (alias == match)
751-
candidates = append(candidates, alias)
750+
aliasFlag := "--" + alias
751+
if utf8.RuneCountInString(alias) == 1 {
752+
aliasFlag = "-" + alias
753+
}
754+
matched = matched || (aliasFlag == match)
755+
candidates = append(candidates, aliasFlag)
752756
}
753757

754758
neg := negatableFlagName(flag.Name, flag.Tag.Negatable)

kong_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -669,6 +669,16 @@ func TestAlias(t *testing.T) {
669669
assert.Equal(t, "hello", cli.String)
670670
}
671671

672+
func TestSingleCharAliasIsShortFlag(t *testing.T) {
673+
var cli struct {
674+
Number string `aliases:"n,num"`
675+
}
676+
app := mustNew(t, &cli)
677+
_, err := app.Parse([]string{"-n", "hello"})
678+
assert.NoError(t, err)
679+
assert.Equal(t, "hello", cli.Number)
680+
}
681+
672682
func TestDuplicateFlagChoosesLast(t *testing.T) {
673683
var cli struct {
674684
Flag int

0 commit comments

Comments
 (0)