feat: Allow kong.Path to describe remaining unparsed args (#472)

As Kong traces a sequence of command line arguments, it parses them and appends them to the parsed `Path` sequence. For each element in `Path`, these is a corresponding sequence of unparsed arguments. This change enables `Path` to yield these.

I have a package that uses Kong's hooks to instrument Kong applications (to monitor usage, reliability, etc of internal tools). I would like to instrument the commandline arguments as well.

This change would enable it to work roughly as follows:
```golang
func (Foo) BeforeApply(app *kong.Kong, ctx *kong.Context, t *Tracker) error {
	command := []string{ctx.Model.Name}
	var args  []string

	for _, path := range ctx.Path {
		if path.Command != nil {
			command = append(command, path.Command.Name)
			args = path.Remainder()
		}
	}

	app.Exit = t.exit(app.Exit)

	t.WithCommand(strings.Join(command, " ")).WithArgs(args)
	return nil
}
```
This commit is contained in:
Bob Lail
2025-03-07 14:28:09 -08:00
committed by GitHub
parent 0c495e4936
commit 5b36573738
3 changed files with 63 additions and 17 deletions
+19
View File
@@ -48,6 +48,25 @@ func TestPositionalArguments(t *testing.T) {
})
}
func TestRemainderReturnsUnparsedArgs(t *testing.T) {
var cli struct {
User struct {
Create struct {
ID int `kong:"arg"`
First string `kong:"arg"`
Last string `kong:"arg"`
} `kong:"cmd"`
} `kong:"cmd"`
}
p := mustNew(t, &cli)
args := []string{"user", "create", "10", "Alec", "Thomas"}
ctx, err := p.Parse(args)
assert.NoError(t, err)
for i, x := range ctx.Path {
assert.Equal(t, strings.Join(args[i:], " "), strings.Join(x.Remainder(), " "))
}
}
func TestBranchingArgument(t *testing.T) {
/*
app user create <id> <first> <last>