libclimate

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2025 License: BSD-3-Clause Imports: 8 Imported by: 1

README

libCLImate.Go

Command-Line Interface boilerplate mini-framework, for Go

Introduction

libCLImate is a Command-Line Interface boilerplate mini-framework, which encapsulates the common aspects of Command-Line Interface boilerplate. The first libCLImate was a C/C++ library. There have been several implementations in other languages. libCLImate.Go is the Go version.

Table of Contents

Background

As described in the CLASP project, command-line arguments may be discriminated as flags, options, and values:

  • flags are arguments that begin with 1+ hyphens and have a name, and whose presence/absence alter program behaviour, e.g. -f, --verbose;
  • options are arguments that begin with 1+ hyphens and have a name and a value, e.g. --verbosity=terse, -v t;
  • values are arguments that do not begin with hyphens (and are not the value of an option), e.g. ~/my-files/.

libCLImate builds upon this discrimination of arguments to provide higher-level facilities and more succinct specification. All variants (except for the C/C++ version) provide this in the form of a Climate class type, which is specified according to a lightweight DSL. The constructed Climate instance is then used to parse the command-line arguments, and provides a number of facilities, including:

  • parsing into flags, options, values, including recognition of special flag -- as marking end of flags/options (which is done via the underlying CLASP library);
  • automatic handling of --help flag, printing out a full description of the program features and all flags/options in details, and then terminating with exit code 0;
  • automatic handling of --version flag, printing out the program name and version, and then terminating with exit code 0;
  • detection and reporting of unrecognised flags/options, and then terminating with exit code 1;
  • sundry other helper functions and parsed information.

libCLImate.Go, which is built from CLASP.Go, provides access to an instance of Climate (a Go struct) via the Init() function's callback function argument, as illustrated in brief in the Components section below and extensively in the EXAMPLES.md.

Installation

Install via go get, as in:

go get "github.com/synesissoftware/libCLImate.Go"

and then import as:

import libclimate "github.com/synesissoftware/libCLImate.Go"

or, simply, as:

import "github.com/synesissoftware/libCLImate.Go"

Components

With libCLImate.Go, specification of the Climate struct is done via the Init() function by specifying a callback within which the features are specified, as in:

// README_Components.go

func main() {

	climate, err := libclimate.Init(func (cl *libclimate.Climate) (error) {

        . . . // specify features HERE

		return nil
	});
	if err != nil {

		fmt.Fprintf(os.Stderr, "failed to create CLI parser: %v\n", err)
	}

	_, _ = climate.ParseAndVerify(os.Args, libclimate.ParseFlag_PanicOnFailure)

    . . . // rest of program
}

Inside "constructor" - at specify features HERE - the various features of the Climate instance under construction can be specified, including:

  • the version as a string or an array (of numbers or strings), as in:
	cl.Version = "0.0.1"
  • the info lines as an array of strings (including special value ":version:", which prints program name and version), as in:
	cl.InfoLines = []string{
		"Example program",
		"",
		":version:",
		"",
	}

Even with just those two attributes set, the program will now respond to --help and --version with useful output:

  • --help
Example program

README_Components 0.0.1

USAGE: README_Components [ ... flags and options ... ]

flags/options:

	--help
		Shows this help and exits

	--version
		Shows version information and exits
  • --version
README_Components 0.0.1

Specification of program-specific flags/options is straightforward, e.g.

  • a flag --debug:
	cl.AddFlag(clasp.Flag("--debug").SetHelp("runs in Debug mode").SetAlias("-d"))
  • an option --verbosity, with a callback function:
	o_Verbosity := clasp.Option("--verbosity").SetHelp("specifies verbosity").SetAlias("-v").SetValues("terse", "quiet", "silent", "chatty")

	cl.AddOptionFunc(o_Verbosity, func (o *clasp.Argument, a *clasp.Alias) {
		fmt.Printf("verbosity specified as: %v\n", o.Value)
	})

