config: github.com/metakeule/config Index | Examples | Files | Directories

package config

import "github.com/metakeule/config"

Package config provides a cross plattform library to merge configuration files, environmental variables and command line flags.

Index

Examples

Package Files

config.go doc.go env_linux.go errors.go files.go getter.go helper.go loader.go option.go saver.go

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]$")
)

func Default Uses

func Default(val interface{}) func(*Option)

func Required Uses

func Required(o *Option)

func Shortflag Uses

func Shortflag(s rune) func(*Option)

func ValidateName Uses

func ValidateName(name string) error

ValidateName checks if the given name conforms to the naming convention. If it does, nil is returned, otherwise ErrInvalidName is returned

func ValidateShortflag Uses

func ValidateShortflag(shortflag string) error

func ValidateType Uses

func ValidateType(option, typ string) error

ValidateType checks if the given type is valid. If it does, nil is returned, otherwise ErrInvalidType is returned

func ValidateVersion Uses

func ValidateVersion(version string) error

type BoolGetter Uses

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

func (*BoolGetter) Get Uses

func (b *BoolGetter) Get() bool

func (*BoolGetter) IsSet Uses

func (b *BoolGetter) IsSet() bool

type Config Uses

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

Code:

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 MustNew Uses

func MustNew(app string, version string, helpIntro string) *Config

MustNew calls New() and panics on errors

func New Uses

func New(app string, version string, helpIntro string) (c *Config, err error)

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 Uses

func (c *Config) ActiveCommand() (s *Config)

CurrentSub returns the active command

func (*Config) Binary Uses

func (c *Config) Binary() (path string, err error)

Binary returns the path to the binary of the app

func (*Config) CheckMissing Uses

func (c *Config) CheckMissing() error

CheckMissing checks if mandatory values are missing inside the values map CheckMissing stops on the first error

func (*Config) Command Uses

func (c *Config) Command(name string, helpIntro string) (s *Config, err error)

Sub returns a *Config for a subcommand. If name does not match to NameRegExp, an error is returned

func (*Config) CommmandName Uses

func (c *Config) CommmandName() string

func (*Config) EachSpec Uses

func (c *Config) EachSpec(fn func(name string, opt *Option))

func (*Config) EachValue Uses

func (c *Config) EachValue(fn func(name string, val interface{}))

func (*Config) FirstGlobalsFile Uses

func (c *Config) FirstGlobalsFile() string

GlobalFile returns the path for the global config file in the first global directory

func (Config) GetBool Uses

func (c Config) GetBool(option string) bool

GetBool returns the value of the option as bool

func (Config) GetFloat32 Uses

func (c Config) GetFloat32(option string) float32

GetFloat32 returns the value of the option as float32

func (Config) GetInt32 Uses

func (c Config) GetInt32(option string) int32

GetInt32 returns the value of the option as int32

func (Config) GetJSON Uses

func (c Config) GetJSON(option string, val interface{}) error

GetJSON unmarshals the value of the option to val.

func (Config) GetString Uses

func (c Config) GetString(option string) string

GetString returns the value of the option as string

func (Config) GetTime Uses

func (c Config) GetTime(option string) (t time.Time)

GetTime returns the value of the option as time

func (Config) GetValue Uses

func (c Config) GetValue(option string) interface{}

GetValue returns the value of the option

func (*Config) IsOption Uses

func (c *Config) IsOption(option string) bool

IsOption returns true, if the given option is allowed

func (Config) IsSet Uses

func (c Config) IsSet(option string) bool

IsSet returns true, if the given option is set and false if not.

func (*Config) Load Uses

func (c *Config) Load(withArgs bool) error

func (*Config) LoadDefaults Uses

func (c *Config) LoadDefaults()

func (*Config) LoadFile Uses

func (c *Config) LoadFile(path string) (err error, found bool)

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 Uses

func (c *Config) LoadGlobals() error

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 Uses

func (c *Config) LoadLocals() error

LoadLocals merges config inside a .config subdir in the local directory

