You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Package getopt provides a zero-dependency Go implementation of the Unix getopt function for parsing command-line options.
The getopt package supports parsing options using the POSIX convention, supporting short options (e.g., -a) and option arguments. It also supports GNU extensions, including support for long options (e.g., --option), options with optional arguments, and permuting non-option parameters.
Install
go get github.com/jonathonwebb/getopt
Usage
This package emulates the C getopt function, but uses a state machine to encapsulate variables (instead of the global optind, optopt, optarg used in C). Rather than implement a high-level interface for defining CLI flags, it aims to implement an accurate emulation of C getopt that can be used by higher-level tools.
This package uses GNU libc as a reference for behavior, since many expect the
non-standard features it provides. This is accomplished via a C test generator that runs getopt for all functions and parsing modes.
It supports the same configuration options as the GNU options via Mode:
ModePosix: enables the '+' compatibility mode, disabling permuting arguments and terminating parsing on the first parameter.
ModeInOrder: enables the '-' optstring prefix mode, treating all parameters as though they were arguments to an option with character code 1.
The specific libc function that is emulated can be configured via Func:
FuncGetOpt: parse only traditional POSIX short options (e.g., -a).
FuncGetOptLong: parse short options, and GNU extension long options (e.g.,
--option).
FuncGetOptLongOnly: parse short and long options, but allow long options to begin with a single dash (like pkg/flag).
The parser differs from GNU libc's getopt in the following ways:
It accepts multi-byte runes in short and long option definitions.
This package does not implement the same argument permutation as GNU libc.
The value of OptInd and order of arguments mid-parsing may differ, and only
the final order is validated against the GNU implementation.
API Documentation
The full API documentation can be found at pkg.go.dev. The API for major version 1.x.x is stable -- any breaking changes to the API will require a new major version.
Acknowledgements
The algorithm for permuting arguments is from musl-libc, and is used under the linked MIT License: