claw

package module
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2023 License: LGPL-3.0 Imports: 7 Imported by: 1

README

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

Documentation

Overview

Package claw is a lightweight command-line argument parser.

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

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(opts *Options) (args map[string]any, err error)

Parse parses the command-line arguments according to opts. It returns a map of flag/positional names to their value. The map only contains a name if it is provided in the command-line arguments or if its default value is defined.

Parse returns an error if opts is invalid. It does not return error when encoutering parsing error. Instead, it prints the error to stdout and exits the program with status 1. If it encounters '--help', it prints an auto-generated help menu and exits immediately with status 0.

Types

type AmbiguousPositionalsError

type AmbiguousPositionalsError struct{}

AmbiguousPositionalsError is returned by Parse if opts.Positionals contains more than one repeating parameter, or one repeating parameter with any number of optional parameter.

func (AmbiguousPositionalsError) Error

type DefaultValueTypeError

type DefaultValueTypeError struct {
	// contains filtered or unexported fields
}

DefaultValueTypeError is returned by Parse if any parameter has a DefaultValue whose type does not match its Type.

func (DefaultValueTypeError) Error

func (e DefaultValueTypeError) Error() string

type DuplicateNameError

type DuplicateNameError struct {
	// contains filtered or unexported fields
}

DuplicateNameError is returned by Parse if any parameter name is used more than once.

func (DuplicateNameError) Error

func (e DuplicateNameError) Error() string

type EmptyProgramNameError

type EmptyProgramNameError struct{}

EmptyProgramNameError is returned by Parse if opts.Name is empty.

func (EmptyProgramNameError) Error

func (e EmptyProgramNameError) Error() string

type Flag

type Flag struct {

	// LongName is the name of the optional flag if it is non-empty.
	// LongName must be empty or at least two characters long,
	// with alphanumeric characters in kebab-case.
	// Use ShortName if a shorter name is preferred.
	LongName string

	// ShortName is the name of the optional flag if LongName is empty.
	// It must be empty or an alphabet.
	ShortName byte

	// Type is the type of the parameter.
	// It must be one of "string, "int", "float", and "bool".
	// An empty string defaults to "string".
	Type string

	// DefaultValue is the default value of the parameter.
	// The type of DefaultValue must match the Type field.
	// The positional parameter is optional if DefaultValue != nil,
	// and required otherwise.
	DefaultValue any

	// Description is a short text of what the flag is, for the help menu.
	Description string

	// ValueName is the hint text printed in place of the value of a non-bool type flag on the help menu.
	// For example, --flag=<value>.
	// An empty string defaults to the Type of the flag (eg. --flag=<string>).
	ValueName string
	// contains filtered or unexported fields
}

Flag represents an optional flag. At least one of LongName and ShortName must be non-empty. If LongName is provided, it will be used as the key in the args map returned by Parse. Otherwise, ShortName will be used.

type InvalidFlagNameError

type InvalidFlagNameError struct {
	// contains filtered or unexported fields
}

InvalidFlagNameError is returned by Parse if any flag name in opts.Flags is invalid.

func (InvalidFlagNameError) Error

func (e InvalidFlagNameError) Error() string

type InvalidParamOrderError

type InvalidParamOrderError struct{}

InvalidParamorderError is returned by Parse if opts.Positionals contains any required parameter that appears after an optional parameter.

func (InvalidParamOrderError) Error

func (e InvalidParamOrderError) Error() string

type InvalidPositionalNameError

type InvalidPositionalNameError struct {
	// contains filtered or unexported fields
}

InvalidPositionalNameError is returned by Parse if any positional parameter name in opts.Positionals is invalid.

func (InvalidPositionalNameError) Error

type InvalidTypeError

type InvalidTypeError struct {
	// contains filtered or unexported fields
}

InvalidTypeError is returned by Parse if any parameter's Type value is invalid.

func (InvalidTypeError) Error

func (e InvalidTypeError) Error() string

type Options

type Options struct {
	// Name is the name of the program in the "Usage" part of the help menu
	// Its value must be non-empty.
	Name string

	// Description is a short text describing what the program does
	// at the top of the help menu.
	Description string

	// Positionals is the positional parameters to parse.
	// All optional parameters must come after all required parameters.
	// There can only be at most one repeating parameter,
	// and no other optional parameter if there is a repeating parameter.
	Positionals []Positional // the positional parameters to parse

	Flags            []Flag // the option flags to parse
	Postnote         string // text to print at the end of the help menu
	DisableShortHelp bool   // disable printing the help menu on -h
}

Options define the flags and positional parameters to parse, some basic information about the program to display on the help menu, and parsing settings.

type Positional

type Positional struct {
	// Name is the name of the parameter to be printed in the help menu
	// and used as the key in the args map returned by Parse.
	// It must be a non-empty alphanumeric string in snake_case.
	Name string

	// Type is the type of the parameter.
	// It must be one of "string, "int", "float", and "bool".
	// An empty string defaults to "string".
	Type string

	// DefaultValue is the default value of the parameter.
	// The type of DefaultValue must match the Type field.
	// The positional parameter is optional if DefaultValue != nil,
	// and required otherwise.
	DefaultValue any

	// Description is a short text of what the parameter is, for the help menu.
	// If left empty, the parameter will only be printed in the "Usage" section
	// but not in the "Parameters" section.
	Description string

	Repeating bool // whether the parameter can take more than one argument
}

Positional represents a positional parameter.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL