goflags

package module
v0.1.50 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2024 License: MIT Imports: 27 Imported by: 264

README

goflags

License Go version Release Checks

An extension of the go flag library that adds convenience functions and functionalities like config file, better usage, short and long flag support, custom types for string slices and maps etc.

Features

  • In-built YAML Configuration file support.
  • Better usage instructions
  • Short and long flags support
  • Custom String Slice types with different options (comma-separated,normalized,etc)
  • Custom Map type
  • Flags grouping support (CreateGroup,SetGroup)

Usage

The following types are supported by the goflags library. The <name>P suffix means that the flag supports both a long and a short flag for the option.

Flag Types
Function Description
BoolVar Boolean value with long name
BoolVarP Boolean value with long short name
DurationVar Time Duration value with long name
DurationVarP Time Duration value with long short name
IntVar Integer value with long name
IntVarP Integer value with long short name
PortVar Port value with long name
PortVarP Port value with long short name
RuntimeMapVar Map value with long name
RuntimeMapVarP Map value with long short name
StringSliceVar String Slice value with long name and options
StringSliceVarConfigOnly String Slice value with long name read from config file only
StringSliceVarP String slice value with long short name and options
StringVar String value with long name
StringVarEnv String value with long short name read from environment
StringVarP String value with long short name
Var Custom value with long name implementing flag.Value interface
VarP Custom value with long short name implementing flag.Value interface
EnumVar Enum value with long name
EnumVarP Enum value with long short name
CallbackVar Callback function as value with long name
CallbackVarP Callback function as value with long short name
SizeVar String value with long name
SizeVarP String value with long short name
String Slice Options
String Slice Option Tokenization Normalization Description
StringSliceOptions None None Default String Slice
CommaSeparatedStringSliceOptions Comma None Comma-separated string slice
FileCommaSeparatedStringSliceOptions Comma None Comma-separated items from file/cli
NormalizedOriginalStringSliceOptions None Standard List of normalized string slice
FileNormalizedStringSliceOptions Comma Standard List of normalized string slice from file/cli
FileStringSliceOptions Standard Standard List of string slice from file
NormalizedStringSliceOptions Comma Standard List of normalized string slice

Example

An example showing various options of the library is specified below.

package main

import (
	"fmt"
	"log"

	"github.com/projectdiscovery/goflags"
)

type options struct {
	silent bool
	inputs goflags.StringSlice
	config string
	values goflags.RuntimeMap
}

const (
	Nil goflags.EnumVariable = iota
	Type1
	Type2
)

func main() {
	enumAllowedTypes := goflags.AllowdTypes{"type1": Type1, "type2": Type2}
	opt := &options{}

	flagSet := goflags.NewFlagSet()
	flagSet.SetDescription("Test program to demonstrate goflags options")

	flagSet.EnumVarP(&options.Type, "enum-type", "et", Nil, "Variable Type (type1/type2)", enumAllowedTypes)
	flagSet.BoolVar(&opt.silent, "silent", true, "show silent output")
	flagSet.StringSliceVarP(&opt.inputs, "inputs", "i", nil, "list of inputs (file,comma-separated)", goflags.FileCommaSeparatedStringSliceOptions)

	update := func(tool string ) func() { 
		return func()  {
			fmt.Printf("%v updated successfully!", tool)
		}
	}
	flagSet.CallbackVarP(update("tool_1"), "update", "up", "update tool_1")


	// Group example
	flagSet.CreateGroup("config", "Configuration",
		flagSet.StringVar(&opt.config, "config", "", "file to read config from"),
		flagSet.RuntimeMapVar(&opt.values, "values", nil, "key-value runtime values"),
	)
	if err := flagSet.Parse(); err != nil {
		log.Fatalf("Could not parse flags: %s\n", err)
	}
	if opt.config != "" {
		if err := flagSet.MergeConfigFile(opt.config); err != nil {
			log.Fatalf("Could not merge config file: %s\n", err)
		}
	}
	fmt.Printf("silent: %v inputs: %v config: %v values: %v\n", opt.silent, opt.inputs, opt.config, opt.values)
}
Thanks
  1. spf13/cobra - For the very nice usage template for the command line.
  2. nmap/nmap - For the service-port mapping and top-ports list.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CommaSeparatedStringSliceOptions = Options{
	IsEmpty: isEmpty,
}

CommaSeparatedStringSliceOptions represents a list of comma separated items Tokenization: Comma Normalization: None Type: []string Example: -flag value1,value2 => {"value1", "value2"}

