flags

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2020 License: MIT Imports: 7 Imported by: 0

README

flags

Build Status codecov

Flags is partially an alternative, partially an extension to the golang's standard flags package.

Flags aims to allow a more unix-style development of application's arguments, providing the following features:

  • Double dash (--option) for long syntax options
  • Single dash (-o) for short syntax options
  • Possibility to accumulate short syntax options (like -opx)
  • An automatic and opt-in --help (or -h) common print (column-based, including app name, version, description. See examples)

Detailed information

This package divides the arguments in two different types:

  • Command, used to tell the application to run a specific runtime
  • Option, used to setup the command's workflow

The most common usage of a CLI command is as follows:

my-binary --option 123 -xy

This application thus uses three different (root) options (--option, -x and -y), represented by a long and two short syntaxes.

Another possibility is to tell the application to run a specific runtime (or command):

my-binary convert --convert-option 1

In this case the application will call the convert runtime with the --convert-option option set to 1.

With this library you can combine options of commands, subcommands and root options, too. Here is an example:

my-binary --verbose convert --convert-option 1

This will turn the (root) option --verbose on, select the convert command and set the command's --convert-option option to 1.

The flags object accepts both a series of Commands and Options, and commands do the same.

See examples/main.go for a complete example.

Usage

import (
  "github.com/elegos/flags"
)

// Setup the flags object
flag := flags.Flags{}
flag.Init("app name", "app description")
flag.AppVersion = "1.0.0"

// Add the "help" helper to show the help message
// when --help or -h is passed (root option). This will
// also handle the sub-commands help pages (i.e. --help command)
flag.WithOptions(flags.HelpOption)

// create some options
opt1 := flags.NewBool("bool", 'b', "description", false)
opt2 := flags.NewString("str", 's', "description", "")

// one of the two syntaxes is optional
// flags.EmptyShort is an alias of empty rune type
opt3 := flags.NewBool("bool2", flags.EmptyShort, "no short syntax", false)
opt4 := flags.NewBool("", 'p', "no long syntax", false)

// add them to the application's root
flag.WithOptions(opt1, opt2)

// create a command with an option
cmd1 := &flags.Command{Name: "command"}
cmd1opt1 := flags.NewFloat64("float", 'f', "description", 0.0)

cmd1.WithOptions(cm1opt1)

// add the command to the application's root
flag.WithCommands(cmd1)

// parse the flags
err := flag.Parse(true)
if err != nil {
  panic(err)
}

// value extractors
isOpt1True := flags.BoolValue(opt1)
opt2Value := flags.StringValue(opt2)
cmd1opt1Value := flags.Float64Value(cmd1opt1)

// continue with application's workflow
Help output example (from examples/main.go)
AppName version 0.0.1

This is a description long enough to let it go on a new line: this tests the
capability of managing columns automatically.

Available options.

--debug                         -d              Enable debug session (default value: "false")
--very-very-long-option                         (default value: "false")
                                -z              Z factor (default value: "false")
--help                          -h              Show the application's help (default value: "false")

Available commands.
Use --help {command} {subcommand} for details.

- build         Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua.
- test          Do test stuff

Option types (out of the box)

This is the series of option types and option builders you can use out of the box (see option_values.go):

  • flags.Bool via flags.NewBool
  • flags.Int via flags.NewInt
  • flags.Int64 via flags.NewInt64
  • flags.Float32 via flags.NewFloat32
  • flags.Float64 via flags.NewFloat64
  • flags.String via flags.NewString
  • flags.Uint via flags.NewUint
  • flags.Uint64 via flags.NewUint64

Option types extension

If you need a particular option type, you can easily create a new one. It MUST adhere to the flags.Value interface. Option values SHOULD have a builder function to init an *flags.Option and a value getter to easily get the option (see option_values.go and option_values_fn.go), as follows:

func NewTypeStruct(long string, short rune, description string, defaultValue Type) *flags.Option {
  return &Option{
    Long:        long,
    Short:       short,
    Description: description,
    Value:       &TypeStruct{ DefaultValue: defaultValue }
  }
}

