Skip to content

Conversation

boblail
Copy link
Contributor

@boblail boblail commented Nov 22, 2024

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:

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.Rest()
		}
	}

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

	t.WithCommand(strings.Join(command, " ")).WithArgs(args)
	return nil
}

@alecthomas
Copy link
Owner

Seems reasonable, but could you add a test? And I think a better name would be Remainder()

@alecthomas
Copy link
Owner

Ping.

@boblail boblail force-pushed the lail/remaining-args branch from 7aab177 to 6681f1d Compare January 27, 2025 04:22
@boblail
Copy link
Contributor Author

boblail commented Jan 27, 2025

Sorry for the delay! I just rebased and pushed a commit.

  • Renamed Rest() to Remainder()
  • Added a test

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
}
```
@boblail boblail force-pushed the lail/remaining-args branch from 6681f1d to 0f91525 Compare February 27, 2025 06:05
Copy link
Owner

@alecthomas alecthomas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice thanks!

@alecthomas alecthomas merged commit 5b36573 into alecthomas:master Mar 7, 2025
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants