run

package
v0.0.0-...-9cd49fd Latest Latest
Warning

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

Go to latest
Published: May 22, 2024 License: BSD-3-Clause Imports: 11 Imported by: 1

Documentation

Overview

Example (Nesting)
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		run.MustApp("outer", "",
			run.Enabler("f", "", false, true).Flag(),
			run.MustCmd("inner", "",
				run.Enabler("g", "", false, true).Flag(),
			),
		).Debug(args...)
	}
	try("-h")
	try("-h", "inner")
	try("inner", "-h")
	try("--f")
	try("--g")
	try("--f", "inner", "--g")
	try("inner", "--f", "--g")

}
Output:

[-h]
  cmd: outer.--help
[-h inner]
  cmd: outer.inner.--help
[inner -h]
  cmd: outer.inner.--help
[--f]
  cmd: outer
  flag: f=true
[--g] err: unexpected flag: --g
  cmd: outer
  flag: f=false
[--f inner --g]
  cmd: outer.inner
  flag: g=true
    flag: f=true
[inner --f --g]
  cmd: outer.inner
  flag: g=true
    flag: f=true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrRedefined = errors.New("already set")
	ErrMissing   = errors.New("missing")
)

Functions

func Accumulator

func Accumulator[T cmp.Ordered](name, desc string, initial, increment T) *flagOnly[T]

Accumulator creates an option that starts as initial, and adds increment every time it is seen.

Example
package main

import (
	"strconv"

	"github.com/mutility/cli/run"
)

type quotedstring string

func (qs quotedstring) String() string {
	return strconv.Quote(string(qs))
}

func main() {
	try := func(args ...string) {
		run.MustApp("accum", "",
			run.Accumulator[quotedstring]("ha", "", "", "ha").Flag(),
			run.Accumulator("no", "", 0, -2).Flag(),
		).Debug(args...)
	}

	try()
	try("--ha")
	try("--no")
	try("--ha", "--no", "--ha")
	try("--ha", "--no", "--ha", "--ha", "--no", "--no", "--no")
	try("--ha=boop")

}
Output:

[]
  cmd: accum
  flag: ha=""
  flag: no=0
[--ha]
  cmd: accum
  flag: ha="ha"
  flag: no=0
[--no]
  cmd: accum
  flag: ha=""
  flag: no=-2
[--ha --no --ha]
  cmd: accum
  flag: ha="haha"
  flag: no=-2
[--ha --no --ha --ha --no --no --no]
  cmd: accum
  flag: ha="hahaha"
  flag: no=-8
[--ha=boop] err: unexpected flag value: --ha=boop
  cmd: accum
  flag: ha=""
  flag: no=0

func AccumulatorVar

func AccumulatorVar[T cmp.Ordered](p *T, name, desc string, increment T) *flagOnly[T]

AccumulatorVar creates an option that starts as initial, and adds increment every time it is seen.

func Enabler

func Enabler[T any](name, desc string, unseen, seen T) *flagOnly[T]

Enabler creates an option that defaults to unseen, gets set to seen, and errors on repeat.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("enable", "", run.Enabler("en", "", false, true).Flag())
		app.Debug(args...)
	}

	try()
	try("--en")
	try("--en", "--en")
	try("--en=true")

}
Output:

[]
  cmd: enable
  flag: en=false
[--en]
  cmd: enable
  flag: en=true
[--en --en] err: --en: repeated
  cmd: enable
  flag: en=true
[--en=true] err: unexpected flag value: --en=true
  cmd: enable
  flag: en=false

func EnablerVar

func EnablerVar[T any](p *T, name, desc string, seen T) *flagOnly[T]

EnablerVar creates an option that defaults to unseen, gets set to seen, and errors on repeat.

func File

func File(name, desc string) *option[string]

File creates an option that stores a string filename. This differs from String by accepting "-" as a positional argument.

func FileLike

func FileLike[T ~string](name, desc string) *option[T]

FileLike creates an option that stores a string-like filename. This differs from StringLike by accepting "-" as a positional argument.

Example
package main

import (
	"strconv"

	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app, _ := run.App("file", "", run.FileLike[quotedstring]("arg", "").Arg("arg"))
		app.Debug(args...)
	}

	try("hello")
	try("-")
	try("-n")
	try("--no")
	try("--", "--okay")

}

type quotedstring string

func (qs quotedstring) String() string {
	return strconv.Quote(string(qs))
}
Output:

[hello]
  cmd: file
  arg: arg="hello"
[-]
  cmd: file
  arg: arg="-"
[-n] err: unexpected flag: -n
  cmd: file
  arg: arg=""
[--no] err: unexpected flag: --no
  cmd: file
  arg: arg=""
[-- --okay]
  cmd: file
  arg: arg="--okay"

func FileLikeSlice

func FileLikeSlice[T ~string](name, desc string) *options[T]

FileLikeSlice creates an option that stores a string-like slice of filenames. This differs from StringLikeSlice by accepting "-" as a positional argument, and from FileLike by supporting Rest().

Example (Many)
package main

import (
	"strconv"

	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("files", "", run.FileLikeSlice[quotedstring]("args", "").Args("arg"))
		app.Debug(args...)
	}

	try("hello", "world")
	try("--", "head", "world")
	try("mid", "--", "world")
	try("trail", "world", "--")
	try("dash", "--", "--", "world")
	try("unquoted", "-n")
	try("quoted", "--", "-n")
	try("-", "-n")
	try("-", "--", "-n")

}

type quotedstring string

func (qs quotedstring) String() string {
	return strconv.Quote(string(qs))
}
Output:

[hello world]
  cmd: files
  arg: args=["hello" "world"]
[-- head world]
  cmd: files
  arg: args=["head" "world"]
[mid -- world]
  cmd: files
  arg: args=["mid" "world"]
[trail world --]
  cmd: files
  arg: args=["trail" "world"]
[dash -- -- world]
  cmd: files
  arg: args=["dash" "--" "world"]
[unquoted -n] err: unexpected flag: -n
  cmd: files
  arg: args=["unquoted"]
[quoted -- -n]
  cmd: files
  arg: args=["quoted" "-n"]
[- -n] err: unexpected flag: -n
  cmd: files
  arg: args=["-"]
[- -- -n]
  cmd: files
  arg: args=["-" "-n"]

func FileLikeSliceVar

func FileLikeSliceVar[T ~string](p *[]T, name, desc string) *options[T]

FileLikeSliceVar creates an option that stores a string-like slice of filenames. This differs from StringLikeSlice by accepting "-" as a positional argument, and from FileLike by supporting Rest().

func FileLikeVar

func FileLikeVar[T ~string](p *T, name, desc string) *option[T]

FileLikeVar creates an option that stores a string-like filename. This differs from StringLike by accepting "-" as a positional argument.

func FileSlice

func FileSlice(name, desc string) *options[string]

FileSlice creates an option that stores a string slice of filenames. This differs from StringSlice by accepting "-" as a positional argument, and from File by supporting Rest().

func FileSliceVar

func FileSliceVar(p *[]string, name, desc string) *options[string]

FileSliceVar creates an option that stores a string slice of filenames. This differs from StringSlice by accepting "-" as a positional argument, and from File by supporting Rest().

func FileVar

func FileVar(p *string, name, desc string) *option[string]

FileVar creates an option that stores a string filename. This differs from String by accepting "-" as a positional argument.

func FloatLike

func FloatLike[T ~float32 | ~float64](name, desc string) *option[T]

FloatLike creates an option that stores any float-like value. It converts strings like strconv.ParseFloat.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app := run.MustApp("floaty", "", run.FloatLike[float64]("pct", "").Arg("pct"))
	app.Debug("+-12.34")
	app.Debug("12.34")
	app.Debug("12")
	app.Debug(".34")

}
Output:

[+-12.34] err: pct: parsing "+-12.34" as float64: invalid syntax
  cmd: floaty
  arg: pct=0
[12.34]
  cmd: floaty
  arg: pct=12.34
[12]
  cmd: floaty
  arg: pct=12
[.34]
  cmd: floaty
  arg: pct=0.34

func FloatLikeSlice

func FloatLikeSlice[T ~float32 | ~float64](name, desc string) *options[T]

FloatLikeSlice creates and option that stores a slice of float-like values. It converts strings like strconv.ParseFloat. This differs from FloatLike by supporting Rest().

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app := run.MustApp("floats", "", run.FloatLikeSlice[float64]("pcts", "").Args("pct"))
	app.Debug("12.34", "+12", "-.34", "+-12.34")

}
Output:

[12.34 +12 -.34 +-12.34] err: pct: parsing "+-12.34" as float64: invalid syntax
  cmd: floats
  arg: pcts=[12.34 12 -0.34]

func FloatLikeSliceVar

func FloatLikeSliceVar[T ~float32 | ~float64](p *[]T, name, desc string) *options[T]

FloatLikeSliceVar creates and option that stores a slice of float-like values. It converts strings like strconv.ParseFloat. This differs from FloatLike by supporting Rest().

func FloatLikeVar

func FloatLikeVar[T ~float32 | ~float64](p *T, name, desc string) *option[T]

FloatLikeVar creates an option that stores any float-like value. It converts strings like strconv.ParseFloat.

func Int

func Int(name, desc string, base int) *option[int]

Int creates an option that stores any int. It converts strings like strconv.ParseInt.

func IntLike

func IntLike[T ~int | ~int8 | ~int16 | ~int32 | ~int64](name, desc string, base int) *option[T]

IntLike creates an option that stores any int-like value. It converts strings like strconv.ParseInt.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	type myint int8
	type myunt uint8
	try := func(args ...string) {
		app := run.MustApp("intish", "", run.IntLike[myint]("i8", "", 10).Arg("i"), run.UintLike[myunt]("u8", "", 0).Arg("u"))
		app.Debug(args...)
	}

	try("-100", "200") // fine
	try("100", "-100") // -100 invalid
	try("200", "100")  // 200 out of range

}
Output:

[-100 200]
  cmd: intish
  arg: i8=-100
  arg: u8=200
[100 -100] err: u: parsing "-100" as run_test.myunt: invalid syntax
  cmd: intish
  arg: i8=100
  arg: u8=0
[200 100] err: i: parsing "200" as run_test.myint: value out of range
  cmd: intish
  arg: i8=0
  arg: u8=0

func IntLikeSlice

func IntLikeSlice[T ~int | ~int8 | ~int16 | ~int32 | ~int64](name, desc string, base int) *options[T]

IntLikeSlice creates and option that stores a slice of int-like values. It converts strings like strconv.ParseInt. This differs from IntLike by supporting Rest().

func IntLikeSliceVar

func IntLikeSliceVar[T ~int | ~int8 | ~int16 | ~int32 | ~int64](p *[]T, name, desc string, base int) *options[T]

IntLikeSliceVar creates and option that stores a slice of int-like values. It converts strings like strconv.ParseInt. This differs from IntLike by supporting Rest().

func IntLikeVar

func IntLikeVar[T ~int | ~int8 | ~int16 | ~int32 | ~int64](p *T, name, desc string, base int) *option[T]

IntLikeVar creates an option that stores any int-like value. It converts strings like strconv.ParseInt.

func IntSlice

func IntSlice(name, desc string, base int) *options[int]

IntSlice creates and option that stores a slice of int values. It converts strings like strconv.ParseInt. This differs from Int by supporting Rest().

Example (Many)
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("ints", "", run.IntSlice("arg", "", 0).Args("arg"))
		app.Debug(args...)
	}

	try()
	try("5")
	try("6", "-2", "17", "+-3")

}
Output:

[] err: expected "<arg> ..."
  cmd: ints
  arg: arg=[]
[5]
  cmd: ints
  arg: arg=[5]
[6 -2 17 +-3] err: arg: parsing "+-3" as int: invalid syntax
  cmd: ints
  arg: arg=[6 -2 17]

func IntSliceVar

func IntSliceVar(p *[]int, name, desc string, base int) *options[int]

IntSliceVar creates and option that stores a slice of int values. It converts strings like strconv.ParseInt. This differs from Int by supporting Rest().

func IntVar

func IntVar(p *int, name, desc string, base int) *option[int]

IntVar creates an option that stores any int. It converts strings like strconv.ParseInt.

func Main

func Main(entry EntryFunc) int

Main runs your entry function and returns an int suitable for os.Exit.

func NamedOf

func NamedOf[T any](name, desc string, mapping []NamedValue[T]) *option[T]

NamedOf creates an option that stores any type of value, looked up from the provided mapping. This is suitable for small to medium sets of names.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	digit := run.NamedOf("digit", "", []run.NamedValue[int]{
		{Name: "one", Value: 1},
		{Name: "two", Value: 2},
		{Name: "three", Value: 3},
	})
	app := run.MustApp("named", "", digit.Arg("d"))
	app.Debug("four")
	app.Debug("two")
	app.Debug("four")

}
Output:

[four] err: d: "four" not one of "one", "two", "three"
  cmd: named
  arg: digit=0
[two]
  cmd: named
  arg: digit=2
[four] err: d: "four" not one of "one", "two", "three"
  cmd: named
  arg: digit=2

func NamedSliceOf