func TypeStructValue(option *Option) (Type, error) {
	if value, ok := option.Value.(*TypeStruct); ok {
		if setCondition {
			return value.Value, nil
		}

		return value.DefaultValue, nil
	}

	return typeDefault, fmt.Errorf("Not a Type option")
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var EmptyShort rune

EmptyShort the short option name's null-value

View Source
var HelpOption = &Option{
	Short:       'h',
	Long:        "help",
	Description: "Show the application's help",
	Value:       &Bool{},
}

HelpOption add it to the root to enable the automatic help prompt

Functions

func BoolValue

func BoolValue(option *Option) (bool, error)

BoolValue return the value of a Bool option

func Float32Value

func Float32Value(option *Option) (float32, error)

Float32Value return the value of a Float32 option

func Float64Value

func Float64Value(option *Option) (float64, error)

Float64Value return the value of a Float64 option

func Int64Value

func Int64Value(option *Option) (int64, error)

Int64Value return the value of an Int option

func IntValue

func IntValue(option *Option) (int, error)

IntValue return the value of an Int option

func StringValue

func StringValue(option *Option) (string, error)

StringValue return the value of a String option

func Uint64Value

func Uint64Value(option *Option) (uint64, error)

Uint64Value return the value of a Float64 option

func UintValue

func UintValue(option *Option) (uint, error)

UintValue return the value of a Float64 option

Types

type Bool

type Bool struct {
	Value        bool
	DefaultValue bool
	ValueSet     bool
}

Bool bool option value (and default value)

func (*Bool) DefaultValueString

func (val *Bool) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Bool) IsBoolValue

func (val *Bool) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Bool) Set

func (val *Bool) Set(value string) error

Set set the value

func (*Bool) String

func (val *Bool) String() string

String representation of the value

type Command

type Command struct {
	Name        string     // Name of the command
	Description string     // Description of the command
	Options     []*Option  // Eventual options bound to the command
	SubCommands []*Command // Eventual sub-commands
	Called      bool
}

Command a command, or subcommand, called by the user

func (*Command) WithCommands

func (cmd *Command) WithCommands(cmds ...*Command)

WithCommands add multiple sub-commands at once

func (*Command) WithOptions

func (cmd *Command) WithOptions(opts ...*Option)

WithOptions add multiple options at once

type Flags

type Flags struct {
	AppName        string     // application's name
	AppVersion     string     // application's version
	AppDescription string     // application's description
	Options        []*Option  // application-level options
	Commands       []*Command // available commands
	// contains filtered or unexported fields
}

Flags main struct for setting up commands and options

func (*Flags) GetCalledCommand

func (flags *Flags) GetCalledCommand() *Command

GetCalledCommand Get the called command, if any

func (*Flags) Init

func (flags *Flags) Init(appName string, appDescription string)

Init set the basic information

func (*Flags) Parse

func (flags *Flags) Parse(printHelpOnError bool) error

Parse parse the application's arguments

func (*Flags) ParseArgs

func (flags *Flags) ParseArgs(args []string, printHelpOnError bool) error

ParseArgs parse arbitrary arguments

func (*Flags) PrintHelp

func (flags *Flags) PrintHelp()

PrintHelp print the help information

func (*Flags) PrintHelpWithArgs

func (flags *Flags) PrintHelpWithArgs(args []string, output io.Writer)

PrintHelpWithArgs print the help information

func (*Flags) WithCommands

func (flags *Flags) WithCommands(cmds ...*Command)

WithCommands add a command to the main help object

func (*Flags) WithOptions

func (flags *Flags) WithOptions(opts ...*Option)

WithOptions add one or more options to the main help object

type Float32

type Float32 struct {
	Value        float32
	DefaultValue float32
	ValueSet     bool
}

Float32 float32 option value (and default value)

func (*Float32) DefaultValueString

func (val *Float32) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Float32) IsBoolValue

func (val *Float32) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Float32) Set

func (val *Float32) Set(value string) error

Set set the value

func (*Float32) String

func (val *Float32) String() string

String representation of the value

type Float64

