go-flags icon indicating copy to clipboard operation
go-flags copied to clipboard

Examples of documenting positional arguments

Open wolever opened this issue 8 years ago • 2 comments

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.

wolever avatar Feb 19 '17 21:02 wolever

Is just the documentation missing or is this not possible at all?

ekle avatar Jan 05 '20 09:01 ekle

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

gsauthof avatar Aug 30 '20 19:08 gsauthof