options

package
v13.15.4 Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2024 License: Apache-2.0 Imports: 8 Imported by: 20

Documentation

Overview

Package options provides methods for working with command-line options

Index

Examples

Constants

View Source
const (
	STRING uint8 = iota // String option
	INT                 // Int/Uint option
	BOOL                // Boolean option
	FLOAT               // Floating number option
	MIXED               // String or boolean option
)

Options types

View Source
const (
	ERROR_UNSUPPORTED = iota
	ERROR_DUPLICATE_LONGNAME
	ERROR_DUPLICATE_SHORTNAME
	ERROR_OPTION_IS_NIL
	ERROR_EMPTY_VALUE
	ERROR_WRONG_FORMAT
	ERROR_CONFLICT
	ERROR_BOUND_NOT_SET
	ERROR_UNSUPPORTED_VALUE
	ERROR_UNSUPPORTED_ALIAS_LIST_FORMAT
	ERROR_UNSUPPORTED_CONFLICT_LIST_FORMAT
	ERROR_UNSUPPORTED_BOUND_LIST_FORMAT
)

Error codes

Variables

View Source
var (
	// ErrNilOptions returns if options struct is nil
	ErrNilOptions = fmt.Errorf("Options struct is nil")

	// ErrNilMap returns if options map is nil
	ErrNilMap = fmt.Errorf("Options map is nil")

	// ErrEmptyName returns if option have no name
	ErrEmptyName = fmt.Errorf("One or more options do not have a name")
)
View Source
var MergeSymbol = " "

MergeSymbol used for joining several mergeble options with string value

Functions

func Add

func Add(name string, opt *V) error

Add adds new supported option

Example
// Add options
Add("u:user", &V{Type: STRING, Value: "john"})
Add("l:lines", &V{Type: INT, Min: 1, Max: 100})

args, _ := Parse()

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", GetS("u:user"))
fmt.Printf("Lines: %d\n", GetI("l:lines"))
Output:

func AddMap

func AddMap(optMap Map) errors.Errors

AddMap adds map with supported options

Example
// Add options
AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

args, _ := Parse()

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", GetS("u:user"))
fmt.Printf("Lines: %d\n", GetI("l:lines"))
Output:

func Delete

func Delete(name string) bool

Delete deletes option with given name

You can use this method to remove options with private data such as passwords, tokens, etc.

Example
args, _ := Parse(Map{
	"u:user":     {Type: STRING, Value: "john"},
	"l:lines":    {Type: INT, Min: 1, Max: 100},
	"p:password": {},
})

// Remove password option after usage
Delete("p:password")

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Has password option: %t\n", Has("p:password"))
Output:

func F

func F(opt string) string

F formats option name (shortcut for Format)

func Format

func Format(opt string) string

Format formats option name

Example
o := "t:test"

fmt.Printf("Option: %s\n", Format(o))
Output:

Option: -t/--test

func GetB

func GetB(name string) bool

GetB returns option value as boolean

Example
args, _ := Parse(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", GetS("u:user"))
fmt.Printf("Force: %t\n", GetB("f:force"))
Output:

func GetF

func GetF(name string) float64

GetF returns option value as floating number

Example
args, _ := Parse(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"r:ratio": {Type: FLOAT},
})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", GetS("u:user"))
fmt.Printf("Ratio: %g\n", GetF("r:ratio"))
Output:

func GetI

func GetI(name string) int

GetI returns option value as integer

