config

package module
v0.0.0-...-57ab79d Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2016 License: MIT Imports: 10 Imported by: 0

README

go-config

travis-ci status for jimmysawczuk/go-config GoDoc Go Report Card

go-config is a configuration library for Go that can process configuration from the source code itself, config files, and the command line.

Usage

Example

Here's some simple usage of go-config in action:

package main

import (
	"fmt"
	"github.com/jimmysawczuk/go-config"
	"math"
)

func main() {
	// Set up the app information for the --help output
	config.Name = "config-test"
	config.Version = "1.0.0"
	config.Description = "Takes two arguments and does an operation on them"

	config.Examples = []config.Example{
		{
			Cmd:         `config-tester -addend.a=1 -addend-b=2`,
			Description: "Adds 1 and 2, returns 3",
		},

		{
			Cmd:         `config-tester -addend.a=3 -addend-b=2 -subtract`,
			Description: "Subtracts 2 from 3, returns 1",
		},
	}

	var res float64

	// Add the variables, store the options as variables for later
	a := config.Add(config.Int("addend.a", 10, "The first addend").Exportable(true))
	b := config.Add(config.Float("addend.b", math.Pi, "The second addend").Exportable(true))
	sub := config.Add(config.Bool("subtract", false, "Subtract instead of add").Exportable(true))

	// Build the config
	err := config.Build()
	if err != nil {
		fmt.Println(err.Error())
	}

	// Calculate the result
	res = op(float64(a.Int()), b.Float(), sub.Bool())

	fmt.Println("From the stored variables")
	fmt.Println(a.Int(), b.Float(), sub.Bool())
	fmt.Println(res)

	// You can also get the config values on demand
	addend_a := float64(config.Require("addend.a").Int())
	addend_b := float64(config.Require("addend.b").Float())
	subtract := config.Require("subtract").Bool()

	res = op(addend_a, addend_b, subtract)

	fmt.Println("------")
	fmt.Println("From the on demand lookup")
	fmt.Println(addend_a, addend_b, sub)
	fmt.Println(res)

}

func op(a, b float64, subtract bool) (r float64) {
	if !subtract {
		r = a + b
	} else {
		r = a - b
	}
	return r
}

The above program produces the following output:

$ config-test
From the stored variables
10 3.141592653589793 false
13.141592653589793
------
From the on demand lookup
10 3.141592653589793 false
13.141592653589793

You can override individual config values using flags:

$ config-test --help
config-test (ver. 1.0.0)
Takes two arguments and does an operation on them

Examples:
 # Adds 1 and 2, returns 3
 $ config-test -addend.a=1 -addend-b=2

 # Subtracts 2 from 3, returns 1
 $ config-test -addend.a=3 -addend-b=2 -subtract

Flags:
 -addend.a       (default: 10)
     The first addend

 -addend.b       (default: 3.141592653589793)
     The second addend

 -subtract       (default: false)
     Subtract instead of add


 -config-debug   (default: false)
     Show the files/scopes that are parsed and which scope each config value comes from

 -config-file    (default: <empty>)
     A filename of an additional config file to use


 -config-partial (default: false)
     Export a partial copy of the configuration, only what is explicitly passed in via flags

 -config-save    (default: false)
     Export the configuration to the specified scope

 -config-scope   (default: <empty>)
     The scope that'll be written to

 -config-write   (default: false)
     Export the configuration to the specified scope, then exit

Automatic config file generation

