cliflags

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2022 License: BSD-3-Clause Imports: 11 Imported by: 0

README

Flags based on structures.

The cliflags package uses structs, reflection and struct field tags to allow you specify command line options. It supports different types and features.

An example:

type HTTPConfig struct {
	Host    string        `desc:"HTTP host"`
	Port    int           `flag:"port p" desc:"some port"`
	SSL     bool          `env:"HTTP_SSL_VALUE"`
	Timeout time.Duration `flag:",deprecated,hidden"`
}

type Config struct {
	HTTP  HTTPConfig
	Stats StatsConfig
}

And you can use your favorite flag or cli library!

Supported flags and cli libraries:

Features:

  • Set environment name
  • Set usage
  • Long and short forms
  • Skip field
  • Required
  • Placeholders (by name)
  • Deprecated and hidden options
  • Multiple ENV names
  • Interface for user types.
  • Validation (using govalidator package)
  • Anonymous nested structure support (anonymous structures flatten by default)

Supported types in structures:

  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • slices for all previous numeric types (e.g. []int, []float64)
  • bool
  • []bool
  • string
  • []string
  • nested structures
  • net.TCPAddr
  • net.IP
  • time.Duration
  • regexp.Regexp
  • map for all previous types (e.g. map[int64]bool, map[string]float64)

Custom types:

  • HexBytes

  • count

  • ipmask

  • enum values

  • enum list values

  • file

  • file list

  • url

  • url list

  • units (bytes 1kb = 1024b, speed, etc)

Supported features matrix:

Name Hidden Deprecated Short Env
flag - - - -
pflag [x] [x] [x] -
kingpin [x] [ ] [x] [x]
urfave [x] - [x] [x]
cobra [x] [x] [x] -
viper [ ] [ ] [ ] [ ]

[x] - feature is supported and implemented

- - feature can't be implemented for this cli library

Simple example for flag library:

package main

import (
	"flag"
	"log"
	"time"

	"github.com/octago/sflags/gen/gflag"
)

type httpConfig struct {
	Host    string `desc:"HTTP host"`
	Port    int
	SSL     bool
	Timeout time.Duration
}

type config struct {
	HTTP httpConfig
}

func main() {
	cfg := &config{
		HTTP: httpConfig{
			Host:    "127.0.0.1",
			Port:    6000,
			SSL:     false,
			Timeout: 15 * time.Second,
		},
	}
	err := gflag.ParseToDef(cfg)
	if err != nil {
		log.Fatalf("err: %v", err)
	}
	flag.Parse()
}

That code generates next output:

go run ./main.go --help
Usage of _obj/exe/main:
  -http-host value
    	HTTP host (default 127.0.0.1)
  -http-port value
    	 (default 6000)
  -http-ssl

  -http-timeout value
    	 (default 15s)
exit status 2

Look at the other examples for different flag libraries.

Options for flag tag

The flag default key string is the struct field name but can be specified in the struct field's tag value. The "flag" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:

// Field is ignored by this package.
Field int `flag:"-"`

// Field appears in flags as "myName".
Field int `flag:"myName"`

// If this field is from nested struct, prefix from parent struct will be ingored.
Field int `flag:"~myName"`

// You can set short name for flags by providing it's value after a space
// Prefixes will not be applied for short names.
Field int `flag:"myName a"`

// this field will be removed from generated help text.
Field int `flag:",hidden"`

// this field will be marked as deprecated in generated help text
Field int `flag:",deprecated"`

Options for desc tag

If you specify description in description tag (desc by default) it will be used in USAGE section.

Addr string `desc:"HTTP host"`

this description produces something like:

  -addr value
    	HTTP host (default 127.0.0.1)

Options for env tag

Options for Parse function:

// DescTag sets custom description tag. It is "desc" by default.
func DescTag(val string)

// FlagTag sets custom flag tag. It is "flag" be default.
func FlagTag(val string)

// Prefix sets prefix that will be applied for all flags (if they are not marked as ~).
func Prefix(val string)

// EnvPrefix sets prefix that will be applied for all environment variables (if they are not marked as ~).
func EnvPrefix(val string)

// FlagDivider sets custom divider for flags. It is dash by default. e.g. "flag-name".
func FlagDivider(val string)

// EnvDivider sets custom divider for environment variables.
// It is underscore by default. e.g. "ENV_NAME".
func EnvDivider(val string)

// Validator sets validator function for flags.
// Check existed validators in sflags/validator package.
func Validator(val ValidateFunc)

// Set to false if you don't want anonymous structure fields to be flatten.
func Flatten(val bool)

Known issues

  • kingpin doesn't pass value for boolean arguments. Counter can't get initial value from arguments.

