opts

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2023 License: 0BSD Imports: 3 Imported by: 0

README

Opts

Opts is a simple Go library implementing unicode-aware getopt(3)- and getopt_long(3) flag parsing in Go. For details, check out the godoc documentation.

Note that unlike the getopt() C function, the ‘:’ and ‘?’ flags are not returned on errors — the errors are instead returned via the err return value of opts.Get() and opts.GetLong(). Additionally, a leading ‘:’ in the opt-string provided to opts.Get() is not supported; you are responsible for your own I/O.

Example Usage

The following demonstrates an example usage of the opts.Get() function…

package main

import (
	"fmt"
	"os"

	"git.sr.ht/~mango/opts"
)

func usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s [-ßλ] [-a arg]\n", os.Args[0])
	os.Exit(1)
}

func main() {
	flags, optind, err := opts.Get(os.Args, "a:ßλ")
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
		usage()
	}

	for _, f := range flags {
		switch f.Key {
		case 'a':
			fmt.Println("-a given with argument", f.Value)
		case 'ß':
			fmt.Println("-ß given")
		case 'λ':
			fmt.Println("-λ given")
		}
	}

	// The remaining arguments
	rest := os.Args[optind:]
}

…and the following demonstrates an example usage of the opts.GetLong() function:

package main

import (
	"fmt"
	"os"

	"git.sr.ht/~mango/opts"
)

const noShortFlag = -1

func usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s [-ßλ] [-a arg] [--no-short]\n", os.Args[0])
	os.Exit(1)
}

func main() {
	flags, optind, err := opts.GetLong(os.Args, []opts.LongOpt{
		{Short: 'a', Long: "add", Arg: opts.Required},
		{Short: 'ß', Long: "sheiße", Arg: opts.None},
		{Short: 'λ', Long: "λεωνίδας", Arg: opts.None},
		{Short: noShortFlag, Long: "no-short", Arg: opts.None},
	})
	if err != nil {
		fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
		usage()
	}

	for _, f := range flags {
		switch f.Key {
		case 'a':
			fmt.Println("-a or --add given with argument", f.Value)
		case 'ß':
			fmt.Println("-ß or --sheiße given")
		case 'λ':
			fmt.Println("-λ or --λεωνίδας given")
		case noShortFlag:
			fmt.Println("--no-short given")
		}
	}

	// The remaining arguments
	rest := os.Args[optind:]
}

Documentation

Overview

Package opts implements unicode-aware getopt(3)- and getopt_long(3) flag parsing.

The opts package aims to provide as simple an API as possible. If your usecase requires more advanced argument-parsing or a more robust API, this may not be the ideal package for you.

While the opts package aims to closely follow the POSIX getopt(3) and GNU getopt_long(3) C functions, there are some notable differences. This package properly supports unicode flags, but also does not support a leading ‘:’ in the Get function’s option string; all user-facing I/O is delegrated to the caller.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ArgMode

type ArgMode int

ArgMode represents whether or not a long-option takes an argument.

const (
	None     ArgMode = iota // long opt takes no argument
	Required                // long opt takes an argument
	Optional                // long opt optionally takes an argument
)

These tokens can be used to specify whether or not a long-option takes an argument.

type BadOptionError

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

A BadOptionError describes an option that the user attempted to pass which the developer did not register.

func (BadOptionError) Error

func (e BadOptionError) Error() string

type Flag

type Flag struct {
	Key   rune   // the flag that was passed
	Value string // the flags argument
}

Flag represents a parsed command-line flag. Key corresponds to the rune that was passed on the command-line, and Value corresponds to the flags argument if one was provided. In the case of long-options Key will map to the corresponding short-code, even if a long-option was used.

func Get

func Get(args []string, optstr string) (flags []Flag, optind int, err error)

Get parses the command-line arguments in args according to optstr. Unlike POSIX-getopt(3), a leading ‘:’ in optstr is not supported and will be ignored and no I/O is ever performed.

Get will look for the flags listed in optstr (i.e., it will look for ‘-a’, ‘-ß’, and ‘λ’ given optstr == "aßλ"). The optstr need not be sorted in any particular order. If an option takes a required argument, it can be suffixed by a colon. If an option takes an optional argument, it can be suffixed by two colons. As an example, optstr == "a::ßλ:" will search for ‘-a’ with an optional argument, ‘-ß’ with no argument, and ‘-λ’ with a required argument.

A successful parse returns the flags in the flags slice and the index of the first non-option argument in optind. In the case of failure, err will be one of BadOptionError or NoArgumentError.

func GetLong

func GetLong(args []string, opts []LongOpt) (flags []Flag, optind int, err error)

GetLong parses the command-line arguments in args according to opts.

This function is identical to Get except it parses according to a LongOpt slice instead of an opt-string, and it parses long-options. When parsing, GetLong will also accept incomplete long-options if they are unambiguous. For example, given the following definition of opts:

opts := []LongOpt{
	{Short: 'a', Long: "add", Arg: None},
	{Short: 'd', Long: "delete", Arg: None},
	{Short: 'D', Long: "defer", Arg: None},
}

The options ‘--a’ and ‘--ad’ will parse as ‘--add’. The option ‘--de’ will not parse however as it is ambiguous.

type LongOpt

type LongOpt struct {
	Short rune
	Long  string
	Arg   ArgMode
}

LongOpt represents a long-option to attempt to parse. All long options have a short-hand form represented by Short and a long-form represented by Long. Arg is used to represent whether or not the long-option takes an argument.

In the case that you want to parse a long-option which doesn’t have a short-hand form, you can set Short to a negative integer.

type NoArgumentError

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

A NoArgumentError describes an option that the user attempted to pass without an argument, which required an argument.

func (NoArgumentError) Error

func (e NoArgumentError) Error() string

Jump to

Keyboard shortcuts

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