config

package module
v1.12.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2018 License: MIT Imports: 16 Imported by: 4

README

config

Codeship Status for metakeule/config

Build status

cross plattform configuration tool.

Not ready for consumption yet.

Example

package main

import (
    "fmt"

    "github.com/metakeule/config"
)

var (
    cfg = config.MustNew("git", "2.1.3")
    version = cfg.NewBool("version", "prints the version")

    commit = cfg.MustSub("commit")
    
    commitCleanup = commit.NewString(
        "cleanup", 
        "This option determines how...", 
        config.Default("default"),
    )
    
    commitAll = commit.NewBool(
        "all", 
        "Tell the command to automatically...",
        config.Shortflag('a'),
    )
)

func main() {
    cfg.Run("git is a DVCS", nil)

    if version.IsSet() {
        fmt.Println("git version 2.1.3")
    }

    
    switch cfg.CurrentSub() {
    case nil:
        fmt.Println("no subcommand")
    case commit:
        fmt.Println("commit cleanup is: ", commitCleanup.Get())
        fmt.Printf("commit cleanup locations: %#v\n", commit.Locations("cleanup"))
        
        fmt.Println("commit all is: ", commitAll.Get())
        fmt.Printf("commit all locations: %#v\n", commit.Locations("all"))
    default:
        panic("must not happen")
    }
}

Documentation

Overview

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

Index

Examples

Constants

View Source
const (
	DateFormat     = "2006-01-02"
	TimeFormat     = "15:04:05"
	DateTimeFormat = "2006-01-02 15:04:05"
)

Variables

View Source
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")
)
View Source
var (
	USER_DIR    string
	GLOBAL_DIRS string // colon separated list to look for
	WORKING_DIR string
	CONFIG_EXT  = ".conf"
	ENV         []string
	ARGS        []string
)
View Source
var (
	NameRegExp      = regexp.MustCompile("^[a-z][a-z0-9]+$")
	VersionRegexp   = regexp.MustCompile("^[a-z0-9-.]+$")
	ShortflagRegexp = regexp.MustCompile("^[a-z]$")
)

Functions

func Default

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

func Required

func Required(o *Option)

func Shortflag

func Shortflag(s rune) func(*Option)

func ValidateName

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

func ValidateShortflag(shortflag string) error

func ValidateType

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

func ValidateVersion(version string) error

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 MustNew

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

MustNew calls New() and panics on errors

func New

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

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

CurrentSub returns the active command

func (*Config) Binary

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

Binary returns the path to the binary of the app

func (*Config) CheckMissing

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

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

func (c *Config) CommmandName() string

func (*Config) EachSpec

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

func (*Config) EachValue

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

func (*Config) FirstGlobalsFile

func (c *Config) FirstGlobalsFile() string

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

func (Config) GetBool

func (c Config) GetBool(option string) bool

GetBool returns the value of the option as bool

func (Config) GetFloat32

func (c Config) GetFloat32(option string) float32

GetFloat32 returns the value of the option as float32

func (Config) GetInt32

func (c Config) GetInt32(option string) int32

GetInt32 returns the value of the option as int32

func (Config) GetJSON

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

GetJSON unmarshals the value of the option to val.

func (Config) GetString

func (c Config) GetString(option string) string

GetString returns the value of the option as string

func (Config) GetTime

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

GetTime returns the value of the option as time

func (Config) GetValue

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

GetValue returns the value of the option

func (*Config) IsOption

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

IsOption returns true, if the given option is allowed

func (Config) IsSet

func (c Config) IsSet(option string) bool

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

func (*Config) Load

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

func (*Config) LoadDefaults

func (c *Config) LoadDefaults()

func (*Config) LoadFile

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

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

func (c *Config) LoadLocals() error

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

func (*Config) LoadUser

func (c *Config) LoadUser() error

LoadUser loads the user specific config file

func (*Config) LocalFile

func (c *Config) LocalFile() string

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

func (*Config) Locations

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

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

MarshalJSON serializes the spec to JSON

func (*Config) Merge

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

func (*Config) MergeArgs

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

func (c *Config) MergeEnv() error

func (*Config) MustCommand

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

MustSub calls Sub() and panics on errors

func (*Config) MustNewOption

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

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) NewOption

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

adds a new option

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) Relax

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

func (*Config) Reset

func (c *Config) Reset()

Reset cleans the values, the locations and any current subcommand

func (*Config) Run

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

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

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

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

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

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

func (*Config) SetLocalOptions

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

func (*Config) SetUserOptions

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

func (*Config) Skip

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

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

UnmarshalJSON deserializes the spec from JSON

func (*Config) Usage

func (c *Config) Usage() string

func (*Config) UserFile

func (c *Config) UserFile() string

UserFile returns the user defined config file path

func (*Config) ValidateValues

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

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

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

type InvalidConfig struct {
	Version string
	Err     error
}

func (InvalidConfig) Error

func (e InvalidConfig) Error() string

type InvalidConfigEnv

type InvalidConfigEnv struct {
	Version string
	EnvKey  string
	Err     error
}

func (InvalidConfigEnv) Error

func (e InvalidConfigEnv) Error() string

type InvalidConfigFileError

type InvalidConfigFileError struct {
	ConfigFile string
	Version    string
	Err        error
}

func (InvalidConfigFileError) Error

func (e InvalidConfigFileError) Error() string

type InvalidConfigFlag

type InvalidConfigFlag struct {
	Version string
	Flag    string
	Err     error
}

func (InvalidConfigFlag) Error

func (e InvalidConfigFlag) Error() string

type InvalidDefault

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

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 string
	Type   string
}

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

type MissingOptionError struct {
	Version string
	Option  string
}

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

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

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

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

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

type UnknownOptionError struct {
	Version string
	Option  string
}

func (UnknownOptionError) Error

func (e UnknownOptionError) Error() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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