func (*Config) LoadUser Uses

func (c *Config) LoadUser() error

LoadUser loads the user specific config file

func (*Config) LocalFile Uses

func (c *Config) LocalFile() string

LocalFile returns the local config file (inside the .config subdir of the current working dir)

func (*Config) Locations Uses

func (c *Config) Locations(option string) []string

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 Uses

func (c *Config) MarshalJSON() ([]byte, error)

MarshalJSON serializes the spec to JSON

func (*Config) Merge Uses

func (c *Config) Merge(rd io.Reader, location string) error

func (*Config) MergeArgs Uses

func (c *Config) MergeArgs() error

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) MergeEnv Uses

func (c *Config) MergeEnv() error

func (*Config) MustCommand Uses

func (c *Config) MustCommand(name string, helpIntro string) *Config

MustSub calls Sub() and panics on errors

func (*Config) MustNewOption Uses

func (c *Config) MustNewOption(name, type_, helpText string, opts []func(*Option)) *Option

panics for invalid values

func (*Config) NewBool Uses

func (c *Config) NewBool(name, helpText string, opts ...func(*Option)) BoolGetter

shortcut for MustNewOption of type bool

func (*Config) NewDate Uses

func (c *Config) NewDate(name, helpText string, opts ...func(*Option)) DateTimeGetter

func (*Config) NewDateTime Uses

func (c *Config) NewDateTime(name, helpText string, opts ...func(*Option)) DateTimeGetter

shortcut for MustNewOption of type datetime

func (*Config) NewFloat32 Uses

func (c *Config) NewFloat32(name, helpText string, opts ...func(*Option)) Float32Getter

shortcut for MustNewOption of type float32

func (*Config) NewInt32 Uses

func (c *Config) NewInt32(name, helpText string, opts ...func(*Option)) Int32Getter

shortcut for MustNewOption of type int32

func (*Config) NewJSON Uses

func (c *Config) NewJSON(name, helpText string, opts ...func(*Option)) JSONGetter

shortcut for MustNewOption of type json

func (*Config) NewOption Uses

func (c *Config) NewOption(name, type_, helpText string, opts []func(*Option)) (*Option, error)

adds a new option

func (*Config) NewString Uses

func (c *Config) NewString(name, helpText string, opts ...func(*Option)) StringGetter

shortcut for MustNewOption of type string

func (*Config) NewTime Uses

func (c *Config) NewTime(name, helpText string, opts ...func(*Option)) DateTimeGetter

func (*Config) Relax Uses

func (c *Config) Relax(option string) *Config

func (*Config) Reset Uses

func (c *Config) Reset()

Reset cleans the values, the locations and any current subcommand

func (*Config) Run Uses

func (c *Config) Run() error

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 Uses

func (c *Config) SaveToGlobals() error

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 Uses

func (c *Config) SaveToLocal() error

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 Uses

func (c *Config) SaveToUser() error

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 Uses

func (c *Config) Set(option string, val string, location string) error

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 Uses

func (c *Config) SetGlobalOptions(options map[string]string) error

func (*Config) SetLocalOptions Uses

func (c *Config) SetLocalOptions(options map[string]string) error

func (*Config) SetUserOptions Uses

func (c *Config) SetUserOptions(options map[string]string) error

func (*Config) Skip Uses

func (c *Config) Skip(option string) *Config

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 Uses

func (c *Config) UnmarshalJSON(data []byte) error

UnmarshalJSON deserializes the spec from JSON

func (*Config) Usage Uses

func (c *Config) Usage() string

func (*Config) UserFile Uses

func (c *Config) UserFile() string

UserFile returns the user defined config file path

func (*Config) ValidateValues Uses

func (c *Config) ValidateValues() error

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 Uses

func (c *Config) WriteConfigFile(path string, perm os.FileMode) (err error)

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 Uses

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

func (*DateTimeGetter) Get Uses

func (b *DateTimeGetter) Get() time.Time

func (*DateTimeGetter) IsSet Uses

func (b *DateTimeGetter) IsSet() bool