Config files can be saved as JSON files. go-config supports parsing multiple config files and in the event of two files having different values for one option, takes the most recently parsed option. The default order in which config files and arguments are parsed is:

  1. $HOME/.<program-name>/config.json (the user's home directory) (scope: "user")
  2. ./config.json (the working directory) (scope: "app")
  3. A config file specified via the -config-file flag (optional) (scope: "custom")
  4. Any flags specified on the command line at runtime (scope: "flag")

You can automatically write a config file by specifying -config-scope (see the list above), a -config-file if necessary, and either -config-save (which continues execution of the program after saving the config file) or -config-write (which terminates the program after writing). By default, this will write all of the exportable options to the specified file, but you can specify -config-partial to only write the config values specified by flag (and not the rest of the exportable options).

More documentation

More documentation is available via GoDoc.

License

go-config is released under the MIT license.

Documentation

Index

Constants

View Source
const (
	BoolType   Type = "bool"
	StringType      = "string"
	FloatType       = "float64"
	IntType         = "int64"
	CustomType      = "custom"
)

These Types constants parallel their standard counterparts, and are the four elementary types that come when unmarshaling JSON

Variables

View Source
var DefaultOptionMeta = OptionMeta{
	Exportable: false,
	Validate:   true,
	Filters:    []OptionFilterFunc{},
	SortOrder:  0,
}

DefaultOptionMeta returns the default OptionMeta object

View Source
var Description string

Description describes the application you're configuring.

View Source
var Examples = []Example{}

Examples contains a list of example commands and what they do.

View Source
var Name = os.Args[0]

Name is the name of the application you're configuring.

View Source
var SearchFiles = []SearchFile{
	{
		Scope: "app",
		Path:  "./config.json",
	},
	{
		Scope: "user",
		Path:  "$HOME/." + strings.ToLower(Name) + "/config.json",
	},
}

SearchFiles contains a list of files which may or may not exist, and if they do, contain configuration files. The last entry in this list is parsed first, and its values are overwritten by values in files further up the list.

View Source
var UsageWriter io.Writer = os.Stdout

UsageWriter is the io.Writer to use for outputting Usage(). Defaults to stdout.

View Source
var Version string

Version is the version of the application you're configuring.

Functions

func Build

func Build() error

Build builds the configuration object. Starts by setting the default values as defined in code, then parses the config file, then loads the overridden options from flag. If set, this also exports the as-run configuration to the the filename set in the "config" option.

func Usage

func Usage()

Usage prints the help information to UsageWriter (defaults to stdout).

Types

type Example

type Example struct {
	Cmd         string
	Description string
}

Example describes an example of a proper way to invoke the current Go program.

type FileIO

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

FileIO implements IO and writes to the filesystem

func (FileIO) Read

func (f FileIO) Read() (err error)

func (FileIO) Scope

func (f FileIO) Scope() string

Scope returns the scope of the file

func (FileIO) Write

func (f FileIO) Write() (err error)

type FlagSet

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

A FlagSet is a set of Flags from the command-line

func NewFlagSet

func NewFlagSet(name string, args []string) (f FlagSet)

NewFlagSet instanciates a new FlagSet with an executable named `name` and OS args `args`.

func (FlagSet) HasHelpFlag

func (f FlagSet) HasHelpFlag() bool

HasHelpFlag returns true if the FlagSet's args contains '-h', '-help' or something similar.

func (*FlagSet) Parse

func (f *FlagSet) Parse() error

Parse parses all the flags in the FlagSet

func (*FlagSet) ParseBuiltIn

func (f *FlagSet) ParseBuiltIn() error

ParseBuiltIn parses only the built-in flags in the FlagSet (config, config-export, config-generate)

func (FlagSet) Release

func (f FlagSet) Release() []string

Release returns the unparsed arguments and flags so they can be picked up by another library if needed (like the built-in flag package).

type IO

type IO interface {
	Read() error
	Write() error
	Scope() string
}

IO defines an interface that allows reading and writing of OptionSets to external storage

type IOError

type IOError struct {
	Type string
	Path string
	// contains filtered or unexported fields
}

IOError describes an error related to loading a config file.

func (IOError) Error

func (e IOError) Error() string

type Option

type Option struct {
	// The name of the option is what's used to reference the option and its value during the program
	Name string

	// What the option is for. This also shows up when invoking `program --help`.
	Description string

	// Holds the actual value contained by this option
	Value interface{}

	// Holds the default value for this option
	DefaultValue interface{}

	// Holds the type of this option
	Type Type

	// Extra options
	Options OptionMeta
	// contains filtered or unexported fields
}

Option holds information for a configuration option

func Add

func Add(o *Option) *Option

Add adds an Option to the config's OptionSet

func Bool

func Bool(name string, defaultValue bool, description string) *Option

Bool creates an Option with the parameters given of type bool

func Enum

func Enum(name string, possibleValues []string, defaultValue string, description string) *Option

Enum creates an Option with the parameters given of type string and a built-in validation to make sure that the parsed Option value is contained within the possibleValues argument.

func Float

func Float(name string, defaultValue float64, description string) *Option

Float creates an Option with the parameters given of type float64

func Get

func Get(key string) (*Option, error)

Get looks for an Option with the name of `key`. If no Option is found, this function returns an error.

func Int

func Int(name string, defaultValue int64, description string) *Option

Int creates an Option with the parameters given of type int64

func Require

func Require(key string) *Option

Require looks for an Option with the name of `key`. If no Option is found, this function panics.

func Str

func Str(name string, defaultValue string, description string) *Option

Str creates an Option with the parameters given of type string

func (*Option) AddFilter

func (o *Option) AddFilter(v OptionFilterFunc) *Option

AddFilter adds an OptionFilterFunc to the Option's filter set. It also sets Validate to true.

func (*Option) AddScope

func (o *Option) AddScope(s string)

AddScope adds a scope to an Option indicating that it was parsed in a file with the given scope.

func (Option) Bool

func (o Option) Bool() bool

Bool returns the bool value of the option. Will panic if the Option's type is not a bool.

func (Option) DebugString

func (o Option) DebugString() string

DebugString returns a string describing some attributes about the Option, including the name, value, type and what scopes it came from.

func (Option) DefaultValueString

func (o Option) DefaultValueString() string

DefaultValueString returns the Option's default value as a string.

func (*Option) Exportable

func (o *Option) Exportable(v bool) *Option

Exportable sets whether or not the Option is exportable to a config file.

func (Option) Float

func (o Option) Float() float64

Float returns the float64 value of the option. Will panic if the Option's type is not a float64.

func (*Option) HasScope

func (o *Option) HasScope(s string) bool

HasScope returns true if the Option has the specified scope.

func (Option) Int

func (o Option) Int() int64

Int returns the int64 value of the option. Will panic if the Option's type not an int64.

func (*Option) SetFromFlagValue

func (o *Option) SetFromFlagValue(val string) (err error)

SetFromFlagValue attempts to set the Option's value as its proper type by parsing the string argument, and also sets a hidden value on the Option indicating it was overridden by a flag argument.

func (*Option) SetFromString

func (o *Option) SetFromString(val string) (err error)

SetFromString attempts to set the Option's value as its proper type by parsing the string argument

func (*Option) SortOrder

func (o *Option) SortOrder(i int) *Option

SortOrder sets the sort order on the Option used in Usage().

func (Option) Str

func (o Option) Str() string

Str returns the string value of the option. Will panic if the Option's type is not a string.

func (Option) String

func (o Option) String() string

String implements fmt.Stringer. This is used for printing the OptionSet if needed; you should use Str() to return the string value of a string Option, as it'll return what you expect all the time.

func (*Option) Validate

func (o *Option) Validate(v bool) *Option

Validate sets whether or not the Filters on the Option will be tested for validity before being accepted.

type OptionFilterFunc

type OptionFilterFunc func(*Option) (bool, error)

OptionFilterFunc is a function type that takes an *Option as a parameter. It returns true, nil if the *Option passes the filter, and false, error with a reason why if it didn't.

func IsOneOfStrings

func IsOneOfStrings(possibleValues []string) OptionFilterFunc

IsOneOfStrings returns an OptionFilterFunc that checks the Option value against a list of string values and returns true if the Option value matches one of the possible values

func NonEmptyString

func NonEmptyString() OptionFilterFunc

NonEmptyString returns an OptionFilterFunc that returns true if the Option value is a non-empty string. It will also return false if the Option is not a string.

type OptionMeta

type OptionMeta struct {
	// Exportable is true if the option is exportable to a config.json file
	Exportable bool

	// Validate is true if the option is required
	Validate bool

	// Filters is a set of boolean functions that are tested with the given value. If Validate is true, all of these must succeed.
	Filters []OptionFilterFunc

	// SortOrder controls the sort order of Options when displayed in Usage(). Defaults to 0; ties are resolved alphabetically.
	SortOrder int
}

OptionMeta holds information for configuring options on Options

type OptionSet

type OptionSet map[string]*Option

An OptionSet is map of Options, keyed by the Options' Names.

func (OptionSet) Add

func (os OptionSet) Add(o *Option)

Add adds an Option to an OptionSet with a key of the Option's name.

func (OptionSet) Export

func (os OptionSet) Export(includeNonExportable bool, includeNonOverrides bool) map[string]interface{}

Export returns a map that's suitable for pushing into a config.json file.

func (OptionSet) Get

func (os OptionSet) Get(key string) (*Option, bool)

Get retrieves an Option with the Name of key, and a boolean to determine if it was found or not.

func (OptionSet) Require

func (os OptionSet) Require(key string) *Option

Require retrieves an Option with the Name of key. Panics if there was no key found.

func (OptionSet) Validate

func (os OptionSet) Validate() error

Validate checks all Options in an OptionSet and returns an error if any of them don't pass any of their Filters and are Required.

type SearchFile

type SearchFile struct {
	Scope string
	Path  string
}

SearchFile contains a potential config file path and a scope relating to where that file is stored.

func (SearchFile) ExpandedPath

func (f SearchFile) ExpandedPath() string

ExpandedPath returns the SearchFile's path expanded with environment variables.

type Type

type Type string

Type is a string representing the type of data stored by an Option

Jump to

Keyboard shortcuts

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