Now the program will respond to the flag --help with:

Example program

README_Components 0.0.1

USAGE: README_Components [ ... flags and options ... ]

flags/options:

	--help
		Shows this help and exits

	--version
		Shows version information and exits

	-d
	--debug
		runs in Debug mode

	-v <value>
	--verbosity=<value>
		specifies verbosity
		where <value> one of:
			terse
			quiet
			silent
			chatty

And will respond to the option -v silent (which is equivalent to --verbosity=silent) with:

verbosity specified as: silent

Examples

Examples are provided in the examples directory, along with a markdown description for each. A detailed list TOC of them is provided in EXAMPLES.md.

Project Information

Where to get help

GitHub Page

Contribution guidelines

Defect reports, feature requests, and pull requests are welcome on https://github.com/synesissoftware/libCLImate.Go.

Dependencies

libCLImate.Go depends on:

Development/Testing Dependencies
License

libCLImate.Go is released under the 3-clause BSD license. See LICENSE for details.

Documentation

Index

Constants

View Source
const (
	VersionMajor uint16 = 0
	VersionMinor uint16 = 8
	VersionPatch uint16 = 1
	VersionAB    uint16 = 0xFFFF
	Version      uint64 = (uint64(VersionMajor) << 48) + (uint64(VersionMinor) << 32) + (uint64(VersionPatch) << 16) + (uint64(VersionAB) << 0)
)
View Source
const (
	UsageHelpSuffix_Default = "; use --help for usage"
)

Variables

This section is empty.

Functions

func VersionString added in v0.6.1

func VersionString() string

Types

type AliasFlag

type AliasFlag int64

Type of flags passed to the Climate.AddFlag and Climate.AddOption methods.

type Climate

type Climate struct {
	Specifications   []*clasp.Specification // The specifications created by [Init].
	ParseFlags       clasp.ParseFlag        // Parsing flags.
	Version          interface{}            // Version field that can be specified by application code in the function called by [Init].
	VersionPrefix    string                 // Version-prefix field that can be specified by application code in the function called by [Init].
	InfoLines        []string               // Information lines field that can be specified by application code in the function called by [Init].
	ValuesString     string                 // Values-string field that can be specified by application code in the function called by [Init].
	ProgramName      string                 // Program-name field that can be specified by application code in the function called by [Init]. Defaults to `os.Args[0]`.
	ValueNames       []string               // Specifies a list of value names that may be used in a contingent report when insufficient values are specified on the command-line (as determined by [Climate.ValuesConstraint]).
	ValuesConstraint []int                  // An array of 1 or 2 numbers that specify the number of values, or the minimum and maximum number of values, required. A value of -1 means "no constraint", so, for example, the constraint `{2, -1}` means 2+ values are required.
	UsageHelpSuffix  string                 // An optional string to be applied to the end of the contingent report produced by [Climate.Abort]. Defaults to nothing. Specify ":" for default suffix string of "; use --help for usage". Insert leading "; " unless first character is punctuation.
	// contains filtered or unexported fields
}

Structure representing a CLI parsing context, obtained from Init.

func Init

func Init(initFn InitFunc, options ...interface{}) (climate *Climate, err error)

Initialises a Climate instance, according to the given function (which may not be nil) and arguments.

func (Climate) Abort added in v0.3.0

func (cl Climate) Abort(message string, err error, options ...interface{})

Emits the given message and, optionally, err to the standard error stream, prefixed with the program name, and then terminates the process with a non-0 exit code.

func (*Climate) AddAlias

func (cl *Climate) AddAlias(resolved_name, alias string)

Adds an alias to the Climate instance