type EmptyValueError Uses

type EmptyValueError string

func (EmptyValueError) Error Uses

func (e EmptyValueError) Error() string

type ErrDoubleOption Uses

type ErrDoubleOption string

func (ErrDoubleOption) Error Uses

func (e ErrDoubleOption) Error() string

type ErrDoubleShortflag Uses

type ErrDoubleShortflag string

func (ErrDoubleShortflag) Error Uses

func (e ErrDoubleShortflag) Error() string

type ErrInvalidAppName Uses

type ErrInvalidAppName string

func (ErrInvalidAppName) Error Uses

func (e ErrInvalidAppName) Error() string

type ErrInvalidOptionName Uses

type ErrInvalidOptionName string

func (ErrInvalidOptionName) Error Uses

func (e ErrInvalidOptionName) Error() string

type Float32Getter Uses

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

func (*Float32Getter) Get Uses

func (b *Float32Getter) Get() float32

func (*Float32Getter) IsSet Uses

func (b *Float32Getter) IsSet() bool

type Int32Getter Uses

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

func (*Int32Getter) Get Uses

func (b *Int32Getter) Get() int32

func (*Int32Getter) IsSet Uses

func (b *Int32Getter) IsSet() bool

type InvalidConfig Uses

type InvalidConfig struct {
    Version string
    Err     error
}

func (InvalidConfig) Error Uses

func (e InvalidConfig) Error() string

type InvalidConfigEnv Uses

type InvalidConfigEnv struct {
    Version string
    EnvKey  string
    Err     error
}

func (InvalidConfigEnv) Error Uses

func (e InvalidConfigEnv) Error() string

type InvalidConfigFileError Uses

type InvalidConfigFileError struct {
    ConfigFile string
    Version    string
    Err        error
}

func (InvalidConfigFileError) Error Uses

func (e InvalidConfigFileError) Error() string

type InvalidConfigFlag Uses

type InvalidConfigFlag struct {
    Version string
    Flag    string
    Err     error
}

func (InvalidConfigFlag) Error Uses

func (e InvalidConfigFlag) Error() string

type InvalidDefault Uses

type InvalidDefault struct {
    Option  string
    Type    string
    Default interface{}
}

func (InvalidDefault) Error Uses

func (e InvalidDefault) Error() string

type InvalidNameError Uses

type InvalidNameError string

func (InvalidNameError) Error Uses

func (e InvalidNameError) Error() string

type InvalidTypeError Uses

type InvalidTypeError struct {
    Option string
    Type   string
}

func (InvalidTypeError) Error Uses

func (e InvalidTypeError) Error() string

type InvalidValueError Uses

type InvalidValueError struct {
    Option string
    Value  interface{}
}

func (InvalidValueError) Error Uses

func (e InvalidValueError) Error() string

type JSONGetter Uses

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

func (*JSONGetter) Get Uses

func (b *JSONGetter) Get(val interface{}) error

func (*JSONGetter) IsSet Uses

func (b *JSONGetter) IsSet() bool

type MissingOptionError Uses

type MissingOptionError struct {
    Version string
    Option  string
}

func (MissingOptionError) Error Uses

func (e MissingOptionError) Error() string

type Option Uses

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 Uses

func (c Option) Validate() error

Validate checks if the Option is valid. If it does, nil is returned, otherwise the error is returned

func (Option) ValidateDefault Uses

func (c Option) ValidateDefault() error

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 Uses

func (c Option) ValidateValue(val interface{}) error

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 Uses

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

func (*StringGetter) Get Uses

func (b *StringGetter) Get() string

func (*StringGetter) IsSet Uses

func (b *StringGetter) IsSet() bool

type UnknownOptionError Uses

type UnknownOptionError struct {
    Version string
    Option  string
}

func (UnknownOptionError) Error Uses

func (e UnknownOptionError) Error() string

Directories

PathSynopsis
example

Package config imports 16 packages (graph) and is imported by 7 packages. Updated 2018-09-28. Refresh now. Tools for package owners.