Documentation
¶
Overview ¶
Package config provides a cross plattform library to merge configuration files, environmental variables and command line flags.
Index ¶
- Constants
- Variables
- func Default(val interface{}) func(*Option)
- func NewProgressbar(max int64, description string, options ...progressbar.Option) *progressbar.ProgressBar
- func NewProgressbarBytes(maxBytes int64, description string, options ...progressbar.Option) *progressbar.ProgressBar
- func NewSpinner(description string, options ...progressbar.Option) *progressbar.ProgressBar
- func OnWindows() bool
- func ParseVersion(vers string) *version.Version
- func Required() func(*Option)
- func RunScaffold(fsys fs.FS, prog string) (err error)
- func Shortflag(s rune) func(*Option)
- func ValidateName(name string) (err error)
- func ValidateType(option Option) error
- type BoolGetter
- type Config
- func (c *Config) ActiveCommand() (s *Config)
- func (c *Config) Binary() (path string, err error)
- func (c *Config) Bool(name, helpText string, opts ...func(*Option)) BoolGetter
- func (c *Config) CheckMissing() error
- func (c *Config) Command(name string, helpIntro string, opts ...ConfigOption) *Config
- func (c *Config) CommmandName() string
- func (c *Config) Date(name, helpText string, opts ...func(*Option)) DateGetter
- func (c *Config) DateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
- func (c *Config) Dir(name, helpText string, opts ...func(*Option)) DirGetter
- func (c *Config) EachCommand(fn func(name string, val *Config))
- func (c *Config) EachSpec(fn func(name string, opt *Option))
- func (c *Config) EachValue(fn func(name string, val interface{}))
- func (c *Config) File(name, helpText string, opts ...func(*Option)) FileGetter
- func (c *Config) FirstGlobalsFile() path.Local
- func (c *Config) Float(name, helpText string, opts ...func(*Option)) FloatGetter
- func (c Config) GetBool(option string) bool
- func (c *Config) GetCommandConfig(name string) (s *Config, err error)
- func (c Config) GetDate(option string) (t time.Time)
- func (c Config) GetDateTime(option string) (t time.Time)
- func (c Config) GetDir(option string) path.Local
- func (c Config) GetFile(option string) path.Local
- func (c Config) GetFloat(option string) float64
- func (c Config) GetInt(option string) int
- func (c Config) GetJSON(option string, val interface{}) error
- func (c Config) GetString(option string) string
- func (c Config) GetTime(option string) (t time.Time)
- func (c Config) GetURL(option string) *url.URL
- func (c Config) GetValue(option string) interface{}
- func (c *Config) Int(name, helpText string, opts ...func(*Option)) IntGetter
- func (c *Config) IsOption(option string) bool
- func (c Config) IsSet(option string) bool
- func (c *Config) JSON(name, helpText string, opts ...func(*Option)) JSONGetter
- func (c *Config) LastBool(name, helpText string, opts ...func(*Option)) BoolGetter
- func (c *Config) LastDate(name, helpText string, opts ...func(*Option)) DateGetter
- func (c *Config) LastDateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
- func (c *Config) LastDir(name, helpText string, opts ...func(*Option)) DirGetter
- func (c *Config) LastFile(name, helpText string, opts ...func(*Option)) FileGetter
- func (c *Config) LastFloat(name, helpText string, opts ...func(*Option)) FloatGetter
- func (c *Config) LastInt(name, helpText string, opts ...func(*Option)) IntGetter
- func (c *Config) LastString(name, helpText string, opts ...func(*Option)) StringGetter
- func (c *Config) LastTime(name, helpText string, opts ...func(*Option)) TimeGetter
- func (c *Config) LastURL(name, helpText string, opts ...func(*Option)) URLGetter
- func (c *Config) Load(withArgs bool) error
- func (c *Config) LoadDefaults()
- func (c *Config) LoadFile(file path.Relative) (err error, found bool)
- func (c *Config) LoadGlobals() error
- func (c *Config) LoadLocals() error
- func (c *Config) LoadUser() error
- func (c *Config) LocalFile() path.Local
- func (c *Config) Locations(option string) []string
- func (c *Config) ManPage() string
- func (c *Config) MarshalJSON() ([]byte, error)
- func (c *Config) Merge(rd io.Reader, location path.Relative) error
- func (c *Config) MergeArgs() error
- func (c *Config) MergeEnv2() error
- func (c *Config) MustNewOption(name, type_, helpText string, opts []func(*Option)) *Option
- func (c *Config) NewOption(name, type_, helpText string, opts []func(*Option)) (*Option, error)
- func (c *Config) Relax(option string) *Config
- func (c *Config) Reset()
- func (c *Config) Run() error
- func (c *Config) RunArgs(args ...string) error
- func (c *Config) RunArgsSilent(args ...string) error
- func (cmdConfig *Config) RunCat(ty string) (outstr string, err error)
- func (cmdConfig *Config) RunGet(key, cmd string) (out string, err error)
- func (cmdConfig *Config) RunLocations() (locjson string, err error)
- func (cmdConfig *Config) RunPath(ty string) (outstr string, err error)
- func (cmdConfig *Config) RunRm(ty string) error
- func (cmdConfig *Config) RunSet(key, val string, ty string, cmd string) error
- func (cmdConfig *Config) RunUnset(key, ty string, cmd string) error
- func (c *Config) SaveToGlobals() error
- func (c *Config) SaveToLocal() error
- func (c *Config) SaveToUser() error
- func (c *Config) Set(option string, val string, location string) error
- func (c *Config) SetGlobalOptions(options map[string]string) error
- func (c *Config) SetLocalOptions(options map[string]string) error
- func (c *Config) SetUserOptions(options map[string]string) error
- func (c *Config) Skip(option string) *Config
- func (c *Config) SkipAllBut(except ...string) *Config
- func (c *Config) SpecTree() map[string]*Option
- func (c *Config) String(name, helpText string, opts ...func(*Option)) StringGetter
- func (c *Config) Time(name, helpText string, opts ...func(*Option)) TimeGetter
- func (c *Config) URL(name, helpText string, opts ...func(*Option)) URLGetter
- func (c *Config) UnmarshalJSON(data []byte) error
- func (c *Config) Usage() string
- func (c *Config) UsageOptions() string
- func (c *Config) UserFile() path.Local
- func (c *Config) ValidateValues() error
- func (c *Config) WriteConfigFile(locfile path.Relative) (err error)
- type ConfigOption
- func AsciiArt(s string) ConfigOption
- func Authors(authors ...string) ConfigOption
- func Bugs(text string) ConfigOption
- func Concept(text string) ConfigOption
- func Copyright(text string) ConfigOption
- func Documentation(text string) ConfigOption
- func Example(text string) ConfigOption
- func Filesystem(fsys fs.FS) ConfigOption
- func History(text string) ConfigOption
- func License(text string) ConfigOption
- func NoAsciiArt() ConfigOption
- func ReportingBugs(text string) ConfigOption
- func Version(v string) ConfigOption
- type DateGetter
- type DateTimeGetter
- type DirGetter
- type EmptyValueError
- type ErrDoubleOption
- type ErrDoubleShortflag
- type ErrInvalidAppName
- type ErrInvalidOptionName
- type FileGetter
- type FloatGetter
- type IntGetter
- type InvalidConfig
- type InvalidConfigEnv
- type InvalidConfigFileError
- type InvalidConfigFlag
- type InvalidDefault
- type InvalidNameError
- type InvalidTypeError
- type InvalidValueError
- type InvalidVersionError
- type JSONGetter
- type MissingOptionError
- type Option
- type StringGetter
- type TimeGetter
- type URLGetter
- type UnknownOptionError
Examples ¶
Constants ¶
const ( DateFormat = "2006-01-02" TimeFormat = "15:04:05" DateTimeFormat = "2006-01-02 15:04:05" DateTimeGeneral = "2006-01-02 15:04:05 -0700 MST" )
Variables ¶
var ( ErrInvalidShortflag = errors.New("invalid shortflag") ErrSubCommand = errors.New("sub command is not supported") ErrMissingHelp = errors.New("missing help text") )
var ( CONFIG_DIR string GLOBAL_DIRS string // colon separated list to look for WORKING_DIR string CONFIG_EXT = ".conf" )
var VERSION string
Functions ¶
func NewProgressbar ¶ added in v2.9.1
func NewProgressbar(max int64, description string, options ...progressbar.Option) *progressbar.ProgressBar
NewProgressbar returns a progressbar of github.com/schollz/progressbar/v3 Output defaults to stderr
func NewProgressbarBytes ¶ added in v2.9.1
func NewProgressbarBytes(maxBytes int64, description string, options ...progressbar.Option) *progressbar.ProgressBar
NewProgressbarBytes is NewProgressbar for bytes
func NewSpinner ¶ added in v2.9.1
func NewSpinner(description string, options ...progressbar.Option) *progressbar.ProgressBar
NewSpinner returns a progressbar of github.com/schollz/progressbar/v3 that is a spinner Output defaults to stdout
func ParseVersion ¶ added in v2.9.1
func ValidateName ¶ added in v2.1.0
rules for names:
must not start with numbers may not have more than an underscore in a row may not have more than a dash in a row may not start or end with an underscore may not start or end with a dash may not have an underscore followed by a dash may not have a dash followed by an underscore other than that, just lowercase letters are allowed we need at least two characters
func ValidateType ¶
ValidateType checks if the given type is valid. If it does, nil is returned, otherwise ErrInvalidType is returned
Types ¶
type BoolGetter ¶
type BoolGetter struct {
// contains filtered or unexported fields
}
func (*BoolGetter) Get ¶
func (b *BoolGetter) Get() bool
func (*BoolGetter) IsSet ¶
func (b *BoolGetter) IsSet() bool
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Example ¶
app := New("testapp", "help text") verbose := app.Bool("verbose", "show verbose messages", Required()) // real application would use // err := app.Run() err := app.RunArgs("--verbose") if err != nil { fmt.Printf("ERROR: %v", err) } fmt.Printf("verbose: %v", verbose.Get())
Output: verbose: true
func New ¶
func New(appname string, helpIntro string, opts ...ConfigOption) (c *Config)
New is like NewConfig, but panics on errors.
func NewConfig ¶
func NewConfig(app string, helpIntro string, mainConfig bool, opts ...ConfigOption) (c *Config, err error)
NewConfig creates a new *Config for the given appname and options It returns and error, if the appname does not conform to the naming rules.
- just lowercase letters are allowed
- it must have at least two characters
- it must not start with numbers
- it must not start or end with an underscore or a dash
- it must not have an underscore followed by an underscore or a dash
- it must not have a dash followed by a dash or an underscore
For the main config mainConfig must be set to true
func (*Config) ActiveCommand ¶
CurrentSub returns the active command
func (*Config) Bool ¶
func (c *Config) Bool(name, helpText string, opts ...func(*Option)) BoolGetter
shortcut for MustNewOption of type bool
func (*Config) CheckMissing ¶
CheckMissing checks if mandatory values are missing inside the values map CheckMissing stops on the first error
func (*Config) Command ¶
func (c *Config) Command(name string, helpIntro string, opts ...ConfigOption) *Config
Command returns a *Config for a command and panics on errors
func (*Config) CommmandName ¶
func (*Config) Date ¶
func (c *Config) Date(name, helpText string, opts ...func(*Option)) DateGetter
func (*Config) DateTime ¶
func (c *Config) DateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
shortcut for MustNewOption of type datetime
func (*Config) EachCommand ¶
func (*Config) File ¶ added in v2.6.0
func (c *Config) File(name, helpText string, opts ...func(*Option)) FileGetter
shortcut for MustNewOption of type file
func (*Config) FirstGlobalsFile ¶
GlobalFile returns the path for the global config file in the first global directory
func (*Config) Float ¶
func (c *Config) Float(name, helpText string, opts ...func(*Option)) FloatGetter
shortcut for MustNewOption of type float64
func (*Config) GetCommandConfig ¶
func (Config) GetDateTime ¶ added in v2.6.0
GetDateTime returns the value of the option as datetime
func (*Config) JSON ¶
func (c *Config) JSON(name, helpText string, opts ...func(*Option)) JSONGetter
shortcut for MustNewOption of type json
func (*Config) LastBool ¶
func (c *Config) LastBool(name, helpText string, opts ...func(*Option)) BoolGetter
LastBool receives the last argument as a boolean
func (*Config) LastDate ¶
func (c *Config) LastDate(name, helpText string, opts ...func(*Option)) DateGetter
LastDate receives the last argument as a date
func (*Config) LastDateTime ¶
func (c *Config) LastDateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
LastDateTime receives the last argument as a datetime
func (*Config) LastFile ¶ added in v2.6.0
func (c *Config) LastFile(name, helpText string, opts ...func(*Option)) FileGetter
LastFile receives the last argument as a file
func (*Config) LastFloat ¶
func (c *Config) LastFloat(name, helpText string, opts ...func(*Option)) FloatGetter
LastFloat receives the last argument as a float32
func (*Config) LastString ¶
func (c *Config) LastString(name, helpText string, opts ...func(*Option)) StringGetter
LastString receives the last argument as a string
func (*Config) LastTime ¶
func (c *Config) LastTime(name, helpText string, opts ...func(*Option)) TimeGetter
LastTime receives the last argument as a time
func (*Config) LoadDefaults ¶
func (c *Config) LoadDefaults()
func (*Config) LoadGlobals ¶
LoadGlobals loads the first config file for the app it could find inside the GLOBAL_DIRS and returns an error if the config could not be merged properly If no config file could be found, no error is returned.
func (*Config) LoadLocals ¶
LoadLocals merges config inside a .config subdir in the local directory
func (*Config) LocalFile ¶
LocalFile returns the local config file (inside the .config subdir of the current working dir)
func (*Config) Locations ¶
Location returns the locations where the option was set in the order of setting.
The locations are tracked differently: - defaults are tracked by their %v printed value - environment variables are tracked by their name - config files are tracked by their path - cli args are tracked by their name - settings via Set() are tracked by the given location or the caller if that is empty
func (*Config) MarshalJSON ¶
MarshalJSON serializes the spec to JSON
func (*Config) MergeArgs ¶
MergeArgs merges the os.Args into the config args like --a-key='a val' will correspond to the config value A_KEY=a val If the key is CONFIG_SPEC, MergeArgs will print the config spec as json and exit the program If any error happens the error will be printed to os.StdErr and the program exists will status code 1 exiting the program. also if --config_spec is set the spec is directly written to the StdOut and the program is exiting. If --help is set, the help message is printed with the the help messages for the config options. If --version is set, the version of the running app is returned
func (*Config) MustNewOption ¶
panics for invalid values
func (*Config) Reset ¶
func (c *Config) Reset()
Reset cleans the values, the locations and any current subcommand
func (*Config) Run ¶
Load loads the config values in the following order where each loader overwrittes corresponding config keys that have been defined
defaults global config user config local config env config args config
in the args config any wrong syntax or values result in writing the error to StdErr and exiting the program. also if --config_spec is set the spec is directly written to the StdOut and the program is exiting. If --help is set, the help message is printed with the the help messages for the config options
func (*Config) RunArgsSilent ¶ added in v2.1.0
RunArgsSilent runs the config by just respecting the given args and don't print anything for defaults
func (*Config) RunLocations ¶ added in v2.1.5
func (*Config) SaveToGlobals ¶
SaveToGlobals saves the given config values to a global config file don't save secrets inside the global config, since it is readable for everyone A new global config is written with 0644. The config is saved inside the first directory of GLOBAL_DIRS
func (*Config) SaveToLocal ¶
SaveToLocal saves all values to the local config file A new config is written with 0640, ro readable for user group and writeable for the user
func (*Config) SaveToUser ¶
SaveToUser saves all values to the user config file creating missing directories A new config is written with 0640, ro readable for user group and writeable for the user
func (*Config) Set ¶
Set sets the option to the value. Location is a hint from where the option setting was triggered. If the location is empty, the caller file and line is tracked as location.
func (*Config) SetGlobalOptions ¶
func (*Config) Skip ¶
Skip skips the given option of the parent command and is chainable It panics, if the given option is not a parent option of if the current config is no subcommand
func (*Config) SkipAllBut ¶
Skip skips all options of the parent command but the given
func (*Config) String ¶
func (c *Config) String(name, helpText string, opts ...func(*Option)) StringGetter
shortcut for MustNewOption of type string
func (*Config) Time ¶
func (c *Config) Time(name, helpText string, opts ...func(*Option)) TimeGetter
func (*Config) UnmarshalJSON ¶
UnmarshalJSON deserializes the spec from JSON
func (*Config) UsageOptions ¶ added in v2.4.3
func (*Config) ValidateValues ¶
ValidateValues validates only values that are set and not nil. It does not check for missing mandatory values (use CheckMissing for that) ValidateValues stops on the first error
type ConfigOption ¶ added in v2.2.2
type ConfigOption func(c *Config)
func AsciiArt ¶ added in v2.2.2
func AsciiArt(s string) ConfigOption
func Authors ¶ added in v2.4.9
func Authors(authors ...string) ConfigOption
func Bugs ¶ added in v2.4.9
func Bugs(text string) ConfigOption
func Concept ¶ added in v2.4.9
func Concept(text string) ConfigOption
func Copyright ¶ added in v2.4.0
func Copyright(text string) ConfigOption
func Documentation ¶ added in v2.4.9
func Documentation(text string) ConfigOption
func Example ¶ added in v2.4.0
func Example(text string) ConfigOption
func Filesystem ¶ added in v2.6.0
func Filesystem(fsys fs.FS) ConfigOption
func History ¶ added in v2.4.9
func History(text string) ConfigOption
func License ¶ added in v2.4.0
func License(text string) ConfigOption
func NoAsciiArt ¶ added in v2.9.1
func NoAsciiArt() ConfigOption
func ReportingBugs ¶ added in v2.4.9
func ReportingBugs(text string) ConfigOption
func Version ¶
func Version(v string) ConfigOption
Version set the version explicit. Otherwise the build version is taken from the VCS.
type DateGetter ¶ added in v2.6.0
type DateGetter struct {
// contains filtered or unexported fields
}
func (*DateGetter) Get ¶ added in v2.6.0
func (b *DateGetter) Get() time.Time
func (*DateGetter) IsSet ¶ added in v2.6.0
func (b *DateGetter) IsSet() bool
type DateTimeGetter ¶
type DateTimeGetter struct {
// contains filtered or unexported fields
}
func (*DateTimeGetter) Get ¶
func (b *DateTimeGetter) Get() time.Time
func (*DateTimeGetter) IsSet ¶
func (b *DateTimeGetter) IsSet() bool
type DirGetter ¶ added in v2.6.0
type DirGetter struct {
// contains filtered or unexported fields
}
type EmptyValueError ¶
type EmptyValueError string
func (EmptyValueError) Error ¶
func (e EmptyValueError) Error() string
type ErrDoubleOption ¶
type ErrDoubleOption string
func (ErrDoubleOption) Error ¶
func (e ErrDoubleOption) Error() string
type ErrDoubleShortflag ¶
type ErrDoubleShortflag string
func (ErrDoubleShortflag) Error ¶
func (e ErrDoubleShortflag) Error() string
type ErrInvalidAppName ¶
type ErrInvalidAppName string
func (ErrInvalidAppName) Error ¶
func (e ErrInvalidAppName) Error() string
type ErrInvalidOptionName ¶
type ErrInvalidOptionName string
func (ErrInvalidOptionName) Error ¶
func (e ErrInvalidOptionName) Error() string
type FileGetter ¶ added in v2.6.0
type FileGetter struct {
// contains filtered or unexported fields
}
func (*FileGetter) Get ¶ added in v2.6.0
func (b *FileGetter) Get() path.Local
func (*FileGetter) IsSet ¶ added in v2.6.0
func (b *FileGetter) IsSet() bool
type FloatGetter ¶
type FloatGetter struct {
// contains filtered or unexported fields
}
func (*FloatGetter) Get ¶
func (b *FloatGetter) Get() float64
func (*FloatGetter) IsSet ¶
func (b *FloatGetter) IsSet() bool
type InvalidConfig ¶
func (InvalidConfig) Error ¶
func (e InvalidConfig) Error() string
type InvalidConfigEnv ¶
func (InvalidConfigEnv) Error ¶
func (e InvalidConfigEnv) Error() string
type InvalidConfigFileError ¶
func (InvalidConfigFileError) Error ¶
func (e InvalidConfigFileError) Error() string
type InvalidConfigFlag ¶
func (InvalidConfigFlag) Error ¶
func (e InvalidConfigFlag) Error() string
type InvalidDefault ¶
type InvalidDefault struct {
Option
}
func (InvalidDefault) Error ¶
func (e InvalidDefault) Error() string
type InvalidNameError ¶
type InvalidNameError string
func (InvalidNameError) Error ¶
func (e InvalidNameError) Error() string
type InvalidTypeError ¶
type InvalidTypeError struct {
Option
}
func (InvalidTypeError) Error ¶
func (e InvalidTypeError) Error() string
type InvalidValueError ¶
type InvalidValueError struct { Option Value interface{} }
func (InvalidValueError) Error ¶
func (e InvalidValueError) Error() string
type InvalidVersionError ¶
type InvalidVersionError string
func (InvalidVersionError) Error ¶
func (e InvalidVersionError) Error() string
type JSONGetter ¶
type JSONGetter struct {
// contains filtered or unexported fields
}
func (*JSONGetter) Get ¶
func (b *JSONGetter) Get(val interface{}) error
func (*JSONGetter) IsSet ¶
func (b *JSONGetter) IsSet() bool
type MissingOptionError ¶
func (MissingOptionError) Error ¶
func (e MissingOptionError) Error() string
type Option ¶
type Option struct { // Name must consist of words that are joined by the underscore character _ // Each word must consist of uppercase letters [A-Z] and may have numbers // A word must consist of two ascii characters or more. // A name must at least have one word // If the option is the flag-less last argument, Name is empty Name string `json:"name"` // Required indicates, if the Option is required Required bool `json:"required"` // Type must be one of "bool","int","float64","string","datetime","json", "dir", "file", "url" Type string `json:"type"` // The Help string is part of the documentation Help string `json:"help"` // The Default value for the Config. The value might be nil for optional Options. // Otherwise, it must have the same type as the Type property indicates Default interface{} `json:"default,omitempty"` // A Shortflag for the Option. Shortflags may only be used for commandline flags // They must be a single lowercase ascii character Shortflag string `json:"shortflag,omitempty"` // LastArgName is only set if the Option is the flag-less last argument (then Name is empty) LastArgName string `json:"lastargname,omitempty"` }
func (Option) Validate ¶
Validate checks if the Option is valid. If it does, nil is returned, otherwise the error is returned
func (Option) ValidateDefault ¶
ValidateDefault checks if the default value is valid. If it does, nil is returned, otherwise ErrInvalidDefault is returned or a json unmarshalling error if the type is json
func (Option) ValidateValue ¶
ValidateValue checks if the given value is valid. If it does, nil is returned, otherwise ErrInvalidValue is returned or a json unmarshalling error if the type is json
type StringGetter ¶
type StringGetter struct {
// contains filtered or unexported fields
}
func (*StringGetter) Get ¶
func (b *StringGetter) Get() string
func (*StringGetter) IsSet ¶
func (b *StringGetter) IsSet() bool
type TimeGetter ¶ added in v2.6.0
type TimeGetter struct {
// contains filtered or unexported fields
}
func (*TimeGetter) Get ¶ added in v2.6.0
func (b *TimeGetter) Get() time.Time
func (*TimeGetter) IsSet ¶ added in v2.6.0
func (b *TimeGetter) IsSet() bool
type URLGetter ¶ added in v2.6.0
type URLGetter struct {
// contains filtered or unexported fields
}
type UnknownOptionError ¶
func (UnknownOptionError) Error ¶
func (e UnknownOptionError) Error() string