Example
args, _ := Parse(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", GetS("u:user"))
fmt.Printf("Lines: %d\n", GetI("l:lines"))
Output:

func GetS

func GetS(name string) string

GetS returns option value as string

Example
args, _ := Parse(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", GetS("u:user"))
fmt.Printf("Lines: %d\n", GetI("l:lines"))
Output:

func Has

func Has(name string) bool

Has checks if option with given name exists and set

Example
args, _ := Parse(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Has user option: %t\n", Has("u:user"))
fmt.Printf("Has lines option: %t\n", Has("l:lines"))
Output:

func Is

func Is(name string, value any) bool

Is checks if option with given name has given value

Example
Parse(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

if Is("u:user", "bob") && Is("lines", 10) {
	fmt.Println("User is bob and lines number is 10")
}
Output:

func Merge

func Merge(opts ...string) string

Merge merges several options into string

func ParseOptionName

func ParseOptionName(opt string) (string, string)

ParseOptionName parses combined name and returns long and short options

func Q

func Q(opts ...string) string

Q merges several options into string (shortcut for Merge)

func Split

func Split(name string) []string

Split splits mergeble option to it's values

Example
// Use null-terminated string instead of default whitespace for merge.
// Note that the merge symbol must be set before the parsing options.
MergeSymbol = "\x00"

args, _ := Parse(Map{
	"u:user":  {Mergeble: true},
	"r:ratio": {Type: FLOAT},
})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Users: %s\n", Split("u:user"))
fmt.Printf("Ratio: %g\n", GetF("r:ratio"))
Output:

Types

type Argument

type Argument string

Argument is command argument

func (Argument) Base

func (a Argument) Base() Argument

Base is shorthand analog of path.Base

Example
opts := NewOptions()

input := "run /srv/app//conf/myapp.conf"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Clean: %s\n", args.Get(1).Clean())
fmt.Printf("Base: %s\n", args.Get(1).Base())
fmt.Printf("Dir: %s\n", args.Get(1).Dir())
fmt.Printf("Ext: %s\n", args.Get(1).Ext())
fmt.Printf("IsAbs: %t\n", args.Get(1).IsAbs())
Output:

Arguments: [run /srv/app//conf/myapp.conf]
Clean: /srv/app/conf/myapp.conf
Base: myapp.conf
Dir: /srv/app/conf
Ext: .conf
IsAbs: true

func (Argument) Bool

func (a Argument) Bool() (bool, error)

Int converts argument to int

Example
opts := NewOptions()

input := "release yes"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
force, _ := args.Get(1).Bool()
fmt.Printf("Force: %t\n", force)
Output:

Arguments: [release yes]
Force: true

func (Argument) Clean

func (a Argument) Clean() Argument

Clean is shorthand analog of path.Clean

Example
opts := NewOptions()

input := "run /srv/app//conf/myapp.conf"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Clean: %s\n", args.Get(1).Clean())
fmt.Printf("Base: %s\n", args.Get(1).Base())
fmt.Printf("Dir: %s\n", args.Get(1).Dir())
fmt.Printf("Ext: %s\n", args.Get(1).Ext())
fmt.Printf("IsAbs: %t\n", args.Get(1).IsAbs())
Output:

Arguments: [run /srv/app//conf/myapp.conf]
Clean: /srv/app/conf/myapp.conf
Base: myapp.conf
Dir: /srv/app/conf
Ext: .conf
IsAbs: true

func (Argument) Dir

func (a Argument) Dir() Argument

Dir is shorthand analog of path.Dir

Example
opts := NewOptions()

input := "run /srv/app//conf/myapp.conf"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Clean: %s\n", args.Get(1).Clean())
fmt.Printf("Base: %s\n", args.Get(1).Base())
fmt.Printf("Dir: %s\n", args.Get(1).Dir())
fmt.Printf("Ext: %s\n", args.Get(1).Ext())
fmt.Printf("IsAbs: %t\n", args.Get(1).IsAbs())
Output:

Arguments: [run /srv/app//conf/myapp.conf]
Clean: /srv/app/conf/myapp.conf
Base: myapp.conf
Dir: /srv/app/conf
Ext: .conf
IsAbs: true

func (Argument) Ext

func (a Argument) Ext() Argument

Ext is shorthand analog of path.Ext

Example
opts := NewOptions()

input := "run /srv/app//conf/myapp.conf"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Clean: %s\n", args.Get(1).Clean())
fmt.Printf("Base: %s\n", args.Get(1).Base())
fmt.Printf("Dir: %s\n", args.Get(1).Dir())
fmt.Printf("Ext: %s\n", args.Get(1).Ext())
fmt.Printf("IsAbs: %t\n", args.Get(1).IsAbs())
Output:

Arguments: [run /srv/app//conf/myapp.conf]
Clean: /srv/app/conf/myapp.conf
Base: myapp.conf
Dir: /srv/app/conf
Ext: .conf
IsAbs: true

func (Argument) Float

func (a Argument) Float() (float64, error)

Int converts argument to int

Example
opts := NewOptions()

input := "ratio 2.37"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
lines, _ := args.Get(1).Float()
fmt.Printf("Ratio: %g\n", lines)
Output:

Arguments: [ratio 2.37]
Ratio: 2.37

func (Argument) Int

func (a Argument) Int() (int, error)

Int converts argument to int

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
lines, _ := args.Get(2).Int()
fmt.Printf("Lines: %d\n", lines)
Output:

Arguments: [head file.txt 10]
Lines: 10

func (Argument) Int64

func (a Argument) Int64() (int64, error)

Int64 converts argument to int64

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
lines, _ := args.Get(2).Int64()
fmt.Printf("Lines: %d\n", lines)
Output:

Arguments: [head file.txt 10]
Lines: 10

func (Argument) Is

func (a Argument) Is(value any) bool

Is returns true if argument equals to given value

Example
opts := NewOptions()

input := "parse fileA.txt fileB.jpg fileC.txt"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Command is \"parse\": %t\n", args.Get(0).Is("parse"))
fmt.Printf("Command is \"clear\": %t\n", args.Get(0).Is("clear"))
Output:

Arguments: [parse fileA.txt fileB.jpg fileC.txt]
Command is "parse": true
Command is "clear": false

func (Argument) IsAbs

func (a Argument) IsAbs() bool

IsAbs is shorthand analog of path.IsAbs

Example
opts := NewOptions()

input := "run /srv/app//conf/myapp.conf"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Clean: %s\n", args.Get(1).Clean())
fmt.Printf("Base: %s\n", args.Get(1).Base())
fmt.Printf("Dir: %s\n", args.Get(1).Dir())
fmt.Printf("Ext: %s\n", args.Get(1).Ext())
fmt.Printf("IsAbs: %t\n", args.Get(1).IsAbs())
Output:

Arguments: [run /srv/app//conf/myapp.conf]
Clean: /srv/app/conf/myapp.conf
Base: myapp.conf
Dir: /srv/app/conf
Ext: .conf
IsAbs: true

func (Argument) Match

func (a Argument) Match(pattern string) (bool, error)

Match is shorthand analog of path.Match

Example
opts := NewOptions()

input := "parse fileA.txt fileB.jpg"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
m1, _ := args.Get(1).Match("*.txt")
m2, _ := args.Get(2).Match("*.txt")
fmt.Printf("%s is match: %t\n", args.Get(1), m1)
fmt.Printf("%s is match: %t\n", args.Get(2), m2)
Output:

Arguments: [parse fileA.txt fileB.jpg]
fileA.txt is match: true
fileB.jpg is match: false

func (Argument) String

func (a Argument) String() string

String converts argument to string

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Command: %s\n", args.Get(0).String())
Output:

Arguments: [head file.txt 10]
Command: head

func (Argument) ToLower

func (a Argument) ToLower() Argument

ToLower returns argument converted to lower case

Example
opts := NewOptions()

input := "add-user John"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", args.Get(1).ToLower().String())
Output:

Arguments: [add-user John]
User: john

func (Argument) ToUpper

func (a Argument) ToUpper() Argument

ToUpper returns argument converted to upper case

Example
opts := NewOptions()

input := "add-user John"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", args.Get(1).ToUpper().String())
Output:

Arguments: [add-user John]
User: JOHN

func (Argument) Uint

func (a Argument) Uint() (uint, error)

Uint converts argument to uint

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
lines, _ := args.Get(2).Uint()
fmt.Printf("Lines: %d\n", lines)
Output:

Arguments: [head file.txt 10]
Lines: 10

func (Argument) Uint64 added in v13.15.1

func (a Argument) Uint64() (uint64, error)

Uint converts argument to uint64

type Arguments

type Arguments []Argument

Arguments is a slice with with command argument

func NewArguments

func NewArguments(args ...string) Arguments

NewArguments creates new arguments slice from given strings

Example
args := NewArguments("head", "file.txt", "10")

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Command: %s\n", args.Get(0).String())
fmt.Printf("File: %s\n", args.Get(1).String())

lines, _ := args.Get(2).Int()
fmt.Printf("Lines: %d\n", lines)
Output:

Arguments: [head file.txt 10]
Command: head
File: file.txt
Lines: 10

func Parse

func Parse(optMap ...Map) (Arguments, errors.Errors)

Parse parses slice with raw options

Example
// Key is option in format "short-name:long-name" or "long-name"
// We highly recommend defining options names as constants
optMap := Map{
	"s:string":   {},                                             // By default, argument has string type
	"S:string2":  {Type: STRING, Value: "Default value"},         // You can predefine default values
	"int":        {Type: INT},                                    // Integer without short name
	"I:int2":     {Type: INT, Min: 1, Max: 10},                   // Integer with limits
	"f:float":    {Type: FLOAT, Value: 10.0},                     // Float
	"b:boolean":  {Type: BOOL},                                   // Boolean
	"m:merg":     {Type: STRING, Mergeble: true},                 // Mergeble options can be defined more than one time
	"h:help":     {Type: BOOL, Alias: "u:usage about"},           // You can define argument aliases
	"e:example":  {Conflicts: []string{"s:string", "S:string2"}}, // Option conflicts with string and string2 (options can't be set at same time)
	"E:example2": {Bound: "int I:int2"},                          // Option bound with int and int2 (options must be set at same time)
}

// args is a slice with command arguments
args, errs := Parse(optMap)

if len(errs) != 0 {
	for _, err := range errs {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
}

if Has("s:string") {
	fmt.Println("\"--string/-s\" is set")
} else {
	fmt.Println("\"--string/-s\" is not set")
}

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("First argument: %s\n\n", args.Get(0).String())

fmt.Printf("string → %s\n", GetS("string"))
fmt.Printf("int → %d\n", GetI("int"))
fmt.Printf("float → %f\n", GetF("f:float"))
fmt.Printf("boolean → %t\n", GetB("b:boolean"))
Output:

func (Arguments) Append

func (a Arguments) Append(args ...string) Arguments

Append adds arguments to the end of the arguments slices

Example
opts := NewOptions()

input := "head file.txt"
args, _ := opts.Parse(strings.Split(input, " "))

args = args.Append("10")

fmt.Printf("Arguments: %v\n", args.Strings())
Output:

Arguments: [head file.txt 10]

func (Arguments) Filter

func (a Arguments) Filter(pattern string) Arguments

Filter filters arguments by a given glob pattern. This method works only with files. It means that for a given path only the last part will be checked for pattern matching.

Example
opts := NewOptions()

input := "parse fileA.txt fileB.jpg fileC.txt"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Text files: %s\n", args[1:].Filter("*.txt"))
Output:

Arguments: [parse fileA.txt fileB.jpg fileC.txt]
Text files: [fileA.txt fileC.txt]

func (Arguments) Flatten

func (a Arguments) Flatten() string

Flatten converts arguments to the string (useful for custom parsing logic)

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args.Flatten())
Output:

Arguments: head file.txt 10

func (Arguments) Get

func (a Arguments) Get(index int) Argument

Get returns argument with given index

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Command: %s\n", args.Get(0).String())
fmt.Printf("File: %s\n", args.Get(1).String())

lines, _ := args.Get(2).Int()
fmt.Printf("Lines: %d\n", lines)
Output:

Arguments: [head file.txt 10]
Command: head
File: file.txt
Lines: 10

func (Arguments) Has

func (a Arguments) Has(index int) bool

Has returns true if arguments contains argument with given index

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Has command: %t\n", args.Has(0))
Output:

Arguments: [head file.txt 10]
Has command: true

func (Arguments) Last

func (a Arguments) Last() Argument

Get returns the last argument

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Last argument: %s\n", args.Last())
Output:

Arguments: [head file.txt 10]
Last argument: 10

func (Arguments) Strings

func (a Arguments) Strings() []string

Strings converts arguments to slice with strings

Example
opts := NewOptions()

input := "head file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args.Strings())
Output:

Arguments: [head file.txt 10]

func (Arguments) Unshift

func (a Arguments) Unshift(args ...string) Arguments

Unshift adds arguments to the beginning of the arguments slices

Example
opts := NewOptions()

input := "file.txt 10"
args, _ := opts.Parse(strings.Split(input, " "))

args = args.Unshift("head")

fmt.Printf("Arguments: %v\n", args.Strings())
Output:

Arguments: [head file.txt 10]

type Map

type Map map[string]*V

Map is map with list of options

func (Map) Delete

func (m Map) Delete(name string) bool

Delete removes option from map

Example
optName := "t:test"

m := Map{
	optName: &V{Value: "abcd"},
}

if m.Delete(optName) {
	fmt.Printf("Option %s deleted\n", F(optName))
} else {
	fmt.Printf("There is no option %s\n", F(optName))
}
Output:

Option -t/--test deleted

func (Map) Set

func (m Map) Set(name string, opt *V) error

Set set option in map Note that if the option is already set, it will be replaced

Example
m := Map{}

err := m.Set("t:test", &V{Value: "abcd"})

if err != nil {
	panic(err.Error())
}
Output:

func (Map) String

func (m Map) String() string

String returns string representation of options map

Example
m := Map{
	"s:size": &V{
		Type:      INT,
		Value:     25,
		Alias:     []string{"items", "objects"},
		Conflicts: "E:empty",
		Bound:     "c:create",
		Min:       10,
		Max:       1000,
	},
}

fmt.Println(m.String())
Output:

options.Map[size:Int{Value:25 Min:10 Max:1000 Alias:[--items --objects] Conflicts:-E/--empty Bound:-c/--create}]

type OptionError

type OptionError struct {
	Option      string
	BoundOption string
	Type        int
}

OptionError is argument parsing error

func (OptionError) Error

func (e OptionError) Error() string

type Options

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

Options is options struct

func NewOptions

func NewOptions() *Options

NewOptions creates new options struct

Example
opts := NewOptions()

// Add options
opts.Add("u:user", &V{Type: STRING, Value: "john"})
opts.Add("l:lines", &V{Type: INT, Min: 1, Max: 100})

// args contains unparsed values
input := "-u bob -l 12 file.txt"
args, errs := opts.Parse(strings.Split(input, " "))

if len(errs) != 0 {
	for _, err := range errs {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
}

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Lines: %d\n", opts.GetI("l:lines"))
Output:

Arguments: [file.txt]
User: bob
Lines: 12

func (*Options) Add

func (o *Options) Add(name string, option *V) error

Add adds a new option

Example
opts := NewOptions()

// Add options
opts.Add("u:user", &V{Type: STRING, Value: "john"})
opts.Add("l:lines", &V{Type: INT, Min: 1, Max: 100})

args, _ := opts.Parse([]string{"-u", "bob", "-l", "12", "file.txt"})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Lines: %d\n", opts.GetI("l:lines"))
Output:

Arguments: [file.txt]
User: bob
Lines: 12

func (*Options) AddMap

func (o *Options) AddMap(optMap Map) errors.Errors

AddMap adds map with supported options

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

args, _ := opts.Parse([]string{"-u", "bob", "-l", "12", "file.txt"})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Lines: %d\n", opts.GetI("l:lines"))
Output:

Arguments: [file.txt]
User: bob
Lines: 12

func (*Options) Delete

func (o *Options) Delete(name string) bool

Delete deletes option with given name

You can use this method to remove options with private data such as passwords, tokens, etc.

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":     {Type: STRING, Value: "john"},
	"l:lines":    {Type: INT, Min: 1, Max: 100},
	"p:password": {},
})

input := "-u bob -p Test1234 file.txt"
args, _ := opts.Parse(strings.Split(input, " "))

opts.Delete("p:password")

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Has user option: %t\n", opts.Has("u:user"))
fmt.Printf("Has lines option: %t\n", opts.Has("l:lines"))
fmt.Printf("Has password option: %t\n", opts.Has("p:password"))
Output:

Arguments: [file.txt]
Has user option: true
Has lines option: false
Has password option: false

func (*Options) GetB

func (o *Options) GetB(name string) bool

GetB returns option value as boolean

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"f:force": {Type: BOOL},
})

args, _ := opts.Parse([]string{"-u", "bob", "-f", "file.txt"})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Force: %t\n", opts.GetB("f:force"))
Output:

Arguments: [file.txt]
User: bob
Force: true

func (*Options) GetF

func (o *Options) GetF(name string) float64

GetF returns option value as floating number

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"r:ratio": {Type: FLOAT},
})

args, _ := opts.Parse([]string{"-u", "bob", "-r", "2.35", "file.txt"})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Ratio: %g\n", opts.GetF("r:ratio"))
Output:

Arguments: [file.txt]
User: bob
Ratio: 2.35

func (*Options) GetI

func (o *Options) GetI(name string) int

GetI returns option value as integer

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

args, _ := opts.Parse([]string{"-u", "bob", "-l", "12", "file.txt"})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Lines: %d\n", opts.GetI("l:lines"))
Output:

Arguments: [file.txt]
User: bob
Lines: 12

func (*Options) GetS

func (o *Options) GetS(name string) string

GetS returns option value as string

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

args, _ := opts.Parse([]string{"-u", "bob", "-l", "12", "file.txt"})

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Lines: %d\n", opts.GetI("l:lines"))
Output:

Arguments: [file.txt]
User: bob
Lines: 12

func (*Options) Has

func (o *Options) Has(name string) bool

Has checks if option with given name exists and set

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Type: STRING, Value: "john"},
	"l:lines": {Type: INT, Min: 1, Max: 100},
})