View Source
var (
	DisableAutoConfigMigration = false
)
View Source
var FileCommaSeparatedStringSliceOptions = Options{
	IsEmpty:    isEmpty,
	IsFromFile: isFromFile,
}

FileCommaSeparatedStringSliceOptions represents a list of comma separated files containing items Tokenization: Comma Normalization: None Type: []string test.txt content: value1 value2

Example: -flag test.txt => {"value1", "value2"}

View Source
var FileNormalizedOriginalStringSliceOptions = Options{
	IsEmpty:    isEmpty,
	Normalize:  normalize,
	IsFromFile: isFromFile,
}

FileNormalizedOriginalStringSliceOptions represents a list of items stored in a file Tokenization: Comma Normalization: Standard

View Source
var FileNormalizedStringSliceOptions = Options{
	IsEmpty:    isEmpty,
	Normalize:  normalizeLowercase,
	IsFromFile: isFromFile,
}

FileNormalizedStringSliceOptions represents a list of path items Tokenization: Comma Normalization: Standard Type: []string Example: -flag /value/1 -flag value2 => {"/value/1", "value2"}

View Source
var FileStringSliceOptions = Options{
	IsEmpty:    isEmpty,
	Normalize:  normalizeTrailingParts,
	IsFromFile: isFromFile,
	IsRaw:      func(s string) bool { return true },
}

FileStringSliceOptions represents a list of items stored in a file Tokenization: Standard Normalization: Standard

View Source
var (
	MaxRateLimitTime = time.Minute // anything above time.Minute is not practical (for our use case)

)
View Source
var NormalizedOriginalStringSliceOptions = Options{
	IsEmpty:   isEmpty,
	Normalize: normalize,
}

NormalizedOriginalStringSliceOptions represents a list of items Tokenization: None Normalization: Standard Type: []string Example: -flag /value/1 -flag 'value2' => {"/value/1", "value2"}

View Source
var NormalizedStringSliceOptions = Options{
	IsEmpty:   isEmpty,
	Normalize: normalizeLowercase,
}

NormalizedStringSliceOptions represents a list of items Tokenization: Comma Normalization: Standard

View Source
var StringSliceOptions = Options{}

StringSliceOptions represents the default string slice (list of items) Tokenization: None Normalization: None Type: []string Example: -flag value1 -flag value2 => {"value1", "value2"}

Functions

func AttemptConfigMigration added in v0.1.24

func AttemptConfigMigration()

AttemptConfigMigration attempts to migrate config from old config dir to new one migration condition 1. old config dir exists 2. new config dir doesn't exist 3. old config dir is not same as new config dir

func ToString added in v0.0.8

func ToString(slice []string) string

func ToStringSlice added in v0.0.5

func ToStringSlice(value string, options Options) ([]string, error)

ToStringSlice converts a value to string slice based on options

Types

type AllowdTypes added in v0.1.1

type AllowdTypes map[string]EnumVariable

func (AllowdTypes) String added in v0.1.1

func (a AllowdTypes) String() string

type CallBackFunc added in v0.1.8

type CallBackFunc func()

CallBackFunc

type EnumSliceVar added in v0.1.13

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

func (*EnumSliceVar) Set added in v0.1.13

func (e *EnumSliceVar) Set(value string) error

func (*EnumSliceVar) String added in v0.1.13

func (e *EnumSliceVar) String() string

type EnumVar added in v0.1.1

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

func (*EnumVar) Set added in v0.1.1

func (e *EnumVar) Set(value string) error

func (*EnumVar) String added in v0.1.1

func (e *EnumVar) String() string

type EnumVariable added in v0.1.1

type EnumVariable int8

func (*EnumVariable) String added in v0.1.1

func (e *EnumVariable) String() string

type FlagData added in v0.0.5

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

func (*FlagData) Group added in v0.0.5

func (flagData *FlagData) Group(name string)

Group sets the group for a flag data

func (*FlagData) Hash added in v0.0.5

func (flagData *FlagData) Hash() string

Hash returns the unique hash for a flagData structure NOTE: Hash panics when the structure cannot be hashed.

type FlagSet

type FlagSet struct {
	CaseSensitive bool
	Marshal       bool

	CommandLine *flag.FlagSet

	// OtherOptionsGroupName is the name for all flags not in a group
	OtherOptionsGroupName string
	// contains filtered or unexported fields
}

