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 Required(o *Option)
- func Shortflag(s rune) func(*Option)
- func ValidateName(name string) error
- func ValidateShortflag(shortflag string) error
- func ValidateType(option, typ string) error
- func ValidateVersion(version string) error
- type BoolGetter
- type Config
- func (c *Config) ActiveCommand() (s *Config)
- func (c *Config) Binary() (path string, err error)
- func (c *Config) CheckMissing() error
- func (c *Config) Command(name string, helpIntro string) (s *Config, err error)
- func (c *Config) CommmandName() string
- func (c *Config) EachSpec(fn func(name string, opt *Option))
- func (c *Config) EachValue(fn func(name string, val interface{}))
- func (c *Config) FirstGlobalsFile() string
- func (c Config) GetBool(option string) bool
- func (c Config) GetFloat32(option string) float32
- func (c Config) GetInt32(option string) int32
- 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) GetValue(option string) interface{}
- func (c *Config) IsOption(option string) bool
- func (c Config) IsSet(option string) bool
- func (c *Config) Load(withArgs bool) error
- func (c *Config) LoadDefaults()
- func (c *Config) LoadFile(path string) (err error, found bool)
- func (c *Config) LoadGlobals() error
- func (c *Config) LoadLocals() error
- func (c *Config) LoadUser() error
- func (c *Config) LocalFile() string
- func (c *Config) Locations(option string) []string
- func (c *Config) MarshalJSON() ([]byte, error)
- func (c *Config) Merge(rd io.Reader, location string) error
- func (c *Config) MergeArgs() error
- func (c *Config) MergeEnv() error
- func (c *Config) MustCommand(name string, helpIntro string) *Config
- func (c *Config) MustNewOption(name, type_, helpText string, opts []func(*Option)) *Option
- func (c *Config) NewBool(name, helpText string, opts ...func(*Option)) BoolGetter
- func (c *Config) NewDate(name, helpText string, opts ...func(*Option)) DateTimeGetter
- func (c *Config) NewDateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
- func (c *Config) NewFloat32(name, helpText string, opts ...func(*Option)) Float32Getter
- func (c *Config) NewInt32(name, helpText string, opts ...func(*Option)) Int32Getter
- func (c *Config) NewJSON(name, helpText string, opts ...func(*Option)) JSONGetter
- func (c *Config) NewOption(name, type_, helpText string, opts []func(*Option)) (*Option, error)
- func (c *Config) NewString(name, helpText string, opts ...func(*Option)) StringGetter
- func (c *Config) NewTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
- func (c *Config) Relax(option string) *Config
- func (c *Config) Reset()
- func (c *Config) Run() 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) UnmarshalJSON(data []byte) error
- func (c *Config) Usage() string
- func (c *Config) UserFile() string
- func (c *Config) ValidateValues() error
- func (c *Config) WriteConfigFile(path string, perm os.FileMode) (err error)
- type DateTimeGetter
- type EmptyValueError
- type ErrDoubleOption
- type ErrDoubleShortflag
- type ErrInvalidAppName
- type ErrInvalidOptionName
- type Float32Getter
- type Int32Getter
- type InvalidConfig
- type InvalidConfigEnv
- type InvalidConfigFileError
- type InvalidConfigFlag
- type InvalidDefault
- type InvalidNameError
- type InvalidTypeError
- type InvalidValueError
- type JSONGetter
- type MissingOptionError
- type Option
- type StringGetter
- type UnknownOptionError
Examples ¶
Constants ¶
const ( DateFormat = "2006-01-02" TimeFormat = "15:04:05" DateTimeFormat = "2006-01-02 15:04:05" )
Variables ¶
var ( // ErrInvalidName = errors.New("invalid name") ErrInvalidVersion = errors.New("invalid version") ErrInvalidShortflag = errors.New("invalid shortflag") ErrCommandCommand = errors.New("command of command is not supported") //ErrInvalidDefault = errors.New("invalid default") // ErrInvalidValue = errors.New("invalid value") ErrMissingHelp = errors.New("missing help text") )
var ( USER_DIR string GLOBAL_DIRS string // colon separated list to look for WORKING_DIR string CONFIG_EXT = ".conf" ENV []string ARGS []string )
var ( NameRegExp = regexp.MustCompile("^[a-z][a-z0-9]+$") VersionRegexp = regexp.MustCompile("^[a-z0-9-.]+$") ShortflagRegexp = regexp.MustCompile("^[a-z]$") )
Functions ¶
func ValidateName ¶
ValidateName checks if the given name conforms to the naming convention. If it does, nil is returned, otherwise ErrInvalidName is returned
func ValidateShortflag ¶
func ValidateType ¶
ValidateType checks if the given type is valid. If it does, nil is returned, otherwise ErrInvalidType is returned
func ValidateVersion ¶
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 := MustNew("testapp", "1.2.3", "help text") verbose := app.NewBool("verbose", "show verbose messages", Required) // real application would use // err := app.Run() empty := map[string]bool{} app.mergeArgs(false, []string{"--verbose"}, empty, empty) fmt.Printf("verbose: %v", verbose.Get())
Output: verbose: true
func New ¶
New creates a new *Config for the given app and version An error is returned, if the app and the version do not not match the following regular expressions: app => NameRegExp version => VersionRegexp
func (*Config) ActiveCommand ¶
CurrentSub returns the active command
func (*Config) CheckMissing ¶
CheckMissing checks if mandatory values are missing inside the values map CheckMissing stops on the first error
func (*Config) Command ¶
Sub returns a *Config for a subcommand. If name does not match to NameRegExp, an error is returned
func (*Config) CommmandName ¶
func (*Config) FirstGlobalsFile ¶
GlobalFile returns the path for the global config file in the first global directory
func (Config) GetFloat32 ¶
GetFloat32 returns the value of the option as float32
func (*Config) LoadDefaults ¶
func (c *Config) LoadDefaults()
func (*Config) LoadFile ¶
LoadFile merges the config from the given file and returns any error happening during the merge If the file could not be opened (does not exist), no error is returned TODO maybe an error should be returned, if the file exists, but could not be opened because of missing access rights
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) MustCommand ¶
MustSub calls Sub() and panics on errors
func (*Config) MustNewOption ¶
panics for invalid values
func (*Config) NewBool ¶
func (c *Config) NewBool(name, helpText string, opts ...func(*Option)) BoolGetter
shortcut for MustNewOption of type bool
func (*Config) NewDate ¶
func (c *Config) NewDate(name, helpText string, opts ...func(*Option)) DateTimeGetter
func (*Config) NewDateTime ¶
func (c *Config) NewDateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
shortcut for MustNewOption of type datetime
func (*Config) NewFloat32 ¶
func (c *Config) NewFloat32(name, helpText string, opts ...func(*Option)) Float32Getter
shortcut for MustNewOption of type float32
func (*Config) NewInt32 ¶
func (c *Config) NewInt32(name, helpText string, opts ...func(*Option)) Int32Getter
shortcut for MustNewOption of type int32
func (*Config) NewJSON ¶
func (c *Config) NewJSON(name, helpText string, opts ...func(*Option)) JSONGetter
shortcut for MustNewOption of type json
func (*Config) NewString ¶
func (c *Config) NewString(name, helpText string, opts ...func(*Option)) StringGetter
shortcut for MustNewOption of type string
func (*Config) NewTime ¶
func (c *Config) NewTime(name, helpText string, opts ...func(*Option)) DateTimeGetter
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) 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) UnmarshalJSON ¶
UnmarshalJSON deserializes the spec from JSON
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
func (*Config) WriteConfigFile ¶
WriteConfigFile writes the configuration values to the given file The file is overwritten/created on success and a backup of an existing file is written back if an error happens the given perm is only used to create new files.
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 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 Float32Getter ¶
type Float32Getter struct {
// contains filtered or unexported fields
}
func (*Float32Getter) Get ¶
func (b *Float32Getter) Get() float32
func (*Float32Getter) IsSet ¶
func (b *Float32Getter) IsSet() bool
type Int32Getter ¶
type Int32Getter struct {
// contains filtered or unexported fields
}
func (*Int32Getter) Get ¶
func (b *Int32Getter) Get() int32
func (*Int32Getter) IsSet ¶
func (b *Int32Getter) 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 ¶
func (InvalidDefault) Error ¶
func (e InvalidDefault) Error() string
type InvalidNameError ¶
type InvalidNameError string
func (InvalidNameError) Error ¶
func (e InvalidNameError) Error() string
type InvalidTypeError ¶
func (InvalidTypeError) Error ¶
func (e InvalidTypeError) Error() string
type InvalidValueError ¶
type InvalidValueError struct { Option string Value interface{} }
func (InvalidValueError) Error ¶
func (e InvalidValueError) 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 Name string `json:"name"` // Required indicates, if the Option is required Required bool `json:"required"` // Type must be one of "bool","int32","float32","string","datetime","json" 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"` }
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 UnknownOptionError ¶
func (UnknownOptionError) Error ¶
func (e UnknownOptionError) Error() string