go-flags
go-flags copied to clipboard
Examples of documenting positional arguments
It would be nice to have some examples showing how positional arguments (ie, the returned args) array can be documented in the help output.
Right now it's not clear how to describe them, show default values, examples, etc.
Is just the documentation missing or is this not possible at all?
I also couldn't find any documentation on how to parse positional arguments although there is a comment that mentions documentation.
After reading that description and looking at some test cases in this repo I managed to build this minimal example:
package main
import (
"log"
"os"
"github.com/jessevdk/go-flags"
)
type args struct {
Verbose bool `short:"v" long:"verbose" description:"verbose output"`
Positional struct {
Dir string `positional-arg-name:"DIRECTORY"`
} `positional-args:"true" required:"true"`
}
func main() {
var args args
_, err := flags.Parse(&args)
if e, ok := err.(*flags.Error); ok {
if e.Type == flags.ErrHelp {
os.Exit(0)
} else {
os.Exit(1)
}
}
if err != nil {
log.Fatal(err)
}
log.Println(args)
}
Example output:
$ ./getargs -h
Usage:
getargs [OPTIONS] DIRECTORY
Application Options:
-v, --verbose verbose output
Help Options:
-h, --help Show this help message
$ echo $?
0
$ ./getargs
the required argument `DIRECTORY` was not provided
$ echo $?
1
$ ./getargs path/to
2020/08/30 20:57:34 {false {path/to}}
$ ./getargs path/to trailing
2020/08/30 21:00:20 {false {path/to}}
$ echo 'expected error due to extra positional argument'
expected error due to extra positional argument