FlagSet is a list of flags for an application

func NewFlagSet added in v0.0.5

func NewFlagSet() *FlagSet

NewFlagSet creates a new flagSet structure for the application

func (*FlagSet) BoolVar

func (flagSet *FlagSet) BoolVar(field *bool, long string, defaultValue bool, usage string) *FlagData

BoolVar adds a bool flag with a longname

func (*FlagSet) BoolVarP

func (flagSet *FlagSet) BoolVarP(field *bool, long, short string, defaultValue bool, usage string) *FlagData

BoolVarP adds a bool flag with a shortname and longname

func (*FlagSet) CallbackVar added in v0.1.8

func (flagSet *FlagSet) CallbackVar(callback CallBackFunc, long string, usage string) *FlagData

CallbackVar adds a Callback flag with a longname

func (*FlagSet) CallbackVarP added in v0.1.8

func (flagSet *FlagSet) CallbackVarP(callback CallBackFunc, long, short string, usage string) *FlagData

CallbackVarP adds a Callback flag with a shortname and longname

func (*FlagSet) CreateGroup added in v0.0.8

func (flagSet *FlagSet) CreateGroup(groupName, description string, flags ...*FlagData)

CreateGroup within the flagset

func (*FlagSet) DurationVar added in v0.0.8

func (flagSet *FlagSet) DurationVar(field *time.Duration, long string, defaultValue time.Duration, usage string) *FlagData

DurationVar adds a duration flag with a longname

func (*FlagSet) DurationVarP added in v0.0.8

func (flagSet *FlagSet) DurationVarP(field *time.Duration, long, short string, defaultValue time.Duration, usage string) *FlagData

DurationVarP adds a duration flag with a short name and long name. It is equivalent to DurationVar but also allows specifying durations in days (e.g., "2d" for 2 days, which is equivalent to 2*24h). The default unit for durations is seconds (ex: "10" => 10s).

func (*FlagSet) DynamicVar added in v0.1.19

func (flagSet *FlagSet) DynamicVar(field interface{}, long string, defaultValue interface{}, usage string) *FlagData

DynamicVar acts as flag with a default value or a option with value example:

var titleSize int
flagSet.DynamicVar(&titleSize, "title", 50, "first N characters of the title")

> go run ./examples/basic -title or go run ./examples/basic -title=100 In case of `go run ./examples/basic -title` it will use default value 50

func (*FlagSet) DynamicVarP added in v0.1.19

func (flagSet *FlagSet) DynamicVarP(field interface{}, long, short string, defaultValue interface{}, usage string) *FlagData

DynamicVarP same as DynamicVar but with short name

func (*FlagSet) EnumSliceVar added in v0.1.13

func (flagSet *FlagSet) EnumSliceVar(field *[]string, long string, defaultValues []EnumVariable, usage string, allowedTypes AllowdTypes) *FlagData

EnumVar adds a enum flag with a longname

func (*FlagSet) EnumSliceVarP added in v0.1.13

func (flagSet *FlagSet) EnumSliceVarP(field *[]string, long, short string, defaultValues []EnumVariable, usage string, allowedTypes AllowdTypes) *FlagData

EnumVarP adds a enum flag with a shortname and longname

func (*FlagSet) EnumVar added in v0.1.1

func (flagSet *FlagSet) EnumVar(field *string, long string, defaultValue EnumVariable, usage string, allowedTypes AllowdTypes) *FlagData

EnumVar adds a enum flag with a longname

func (*FlagSet) EnumVarP added in v0.1.1

func (flagSet *FlagSet) EnumVarP(field *string, long, short string, defaultValue EnumVariable, usage string, allowedTypes AllowdTypes) *FlagData

EnumVarP adds a enum flag with a shortname and longname

func (*FlagSet) GetConfigFilePath added in v0.1.1

func (flagSet *FlagSet) GetConfigFilePath() (string, error)

GetConfigFilePath returns the config file path

func (*FlagSet) GetToolConfigDir added in v0.1.22

func (flagset *FlagSet) GetToolConfigDir() string

GetToolConfigDir returns the config dir path of the tool

func (*FlagSet) IntVar

func (flagSet *FlagSet) IntVar(field *int, long string, defaultValue int, usage string) *FlagData

IntVar adds a int flag with a longname

func (*FlagSet) IntVarP

func (flagSet *FlagSet) IntVarP(field *int, long, short string, defaultValue int, usage string) *FlagData