func NamedSliceOf[T any](name, desc string, mapping []NamedValue[T]) *options[T]

NamedSliceOf creates an option that stores a slice of any type of value, looked up from the provided mapping. This is suitable for small to medium sets of names.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	digit := run.NamedSliceOf("digits", "", []run.NamedValue[int]{
		{Name: "one", Value: 1},
		{Name: "two", Value: 2},
		{Name: "three", Value: 3},
	})
	app := run.MustApp("nameds", "", digit.Args("digit"))
	app.Debug("two", "three")
	app.Debug("two", "four")

}
Output:

[two three]
  cmd: nameds
  arg: digits=[2 3]
[two four] err: digit: "four" not one of "one", "two", "three"
  cmd: nameds
  arg: digits=[2]

func NamedSliceVarOf

func NamedSliceVarOf[T any](p *[]T, name, desc string, mapping []NamedValue[T]) *options[T]

NamedSliceVarOf creates an option that stores a slice of any type of value, looked up from the provided mapping. This is suitable for small to medium sets of names.

func NamedVarOf

func NamedVarOf[T any](p *T, name, desc string, mapping []NamedValue[T]) *option[T]

NamedVarOf creates an option that stores any type of value, looked up from the provided mapping. This is suitable for small to medium sets of names.

func Parser

func Parser[T any](name, desc string, parse func(string) (T, error)) *option[T]

Parser creates an option that converts with the provided parse function.

Example
package main

import (
	"net/url"

	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		run.MustApp("parser", "",
			run.Parser("url", "", url.ParseRequestURI).Arg("url"),
		).Debug(args...)
	}

	try("rel")
	try("schema:relative")
	try("schema:/rooted")
	try("https://example.com/")

}
Output:

[rel] err: url: parse "rel": invalid URI for request
  cmd: parser
  arg: url=<nil>
[schema:relative]
  cmd: parser
  arg: url=schema:relative
[schema:/rooted]
  cmd: parser
  arg: url=schema:/rooted
[https://example.com/]
  cmd: parser
  arg: url=https://example.com/

func ParserSlice

func ParserSlice[T any](name, desc string, parse func(string) (T, error)) *options[T]

ParserSlice creates an option that stores a slice of T values. It converts strings by calling parse.

Example
package main

import (
	"net/url"

	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		run.MustApp("parser", "",
			run.ParserSlice("urls", "", url.ParseRequestURI).Args("url"),
		).Debug(args...)
	}

	try("rel")
	try("schema:relative", "schema:/rooted", "https://example.com/")

}
Output:

[rel] err: url: parse "rel": invalid URI for request
  cmd: parser
  arg: urls=[]
[schema:relative schema:/rooted https://example.com/]
  cmd: parser
  arg: urls=[schema:relative schema:/rooted https://example.com/]

func ParserSliceVar

func ParserSliceVar[T any](p *[]T, name, desc string, parse func(string) (T, error)) *options[T]

ParserSliceVar creates an option that stores a slice of T values. It converts strings by calling parse.

func ParserVar

func ParserVar[T any](p *T, name, desc string, parse func(string) (T, error)) *option[T]

Parser creates an option that converts with the provided parse function.

func Pass

func Pass[T any](v T) pass[T]

func String

func String(name, desc string) *option[string]

String creates an option that stores any string.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("str", "")
		argVal := run.String("arg", "")
		app.SetArgs(argVal.Arg("arg"))
		app.Debug(args...)
	}

	try("hello")
	try("-")
	try("-n")
	try("--no")
	try("--", "--okay")

}
Output:

[hello]
  cmd: str
  arg: arg=hello
[-]
  cmd: str
  arg: arg=-
[-n] err: unexpected flag: -n
  cmd: str
  arg: arg=
[--no] err: unexpected flag: --no
  cmd: str
  arg: arg=
[-- --okay]
  cmd: str
  arg: arg=--okay

func StringLike

func StringLike[T ~string](name, desc string) *option[T]

StringLike creates an option that stores any string-like value.

Example
package main

import (
	"strconv"

	"github.com/mutility/cli/run"
)

type quotedstring string

func (qs quotedstring) String() string {
	return strconv.Quote(string(qs))
}

func main() {
	app := run.MustApp("quoted", "", run.StringLike[quotedstring]("files", "").Arg("file"))
	app.Debug("hello")

}
Output:

[hello]
  cmd: quoted
  arg: files="hello"

func StringLikeSlice

