Clean up disparity between Context and Kong.

Previously, there was a confusing mix of functionality shared between
the two wherein you would need to use the Kong type for printing errors,
etc. but it did not have access to the context in order to print
context-sensitive usage information. This has been fixed.

Additionally, there are now fuzzy correction suggestions for flags and
commands

Also added a server example which shows how Kong can be used for parsing
in interactive shells. Run with:

    $ go run ./_examples/server/*.go

Then interact with:

    $ ssh -p 6740 127.0.0.1
This commit is contained in:
Alec Thomas
2018-06-25 14:45:20 +10:00
parent f7acb2b389
commit 6408010083
20 changed files with 489 additions and 130 deletions
+2 -30
View File
@@ -4,41 +4,13 @@ import (
"os"
)
// App is the default global instance. It is populated by Parse().
var App *Kong
// Parse constructs a new parser and parses the default command-line.
func Parse(cli interface{}, options ...Option) string {
func Parse(cli interface{}, options ...Option) *Context {
parser, err := New(cli, options...)
if err != nil {
panic(err)
}
App = parser
ctx, err := parser.Parse(os.Args[1:])
parser.FatalIfErrorf(err)
return ctx.Command()
}
// FatalIfErrorf terminates with an error message if err != nil.
func FatalIfErrorf(err error, args ...interface{}) {
if App == nil {
panic("call kong.Parse() before using kong.FatalIfErrorf()")
}
App.FatalIfErrorf(err, args...)
}
// Errorf writes a message to Kong.Stderr with the application name prefixed.
func Errorf(format string, args ...interface{}) {
if App == nil {
panic("call kong.Parse() before using kong.Errorf()")
}
App.Errorf(format, args...)
}
// Printf writes a message to Kong.Stdout with the application name prefixed.
func Printf(format string, args ...interface{}) {
if App == nil {
panic("call kong.Parse() before using kong.Printf()")
}
App.Printf(format, args...)
return ctx
}