~liliace/claw

A lightweight command-line argument parser for Go
chore: re-license under MPL-2.0
align long flags in help menu

clone

read-only
https://git.sr.ht/~liliace/claw
read/write
git@git.sr.ht:~liliace/claw

You can also use your local clone with git send-email.

#claw Go Documentation

A lightweight command-line argument parser for Go

#Features

  • POSIX-compliant
  • Parses positional parameters in addition to option flags
  • Auto-generates the help menu in a standard style (see example below)
  • Zero external dependencies
  • Intuitive and readable struct-based API (opinionated)

#Example usage

package main

import (
	"fmt"
	"git.sr.ht/~liliace/claw"
)

func main() {
	args, err := claw.Parse(&claw.Options{
		Name:        "hello",
		Description: "A program that says hello.",
		Flags: []claw.Flag{
			{
				LongName:     "interval",
				ShortName:    'i',
				DefaultValue: 1.0,
				Type:         "float",
				Description:  "interval to send the hellos",
			},
			{
				LongName:    "language",
				ValueName:   "iso_code",
				Description: "language to say the hello in",
			},
			{
				LongName:     "name",
				ShortName:    'n',
				DefaultValue: "",
				Description:  "optional name to greet",
			},
			{
				LongName:  "config-file",
				ShortName: 'f',
				ValueName: "filename",
			},
			{
				ShortName:   'q',
				Type:        "bool",
				Description: "only display output at start and finish",
			},
			{
				ShortName: 'v',
				Type:      "bool",
			},
		},
		Positionals: []claw.Positional{
			{
				Name:        "count",
				Type:        "int",
				Description: "the number of hellos to send",
			},
			{
				Name:         "repeat",
				Type:         "int",
				DefaultValue: []int{1},
				Repeating:    true,
				Description:  "number of hellos to print per line, must be > 0. If more than one value is provided, it cycles through them for each line",
			},
		},
		Postnote: "See man (1) hello for more information",
	})
	if err != nil {
		panic(err)
	}
	for key, value := range args {
		fmt.Println(key, value)
	}
}

This generates the following help menu:

A program that says hello.

Usage: hello [options] <count> [repeat]...

Parameters:
 count     the number of hellos to send
 repeat    number of hellos to print per line, must be > 0. If more than one value is provided, it cycles through them for each line (default: [1])

Options:
 -h, --help                    print this help text and exit
 -f, --config-file=<filename>
 -i, --interval=<float>        interval to send the hellos (default: 1)
     --language=<iso_code>     language to say the hello in
 -n, --name=<string>           optional name to greet (default: "")
 -q                            only display output at start and finish
 -v

See man (1) hello for more information
Do not follow this link