func StringLikeSlice[T ~string](name, desc string) *options[T]

StringLikeSlice creates and option that stores a slice of string-like values. This differs from StringLike by supporting Rest().

func StringLikeSliceVar

func StringLikeSliceVar[T ~string](p *[]T, name, desc string) *options[T]

StringLikeSlice creates and option that stores a slice of string-like values. This differs from StringLike by supporting Rest().

func StringLikeVar

func StringLikeVar[T ~string](p *T, name, desc string) *option[T]

StringLikeVar creates an option that stores any string-like value.

func StringOf

func StringOf[T ~string](name, desc string, names ...T) *option[T]

StringOf creates an option that stores a string-like value from the provided list. This is suitable for small to medium sets of string-like names.

Example (Enum)
package main

import (
	"strconv"

	"github.com/mutility/cli/run"
)

type quotedstring string

func (qs quotedstring) String() string {
	return strconv.Quote(string(qs))
}

func main() {
	app := run.MustApp("enum", "", run.StringOf[quotedstring]("letter", "", "alpha", "bravo", "charlie").Arg("abbrev"))
	app.Debug("delta")
	app.Debug("bravo")

}
Output:

[delta] err: abbrev: "delta" not one of "alpha", "bravo", "charlie"
  cmd: enum
  arg: letter=""
[bravo]
  cmd: enum
  arg: letter="bravo"

func StringSlice

func StringSlice(name, desc string) *options[string]

StringSlice creates and option that stores a slice of string values. This differs from String by supporting Rest().

func StringSliceOf

func StringSliceOf[T ~string](name, desc string, names ...T) *options[T]

StringSliceOf creates an option that stores a string-like slice of value from the provided list. This is suitable for small to medium sets of string-like names.

func StringSliceVar

func StringSliceVar(p *[]string, name, desc string) *options[string]

StringSliceVar creates and option that stores a slice of string values. This differs from String by supporting Rest().

func StringSliceVarOf

func StringSliceVarOf[T ~string](p *[]T, name, desc string, names ...T) *options[T]

StringSliceVarOf creates an option that stores a string-like slice of value from the provided list. This is suitable for small to medium sets of string-like names.

func StringVar

func StringVar(p *string, name, desc string) *option[string]

StringVar creates an option that stores any string.

func StringVarOf

func StringVarOf[T ~string](p *T, name, desc string, names ...T) *option[T]

StringVarOf creates an option that stores a string-like value from the provided list. This is suitable for small to medium sets of string-like names.

func TestErr

func TestErr(main EntryFunc) error

TestErr runs your entry function and returns its error.

func Toggler

func Toggler[T any](name, desc string, unseen, seen T) *flagOnly[T]

Toggler creates an option that toggles between two values, defaulting to the first.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("toggle", "", run.Toggler("en", "", false, true).Flag())
		app.Debug(args...)
	}

	try()
	try("--en")
	try("--en", "--en")
	try("--en", "--en", "--en")
	try("--en=false")

}
Output:

[]
  cmd: toggle
  flag: en=false
[--en]
  cmd: toggle
  flag: en=true
[--en --en]
  cmd: toggle
  flag: en=false
[--en --en --en]
  cmd: toggle
  flag: en=true
[--en=false] err: unexpected flag value: --en=false
  cmd: toggle
  flag: en=false

func TogglerVar

func TogglerVar[T any](p *T, name, desc string, seen T) *flagOnly[T]

TogglerVar creates an option that toggles between two values, defaulting to the first.

func Uint

func Uint(name, desc string, base int) *option[uint]

Uint creates an option that stores any uint. It converts strings like strconv.ParseUint.

func UintLike

func UintLike[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64](name, desc string, base int) *option[T]

UintLike creates an option that stores any uint-like value. It converts strings like strconv.ParseUint.

func UintLikeSlice

func UintLikeSlice[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64](name, desc string, base int) *options[T]

UintLikeSlice creates and option that stores a slice of uint-like values. It converts strings like strconv.ParseUint. This differs from UintLike by supporting Rest().

func UintLikeSliceVar

func UintLikeSliceVar[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64](p *[]T, name, desc string, base int) *options[T]

UintLikeSliceVar creates and option that stores a slice of uint-like values. It converts strings like strconv.ParseUint. This differs from UintLike by supporting Rest().

func UintLikeVar

func UintLikeVar[T ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64](p *T, name, desc string, base int) *option[T]

UintLikeVar creates an option that stores any uint-like value. It converts strings like strconv.ParseUint.