IntVarP adds a int flag with a shortname and longname

func (*FlagSet) MergeConfigFile

func (flagSet *FlagSet) MergeConfigFile(file string) error

MergeConfigFile reads a config file to merge values from.

func (*FlagSet) Parse

func (flagSet *FlagSet) Parse() error

Parse parses the flags provided to the library.

func (*FlagSet) PortVar added in v0.1.0

func (flagSet *FlagSet) PortVar(field *Port, long string, defaultValue []string, usage string) *FlagData

PortVar adds a port flag with a longname

func (*FlagSet) PortVarP added in v0.1.0

func (flagSet *FlagSet) PortVarP(field *Port, long, short string, defaultValue []string, usage string) *FlagData

PortVarP adds a port flag with a shortname and longname

func (*FlagSet) RateLimitMapVar added in v0.1.12

func (flagSet *FlagSet) RateLimitMapVar(field *RateLimitMap, long string, defaultValue []string, usage string, options Options) *FlagData

RateLimitMapVar adds a ratelimit flag with a longname

func (*FlagSet) RateLimitMapVarP added in v0.1.12

func (flagSet *FlagSet) RateLimitMapVarP(field *RateLimitMap, long, short string, defaultValue StringSlice, usage string, options Options) *FlagData

RateLimitMapVarP adds a ratelimit flag with a short name and long name. It is equivalent to RateLimitMapVar, and also allows specifying ratelimits in days (e.g., "hackertarget=2/d" 2 requests per day, which is equivalent to 24h).

func (*FlagSet) RuntimeMapVar added in v0.0.7

func (flagSet *FlagSet) RuntimeMapVar(field *RuntimeMap, long string, defaultValue []string, usage string) *FlagData

RuntimeMapVarP adds a runtime only map flag with a longname

func (*FlagSet) RuntimeMapVarP added in v0.0.7

func (flagSet *FlagSet) RuntimeMapVarP(field *RuntimeMap, long, short string, defaultValue []string, usage string) *FlagData

RuntimeMapVarP adds a runtime only map flag with a shortname and longname

func (*FlagSet) SetConfigFilePath added in v0.1.1

func (flagSet *FlagSet) SetConfigFilePath(filePath string)

SetConfigFilePath sets custom config file path

func (*FlagSet) SetCustomHelpText added in v0.1.12

func (flagSet *FlagSet) SetCustomHelpText(helpText string)

SetCustomHelpText sets the help text for a flagSet to a value. This variable appends text to the default help text.

func (*FlagSet) SetDescription

func (flagSet *FlagSet) SetDescription(description string)

SetDescription sets the description field for a flagSet to a value.

func (*FlagSet) SetGroup added in v0.0.5

func (flagSet *FlagSet) SetGroup(name, description string)

SetGroup sets a group with name and description for the command line options

The order in which groups are passed is also kept as is, similar to flags.

func (*FlagSet) SizeVar added in v0.1.9

func (flagSet *FlagSet) SizeVar(field *Size, long string, defaultValue string, usage string) *FlagData

SizeVar converts the given fileSize with a unit (kb, mb, gb, or tb) to bytes. For example, '2kb' will be converted to 2048. If no unit is provided, it will fallback to mb. e.g: '2' will be converted to 2097152.

func (*FlagSet) SizeVarP added in v0.1.9

func (flagSet *FlagSet) SizeVarP(field *Size, long, short string, defaultValue string, usage string) *FlagData

SizeVarP converts the given fileSize with a unit (kb, mb, gb, or tb) to bytes. For example, '2kb' will be converted to 2048. If no unit is provided, it will fallback to mb. e.g: '2' will be converted to 2097152.

func (*FlagSet) StringSliceVar

func (flagSet *FlagSet) StringSliceVar(field *StringSlice, long string, defaultValue []string, usage string, options Options) *FlagData

StringSliceVar adds a string slice flag with a longname Supports ONE value at a time. Adding multiple values require repeating the argument (-flag value1 -flag value2) No value normalization is happening.

func (*FlagSet) StringSliceVarConfigOnly added in v0.0.8

func (flagSet *FlagSet) StringSliceVarConfigOnly(field *StringSlice, long string, defaultValue []string, usage string) *FlagData

StringSliceVarConfigOnly adds a string slice config value (without flag) with a longname

func (*FlagSet) StringSliceVarP

func (flagSet *FlagSet) StringSliceVarP(field *StringSlice, long, short string, defaultValue StringSlice, usage string, options Options) *FlagData