input := "-u bob file.txt"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Has user option: %t\n", opts.Has("u:user"))
fmt.Printf("Has lines option: %t\n", opts.Has("l:lines"))
Output:

Arguments: [file.txt]
Has user option: true
Has lines option: false

func (*Options) Is

func (o *Options) Is(name string, value any) bool

Is checks if option with given name has given value

func (*Options) Parse

func (o *Options) Parse(rawOpts []string, optMap ...Map) (Arguments, errors.Errors)

Parse parses slice with raw options

Example
opts := NewOptions()

input := "-u bob -l 12 file.txt"
args, _ := opts.Parse(
	strings.Split(input, " "),
	Map{
		"u:user":  {Type: STRING, Value: "john"},
		"l:lines": {Type: INT, Min: 1, Max: 100},
	},
)

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("User: %s\n", opts.GetS("u:user"))
fmt.Printf("Lines: %d\n", opts.GetI("l:lines"))
Output:

Arguments: [file.txt]
User: bob
Lines: 12

func (*Options) Split

func (o *Options) Split(name string) []string

Split splits mergeble option to it's values

Example
opts := NewOptions()

// Add options
opts.AddMap(Map{
	"u:user":  {Mergeble: true},
	"r:ratio": {Type: FLOAT},
})

// Use null-terminated string instead of default whitespace for merge.
// Note that the merge symbol must be set before the parsing options.
MergeSymbol = "\x00"