func UintSlice

func UintSlice(name, desc string, base int) *options[uint]

UintSlice creates and option that stores a slice of uint values. It converts strings like strconv.ParseUint. This differs from Uint by supporting Rest().

Example (Many)
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("uints", "", run.UintSlice("arg", "", 0).Args("arg"))
		app.Debug(args...)
	}

	try()
	try("5", "2")
	try("6", "-2", "17") // -2 blocks the parse, then has no home

}
Output:

[] err: expected "<arg> ..."
  cmd: uints
  arg: arg=[]
[5 2]
  cmd: uints
  arg: arg=[5 2]
[6 -2 17] err: unexpected flag: -2
  cmd: uints
  arg: arg=[6]

func UintSliceVar

func UintSliceVar(p *[]uint, name, desc string, base int) *options[uint]

UintSliceVar creates and option that stores a slice of uint values. It converts strings like strconv.ParseUint. This differs from Uint by supporting Rest().

func UintVar

func UintVar(p *uint, name, desc string, base int) *option[uint]

UintVar creates an option that stores any uint. It converts strings like strconv.ParseUint.

Types

type Application

type Application struct {
	Command
	// contains filtered or unexported fields
}

func App

func App(name, desc string, opts ...CmdOption) (*Application, error)

App creates an application and applies options.

Example (Empty)
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app, _ := run.App("noarg", "")
	app.Debug()
	app.Debug("--help")

}
Output:

[]
  cmd: noarg
[--help]
  cmd: noarg.--help

func MustApp

func MustApp(name, desc string, opts ...CmdOption) *Application

App creates an application, applies options, and panics on error.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app := run.MustApp("noway", "")
	app.Debug("hello")

}
Output:

[hello] err: unexpected argument: "hello"
  cmd: noway

func (*Application) AllowGroupShortFlags

func (a *Application) AllowGroupShortFlags(f bool)
Example

Allow short flags to be grouped can alter error messages. Negative numbers might be sequences of short flags, so are only offered to relevant option types. (Normally only single-digit negative numbers look like a short flag; others are treated as positional.)

package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app := run.MustApp("shorts", "")
	u := run.UintLike[uint8]("u8", "", 10)
	app.SetArgs(u.Arg("u"))
	app.AllowGroupShortFlags(false) // default
	app.Debug("-1")
	app.Debug("-100")
	app.AllowGroupShortFlags(true)
	app.Debug("-1")
	app.Debug("-100")

}
Output:

[-1] err: unexpected flag: -1
  cmd: shorts
  arg: u8=0
[-100] err: u: parsing "-100" as uint8: invalid syntax
  cmd: shorts
  arg: u8=0
[-1] err: unexpected flag: -1
  cmd: shorts
  arg: u8=0
[-100] err: unexpected flag: -100
  cmd: shorts
  arg: u8=0

func (*Application) Debug

func (a *Application) Debug(args ...string) (*Command, error)

Debug parses command line arguments, printing any resulting error, selected command, and its options.

func (*Application) DebugEnv

func (a *Application) DebugEnv(env Environ, args ...string) (*Command, error)

DebugEnv parses command line arguments, printing any resulting error, selected command, and its options.

func (*Application) Ferror

func (a *Application) Ferror(w io.Writer, err error)
Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app := run.MustApp("commands", "",
		run.MustCmd("foo", "does foo"),
		run.MustCmd("bar", "does bar", run.Handler(func(run.Context) error { return nil })),
	)

	env := run.DefaultEnviron()
	_, err := app.DebugEnv(env)
	app.Ferror(env.Stdout, err)
	_, err = app.DebugEnv(env, "foo")
	app.Ferror(env.Stdout, err)
	_, err = app.DebugEnv(env, "bar")
	app.Ferror(env.Stdout, err)

}
Output:

[]
  cmd: commands
commands: error: expected <command>
[foo]
  cmd: commands.foo
commands: error: foo: no handler
[bar]
  cmd: commands.bar
commands: error: <nil>

func (*Application) Main

func (a *Application) Main(ctx context.Context, env Environ) error

Main parses arguments and attemps to run the specified command handler. If the command-line is invalid, it prints help for the selected command.

func (*Application) Parse

func (a *Application) Parse(env Environ) (*Command, error)

Parse attemps to parse arguments and returns the selected command.

type Arg

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

Arg represents a positional option for a Command.

type CmdOption

type CmdOption interface {
	// contains filtered or unexported methods
}

CmdOptions specify options to apply to a command in CmdOpt.