StringSliceVarP adds a string slice flag with a shortname and longname Use options to customize the behavior

func (*FlagSet) StringVar

func (flagSet *FlagSet) StringVar(field *string, long, defaultValue, usage string) *FlagData

StringVar adds a string flag with a longname

func (*FlagSet) StringVarEnv added in v0.0.3

func (flagSet *FlagSet) StringVarEnv(field *string, long, short, defaultValue, envName, usage string) *FlagData

StringVarEnv adds a string flag with a shortname and longname with a default value read from env variable with a default value fallback

func (*FlagSet) StringVarP

func (flagSet *FlagSet) StringVarP(field *string, long, short, defaultValue, usage string) *FlagData

StringVarP adds a string flag with a shortname and longname

func (*FlagSet) Var added in v0.0.3

func (flagSet *FlagSet) Var(field flag.Value, long, usage string) *FlagData

Var adds a Var flag with a longname

func (*FlagSet) VarP added in v0.0.3

func (flagSet *FlagSet) VarP(field flag.Value, long, short, usage string) *FlagData

VarP adds a Var flag with a shortname and longname

type InsertionOrderedMap added in v0.0.5

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

func (*InsertionOrderedMap) Set added in v0.0.5

func (insertionOrderedMap *InsertionOrderedMap) Set(key string, value *FlagData)

type Options added in v0.0.8

type Options struct {
	// IsFromFile determines if the values are from file
	IsFromFile func(string) bool
	// IsEmpty determines if the values are empty
	IsEmpty func(string) bool
	// Normalize the value (eg. removing trailing spaces)
	Normalize func(string) string
	// IsRaw determines if the value should be considered as a raw string
	IsRaw func(string) bool
}

type Port added in v0.1.0

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

Port is a list of unique ports in a normalized format

func (*Port) AsPorts added in v0.1.0

func (port *Port) AsPorts() []int

AsPorts returns the ports list after normalization

func (*Port) Set added in v0.1.0

func (port *Port) Set(value string) error

Set inserts a value to the port map. A number of formats are accepted.

func (Port) String added in v0.1.0

func (port Port) String() string

type RateLimit added in v0.1.12

type RateLimit struct {
	MaxCount uint
	Duration time.Duration
}

type RateLimitMap added in v0.1.12

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

func (*RateLimitMap) AsMap added in v0.1.12

func (rateLimitMap *RateLimitMap) AsMap() map[string]RateLimit

AsMap returns the internal map as reference - changes are allowed

func (*RateLimitMap) Del added in v0.1.12

func (rateLimitMap *RateLimitMap) Del(key string) error

Del removes the specified key

func (*RateLimitMap) IsEmpty added in v0.1.12

func (rateLimitMap *RateLimitMap) IsEmpty() bool

IsEmpty specifies if the underlying map is empty

func (*RateLimitMap) Set added in v0.1.12

func (rateLimitMap *RateLimitMap) Set(value string) error

Set inserts a value to the map. Format: key=value

func (RateLimitMap) String added in v0.1.12

func (rateLimitMap RateLimitMap) String() string

type RuntimeMap added in v0.0.7

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

RuntimeMap is a runtime only map of interfaces

func (*RuntimeMap) AsMap added in v0.0.7

func (runtimeMap *RuntimeMap) AsMap() map[string]interface{}

AsMap returns the internal map as reference - changes are allowed

func (*RuntimeMap) Del added in v0.0.8

func (runtimeMap *RuntimeMap) Del(key string) error

Del removes the specified key

func (*RuntimeMap) IsEmpty added in v0.0.7

func (runtimeMap *RuntimeMap) IsEmpty() bool

IsEmpty specifies if the underlying map is empty

func (*RuntimeMap) Set added in v0.0.7

func (runtimeMap *RuntimeMap) Set(value string) error

Set inserts a value to the map. Format: key=value

func (RuntimeMap) String added in v0.0.7

func (runtimeMap RuntimeMap) String() string

type Size added in v0.1.9

type Size int

func (*Size) Set added in v0.1.9

func (s *Size) Set(size string) error

func (*Size) String added in v0.1.9

func (s *Size) String() string

type StringSlice

type StringSlice []string

StringSlice is a slice of strings

func (*StringSlice) Set

func (stringSlice *StringSlice) Set(value string) error

Set appends a value to the string slice.

func (StringSlice) String

func (stringSlice StringSlice) String() string

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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