input := "-u bob -u john -u dave -r 3.14 file.txt"
args, _ := opts.Parse(strings.Split(input, " "))

fmt.Printf("Arguments: %v\n", args)
fmt.Printf("Users: %s\n", opts.Split("u:user"))
fmt.Printf("Ratio: %g\n", opts.GetF("r:ratio"))
Output:

Arguments: [file.txt]
Users: [bob john dave]
Ratio: 3.14

type V

type V struct {
	Type      uint8   // option type
	Max       float64 // maximum integer option value
	Min       float64 // minimum integer option value
	Alias     any     // string or slice of strings with aliases
	Conflicts any     // string or slice of strings with conflicts options
	Bound     any     // string or slice of strings with bound options
	Mergeble  bool    // option supports options value merging

	Value any // default value
	// contains filtered or unexported fields
}

V is basic option struct

func (*V) String

func (v *V) String() string

String returns string representation of option

Example
v := &V{
	Type:      INT,
	Value:     25,
	Alias:     "items",
	Conflicts: "E:empty",
	Bound:     "c:create",
	Min:       10,
	Max:       1000,
}

fmt.Println(v.String())
Output:

Int{Value:25 Min:10 Max:1000 Alias:--items Conflicts:-E/--empty Bound:-c/--create}

Jump to

Keyboard shortcuts

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