func Details

func Details(detail string) CmdOption

Details sets extra help information for a Command.

func DetailsFor

func DetailsFor(detail string, opts ...Option) CmdOption

Details sets extra help information for a Command, and links it to options.

func NoHelp

func NoHelp() CmdOption
Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	app := run.MustApp("nohelp", "", run.NoHelp())
	app.SetCommands()
	app.Debug("hello")
	app.Debug("--help")

}
Output:

[hello] err: unexpected argument: "hello"
  cmd: nohelp
[--help] err: unexpected flag: --help
  cmd: nohelp

type Command

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

A command is a 'verb' for an application. It can be configured with Flags and Args, and a Handler. An application starts with an implicit root command, to which other "sub" commands can be added.

func Cmd

func Cmd(name, desc string, opts ...CmdOption) (*Command, error)

Cmd creates a command and applies options.

func MustCmd

func MustCmd(name, desc string, opts ...CmdOption) *Command

MustCmd creates a command, applies options, and panics on error.

func (*Command) Args

func (c *Command) Args() []Arg

Args returns a copy of the args previously set.

func (*Command) CommandName

func (c *Command) CommandName() string

CommandName returns the hierarchical name for a command.

For example, if this command represented git commit, it would return "commit".

func (*Command) Commands

func (c *Command) Commands() []*Command

Commands returns a copy of the commands previously set.

func (*Command) Flags

func (c *Command) Flags() []Flag

Flags returns a copy of the flags previously set.

func (*Command) Name

func (c *Command) Name() string

Name returns the hierarchical program name for a command.

For example, if this command represented git commit, it would return "git.commit".

func (*Command) PrintHelp

func (c *Command) PrintHelp(ctx Context, a *Application) error

PrintHelp writes usage information for this command to env.Stdout.

func (*Command) SetArgs

func (c *Command) SetArgs(args ...Arg) error

SetArgs sets the positional options for a command. Attempting to set them more than once causes an error.

func (*Command) SetCommands

func (c *Command) SetCommands(cmds ...*Command) error

SetCommands sets the named subcommands for a command. Attempting to set them more than once causes an error.

func (*Command) SetDetails

func (c *Command) SetDetails(detail string) error

SetDetails sets extra help information for a Command. Attempting to set details more than once causes an error.

func (*Command) SetDetailsFor

func (c *Command) SetDetailsFor(detail string, opts ...Option) error

SetDetailsFor sets extra help information for a Command, and links it to options. Options reused in other commands will point to this command for further information.

Attempting to set details more than once causes an error.

func (*Command) SetFlags

func (c *Command) SetFlags(flags ...Flag) error

SetFlags sets the named options for a command. Attempting to set them more than once causes an error.

func (*Command) SetHandler

func (c *Command) SetHandler(handler Handler) error

SetHandler sets the handler for a Command. Attempting to set more than one handler causes an error.

type Context

type Context struct {
	context.Context
	Environ
	Command *Command
}

type EntryFunc

type EntryFunc func(Environ) error

EntryFunc is the recommended type for your entry function.

type Environ

type Environ struct {
	Args      []string // Args includes the program name at index 0.
	Stdin     io.Reader
	Stdout    io.Writer
	Stderr    io.Writer
	Getenv    func(string) string
	LookupEnv func(string) (string, bool)
}

func DefaultEnviron

func DefaultEnviron() (env Environ)

DefaultEnviron returns an Environ that works like the os package.

func (Environ) WithArgs

func (e Environ) WithArgs(args []string) Environ

WithArgs overrides Args.

func (Environ) WithInput

func (e Environ) WithInput(r io.Reader) Environ

WithInput overrides Stdin. Pass nil to simulate a closed handle.

func (Environ) WithOutput

func (e Environ) WithOutput(w io.Writer) Environ

WithOutput overrides Stdout and Stderr together.

func (Environ) WithStderr

func (e Environ) WithStderr(w io.Writer) Environ

WithStderr overrides Stderr.

func (Environ) WithStdout

func (e Environ) WithStdout(w io.Writer) Environ

WithStdout overrides Stdout.

func (Environ) WithVariables

func (e Environ) WithVariables(env Variables) Environ

WithVariables overrides Getenv and LookupEnv to use env.

type Flag

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

Flag represents the named options for a Command.

func (Flag) Default

func (f Flag) Default(string string) Flag

Default specifies a value that will be supplied for an unprovided flag.

Example
package main