Similar projects

Documentation

Overview

Package cliflags helps to generate flags by parsing structure

Index

Constants

This section is empty.

Variables

MapAllowedKinds stores list of kinds allowed for map keys.

Functions

This section is empty.

Types

type BoolFlag

type BoolFlag interface {
	Value
	IsBoolFlag() bool
}

BoolFlag is an optional interface to indicate boolean flags that don't accept v value, and implicitly have v --no-<x> negation counterpart.

type Counter

type Counter int

Counter type is useful if you want to save number by using flag multiple times in command line. It's a boolean type, so you can use it without value. If you use `struct{count Counter} and parse it with `-count=10 ... -count .. -count`, then final value of `count` will be 12. Implements Value, Getter, BoolFlag, RepeatableFlag interfaces

func (Counter) Get

func (v Counter) Get() interface{}

Get method returns inner value for Counter.

func (Counter) IsBoolFlag

func (v Counter) IsBoolFlag() bool

IsBoolFlag returns true, because Counter might be used without value.

func (Counter) IsCumulative

func (v Counter) IsCumulative() bool

IsCumulative returns true, because Counter might be used multiple times.

func (*Counter) Set

func (v *Counter) Set(s string) error

Set method parses string from command line.

func (Counter) String

func (v Counter) String() string

String returns string representation of Counter

func (Counter) Type

func (v Counter) Type() string

Type returns `count` for Counter, it's mostly for pflag compatibility.

type Flag

type Flag struct {
	Name       string // name as it appears on command line
	Short      string // optional short name
	EnvName    string // optional environment variable
	Usage      string // help message
	Value      Value  // value as set
	Default    string // default value (as text); for usage message
	Hidden     bool   // hidden flags
	Deprecated bool   // flag is no longer in use
}

Flag represents the available tags that you can use for parsing

func ParseStruct

func ParseStruct(cfg interface{}, optFuncs ...OptFunc) ([]*Flag, error)

ParseStruct parses structure and returns list of flags based on this structure. This list of flags can be used by generators for flag, kingpin, cobra, pflag, urfave/cli.

type Getter

type Getter interface {
	Value
	Get() interface{}
}

Getter is an interface that allows the contents of v Value to be retrieved. It wraps the Value interface, rather than being part of it, because it appeared after Go 1 and its compatibility rules. All Value types provided by this package satisfy the Getter interface.

type HexBytes

type HexBytes []byte

HexBytes might be used if you want to parse slice of bytes as hex string. Original `[]byte` or `[]uint8` parsed as a list of `uint8`.

type OptFunc

type OptFunc func(opt *opts)

OptFunc sets values in opts structure.

func DescTag

func DescTag(val string) OptFunc

DescTag sets custom description tag. It is "desc" by default.

func EnvDivider

func EnvDivider(val string) OptFunc

EnvDivider sets custom divider for environment variables. It is underscore by default. e.g. "ENV_NAME".

func EnvPrefix

func EnvPrefix(val string) OptFunc

EnvPrefix sets prefix that will be applied for all environment variables (if they are not marked as ~).

func FlagDivider

func FlagDivider(val string) OptFunc

FlagDivider sets custom divider for flags. It is dash by default. e.g. "flag-name".

func FlagTag

func FlagTag(val string) OptFunc

FlagTag sets custom flag tag. It is "flag" be default.

func Flatten added in v0.2.0

func Flatten(val bool) OptFunc

Flatten set flatten option. Set to false if you don't want anonymous structure fields to be flatten.

func Prefix

func Prefix(val string) OptFunc

Prefix sets prefix that will be applied for all flags (if they are not marked as ~).

type RepeatableFlag

type RepeatableFlag interface {
	Value
	IsCumulative() bool
}

RepeatableFlag is an optional interface for flags that can be repeated. required by kingpin

type ValidateFunc added in v0.2.0

type ValidateFunc func(val string, field reflect.StructField, cfg interface{}) error

ValidateFunc describes a validation func, that takes string val for flag from command line, field that's associated with this flag in structure cfg. Should return error if validation fails.

type Value

type Value interface {
	String() string
	Set(string) error

	// pflag.Flag require this
	Type() string
}

Value is the interface to the dynamic value stored in v flag. (The default value is represented as v string.)

If v Value has an IsBoolFlag() bool method returning true, the command-line parser makes --name equivalent to -name=true rather than using the next command-line argument, and adds v --no-name counterpart for negating the flag.

Directories

Path Synopsis
cmd
genvalues
This generator is for internal usage only.
This generator is for internal usage only.
examples
gen

Jump to

Keyboard shortcuts

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