The resolved_name param can be the name of a flag or option, or an option-with-value. The alias param is the alias (which must not contain an equals sign.

func (*Climate) AddFlag

func (cl *Climate) AddFlag(flag clasp.Specification, flags ...AliasFlag)

Adds a (copy of the) flag to the Climate instance.

func (*Climate) AddFlagFunc added in v0.2.0

func (cl *Climate) AddFlagFunc(flag clasp.Specification, flagFn FlagFunc, flags ...AliasFlag)

Adds a (copy of the) flag to the Climate instance.

func (*Climate) AddOption

func (cl *Climate) AddOption(option clasp.Specification, flags ...AliasFlag)

Adds a (copy of the) option to the Climate instance.

func (*Climate) AddOptionFunc added in v0.2.0

func (cl *Climate) AddOptionFunc(option clasp.Specification, optionFn OptionFunc, flags ...AliasFlag)

Adds a (copy of the) option to the Climate instance.

func (Climate) Parse

func (cl Climate) Parse(argv []string, options ...interface{}) (result Result, err error)

Parses a command line, obtaining a Result instance representing the arguments received by the process.

func (Climate) ParseAndVerify

func (cl Climate) ParseAndVerify(argv []string, options ...interface{}) (result Result, err error)

Parses via Climate.Parse and verifies via Result.Verify.

Panics, rather than returns, if the ParseFlag_PanicOnFailure flag is specified

type FlagFunc added in v0.2.0

type FlagFunc func()

Type of callback function that may be specified to Climate.AddFlagFunc.

type InitFlag

type InitFlag int64

Type of flags passed to the Init method.

const (
	InitFlag_PanicOnFailure InitFlag = 1 << iota // Causes [Init] to panic if an error encountered during processing.
	InitFlag_NoHelpFlag                          // Suppresses the provision and processing of a help flag (aka "--help").
	InitFlag_NoVersionFlag                       // Suppresses the provision and processing of a version flag (aka "--version").
)
const (
	InitFlag_None InitFlag = 0 // No initialisation flags specified.
)

type InitFunc

type InitFunc func(cl *Climate) error

Callback function for specification of Climate via DSL.

type OptionFunc added in v0.2.0

type OptionFunc func(option *clasp.Argument, specification *clasp.Specification)

Type of callback function that may be specified to Climate.AddOptionFunc, which receives the argument and its specification.

type ParseFlag

type ParseFlag int64

Type of flags passed to the Climate.Parse and Climate.ParseAndVerify methods.

const (
	ParseFlag_PanicOnFailure  ParseFlag = 1 << iota // Causes [Climate.Parse] to panic if an error encountered during processing.
	ParseFlag_DontCheckUnused                       // Causes [Climate.Verify] to ignore unrecognised arguments.
)
const (
	ParseFlag_None ParseFlag = 0 // No parse flags specified.
)

type Result

type Result struct {
	Flags       []*clasp.Argument // Array of all flags.
	Options     []*clasp.Argument // Array of all options.
	Values      []*clasp.Argument // Array of all values.
	ProgramName string            // The program name inferred by [Init], which may be overridden in the function called by [Init].
	Argv        []string          // The original argument string array passed to [Parse].
	// contains filtered or unexported fields
}

Structure representing CLI results, obtained from Climate.Parse.

func (Result) FlagIsSpecified

func (result Result) FlagIsSpecified(id interface{}) bool

Determines if the given flag is specified

func (Result) LookupFlag added in v0.2.0

func (result Result) LookupFlag(id interface{}) (*clasp.Argument, bool)

Looks for a flag with the given id - name, or the specification instance - and returns it and the value true if found; if not, returns nil and false.

func (Result) LookupOption

func (result Result) LookupOption(id interface{}) (*clasp.Argument, bool)

Looks for an option with the given id - name, or the specification instance - and returns it and the value true if found; if not, returns nil and false.

func (Result) Verify

func (result Result) Verify(options ...interface{})

Verifies that all given arguments received are recognised according to the specified flags and options

Directories

Path Synopsis
test
scratch command

Jump to

Keyboard shortcuts

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