import (
	"github.com/mutility/cli/run"
)

func main() {
	try := func(args ...string) {
		app := run.MustApp("default", "")
		digit := run.NamedOf("digit", "", []run.NamedValue[int]{
			{Name: "one", Value: 1},
			{Name: "two", Value: 2},
			{Name: "three", Value: 3},
		})
		app.SetFlags(digit.Flag().Default("two"))
		app.Debug(args...)
	}
	try()
	try("--digit", "three")
	try("--digit", "four")

}
Output:

[]
  cmd: default
  flag: digit=2
[--digit three]
  cmd: default
  flag: digit=3
[--digit four] err: --digit: "four" not one of "one", "two", "three"
  cmd: default
  flag: digit=0

type Handler

type Handler func(Context) error

Handler can be passed to (*Command).Runs, or used applied as an option in CmdOpt.

func Handler1

func Handler1[
	T1 any, V1 Param[T1],
](
	handler func(Context, T1) error,
	v1 V1,
) Handler

Handler1 adapts a func(Context, T1) for (*command).Runs.

func Handler2

func Handler2[
	T1 any, V1 Param[T1],
	T2 any, V2 Param[T2],
](
	handler func(Context, T1, T2) error,
	v1 V1, v2 V2,
) Handler

Handler2 adapts a func(Context, T1, T2) for (*command).Runs.

func Handler3

func Handler3[
	T1 any, V1 Param[T1],
	T2 any, V2 Param[T2],
	T3 any, V3 Param[T3],
](
	handler func(Context, T1, T2, T3) error,
	v1 V1, v2 V2, v3 V3,
) Handler

Handler3 adapts a func(Context, T1, T2, T3) for (*command).Runs.

func Handler4

func Handler4[
	T1 any, V1 Param[T1],
	T2 any, V2 Param[T2],
	T3 any, V3 Param[T3],
	T4 any, V4 Param[T4],
](
	handler func(Context, T1, T2, T3, T4) error,
	v1 V1, v2 V2, v3 V3, v4 V4,
) Handler

Handler4 adapts a func(Context, T1...T4) for (*command).Runs.

func Handler5

func Handler5[
	T1 any, V1 Param[T1],
	T2 any, V2 Param[T2],
	T3 any, V3 Param[T3],
	T4 any, V4 Param[T4],
	T5 any, V5 Param[T5],
](
	handler func(Context, T1, T2, T3, T4, T5) error,
	v1 V1, v2 V2, v3 V3, v4 V4, v5 V5,
) Handler

Handler5 adapts a func(Context, T1...T5) for (*command).Runs.

func Handler6

func Handler6[
	T1 any, V1 Param[T1],
	T2 any, V2 Param[T2],
	T3 any, V3 Param[T3],
	T4 any, V4 Param[T4],
	T5 any, V5 Param[T5],
	T6 any, V6 Param[T6],
](
	handler func(Context, T1, T2, T3, T4, T5, T6) error,
	v1 V1, v2 V2, v3 V3, v4 V4, v5 V5, v6 V6,
) Handler

Handler6 adapts a func(Context, T1...T6) for (*command).Runs.

func Handler7

func Handler7[
	T1 any, V1 Param[T1],
	T2 any, V2 Param[T2],
	T3 any, V3 Param[T3],
	T4 any, V4 Param[T4],
	T5 any, V5 Param[T5],
	T6 any, V6 Param[T6],
	T7 any, V7 Param[T7],
](
	handler func(Context, T1, T2, T3, T4, T5, T6, T7) error,
	v1 V1, v2 V2, v3 V3, v4 V4, v5 V5, v6 V6, v7 V7,
) Handler

Handler7 adapts a func(Context, T1...T7) for (*command).Runs.

type HelpDisabledError

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

func (HelpDisabledError) Command

func (e HelpDisabledError) Command() *Command

func (HelpDisabledError) Error

func (e HelpDisabledError) Error() string

type NamedValue

type NamedValue[T any] struct {
	Name  string
	Desc  string
	Value T
}

type NotOneOfError

type NotOneOfError[T any] struct {
	// contains filtered or unexported fields
}

func (NotOneOfError[T]) Error

func (e NotOneOfError[T]) Error() string

type Option

type Option interface {
	// contains filtered or unexported methods
}

Options implement the required internal interface for use as either Flags, Args, or both.

type Param

type Param[T any] interface{ Value() T }

type Variables

type Variables map[string]string

Variables represents an environment block.

Jump to

Keyboard shortcuts

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