type Float64 struct {
	Value        float64
	DefaultValue float64
	ValueSet     bool
}

Float64 float64 option value (and default value)

func (*Float64) DefaultValueString

func (val *Float64) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Float64) IsBoolValue

func (val *Float64) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Float64) Set

func (val *Float64) Set(value string) error

Set set the value

func (*Float64) String

func (val *Float64) String() string

String representation of the value

type Int

type Int struct {
	Value        int
	DefaultValue int
	ValueSet     bool
}

Int integer option value (and default value)

func (*Int) DefaultValueString

func (val *Int) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Int) IsBoolValue

func (val *Int) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Int) Set

func (val *Int) Set(value string) error

Set set the value

func (*Int) String

func (val *Int) String() string

String representation of the value

type Int64

type Int64 struct {
	Value        int64
	DefaultValue int64
	ValueSet     bool
}

Int64 64-bits option integer value (and default value)

func (*Int64) DefaultValueString

func (val *Int64) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Int64) IsBoolValue

func (val *Int64) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Int64) Set

func (val *Int64) Set(value string) error

Set set the value

func (*Int64) String

func (val *Int64) String() string

String representation of the value

type Option

type Option struct {
	Short       rune   // Short option name (i.e. 'd')
	Long        string // Long option name (i.e. "debug")
	Description string // Option's description (i.e. "Log debug messages")
	Value       Value  // Option's value and default value
}

Option Application or command level option

func NewBool

func NewBool(long string, short rune, description string, defaultValue bool) *Option

NewBool create a bool option

func NewFloat32

func NewFloat32(long string, short rune, description string, defaultValue float32) *Option

NewFloat32 create an Float32 option

func NewFloat64

func NewFloat64(long string, short rune, description string, defaultValue float64) *Option

NewFloat64 create an Float64 option

func NewInt

func NewInt(long string, short rune, description string, defaultValue int) *Option

NewInt create an int option

func NewInt64

func NewInt64(long string, short rune, description string, defaultValue int64) *Option

NewInt64 create an Int64 option

func NewString

func NewString(long string, short rune, description string, defaultValue string) *Option

NewString create a string option

func NewUint

func NewUint(long string, short rune, description string, defaultValue uint) *Option

NewUint create an Float64 option

func NewUint64

func NewUint64(long string, short rune, description string, defaultValue uint64) *Option

NewUint64 create an Float64 option

type String

type String struct {
	Value        string
	DefaultValue string
}

String string option value (and default value)

func (*String) DefaultValueString

func (val *String) DefaultValueString() string

DefaultValueString string representation of the default value

func (*String) IsBoolValue

func (val *String) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*String) Set

func (val *String) Set(value string) error

Set set the value

func (*String) String

func (val *String) String() string

String representation of the value

type Uint

type Uint struct {
	Value        uint
	DefaultValue uint
	ValueSet     bool
}

Uint unsigned integer option value (and default value)

func (*Uint) DefaultValueString

func (val *Uint) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Uint) IsBoolValue

func (val *Uint) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Uint) Set

func (val *Uint) Set(value string) error

Set set the value

func (*Uint) String

func (val *Uint) String() string

String representation of the value

type Uint64

type Uint64 struct {
	Value        uint64
	DefaultValue uint64
	ValueSet     bool
}

Uint64 64-bits unsigned integer option value (and default value)

func (*Uint64) DefaultValueString

func (val *Uint64) DefaultValueString() string

DefaultValueString string representation of the default value

func (*Uint64) IsBoolValue

func (val *Uint64) IsBoolValue() bool

IsBoolValue check if value is boolean

func (*Uint64) Set

func (val *Uint64) Set(value string) error

Set set the value

func (*Uint64) String

func (val *Uint64) String() string

String representation of the value

type Value

type Value interface {
	String() string             // String representation of the value
	DefaultValueString() string // String representation of the default value
	// Set - Used to set from the application's arguments.
	// If RequiresValue() == true, ("true" or "") or "false" are expected
	Set(string) error
	IsBoolValue() bool // If it returns true and no parameter is specified, Set will be called with "true"
}

Value all values must adhere to this interface

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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