cfg

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2024 License: MIT Imports: 16 Imported by: 19

Documentation

Overview

Package cfg provides facilities to ingest structs as configuration elements via reflection. Struct names must be exported. Beyond that recursive structs are supported with options prefixing with the outermost struct name. Name overrides via struct tags can be used to rename configuration options as well as (optionally) set defaults.

Configurations share these options

 - A configuration is one or more struct pointers
 - Each struct member's data type is used for type conversion during assignment
 - Primitive types are evaluated directly
 - Aggregate slice can be set with comma delibmited syntax
 - Aggregate map can be set with comma delibmited syntax

 map example
 Map  map[string]float64 `short:"m" default:"π:3.14159,ξ:1,ρ:.01,φ:1.2,β:3,α:.01,δ:3,ε:.001,φ:.1,ψ:.9,ω:2.1"`

 - Decorate

Modes of configuration

  • Wrap(prefix, ptrs...) options with a prefix argument to each flag or environment variable
  • Nest(ptrs...) each struct member with the name of the the parent struct(s)
  • Unwrap( ptr ... interface{} ) error
  • Flags and Env Vars are unwrapped - no prefix or argument name added
  • Call with one or more structures with uniquely named members
  • One flag + env variable for each entry named
  • When called with duplicate members in one or more structs flags and env vars will conflict and error

Index

Constants

This section is empty.

Variables

View Source
var (
	Info  = Teal
	Warn  = Yellow
	Fatal = Red
	Pass  = Green
	Fail  = Red
)
View Source
var (
	Black   = Color("\033[1;30m%s\033[0m")
	Red     = Color("\033[1;31m%s\033[0m")
	Green   = Color("\033[1;32m%s\033[0m")
	Yellow  = Color("\033[1;33m%s\033[0m")
	Purple  = Color("\033[1;34m%s\033[0m")
	Magenta = Color("\033[1;35m%s\033[0m")
	Teal    = Color("\033[1;36m%s\033[0m")
	White   = Color("\033[1;37m%s\033[0m")
)
View Source
var ErrIgnoreTag = errors.New("this Tag isn't in use")
View Source
var ErrInvalidArgMapParseSpec = errors.New("map argument requires pairs")
View Source
var ErrInvalidArgPointerRequired = fmt.Errorf("%s: requires one or more struct pointer arguments", Package)
View Source
var ErrInvalidArgStructPointerRequired = errors.New("Argument must be a struct pointer")
View Source
var ErrInvalidSpecification = errors.New("specification must be a struct pointer")
View Source
var ErrorHandlerModel = eflag.ContinueOnError

ErrorHandlerModel enables reconfiguring eflag.ErrorHandling for the flag handlers

View Source
var LookupEnv = syscall.Getenv
View Source
var Package = func() string {
	type Empty struct{}
	return reflect.TypeOf(Empty{}).PkgPath()
}()
View Source
var PrefixOverrideText = `` /* 490-byte string literal not displayed */
View Source
var Store = NewStor()

Store persistable representation

View Source
var Usage = func() {
	var parts = strings.Split(os.Args[0], "/")
	var l = len(parts)
	var Program = parts[l-1]
	fmt.Fprintf(os.Stderr, "\nUsage of %s:\n", Program)
	if len(helpText) > 0 {
		fmt.Fprintf(os.Stderr, "\n%s\n\n", helpText)
	}

	eflag.PrintDefaults()

}

Usage add usage text for flags/help processing

Functions

func Add

func Add(ptrs ...interface{}) error

Add alias of Eval

func Bare

func Bare(ptrs ...interface{}) error

Bare alias of Simple create env vars without prefices

func Caller

func Caller() string

Caller get the calling frame info

func Capitalize

func Capitalize(text string) string

Capitalize text

func CheckArgs

func CheckArgs(ptrs ...interface{}) error

CheckArgs validate that the pointers are pointers to struct

func Color added in v1.2.12

func Color(colorString string) func(...interface{}) string

Color returns a function that configures a scoped string colorizor

func Copy

func Copy(config interface{})

Copy from the internal store to the config object interface{}

func CopyOut

func CopyOut(in, out interface{}) error

CopyOut serializes and deseiralizes an object to copy it out of an object

func Debug

func Debug(args ...bool)

Debug set the debug test var to true

func Decorate

func Decorate() bool

Decorate structs with prefix

func DeepCopyInto

func DeepCopyInto(src Stor, dst map[string]interface{}, depthArgs ...int)

DeepCopyInto dst from source

func Downcase

func Downcase(text string) string

Downcase text

func Dump

func Dump(o interface{}) string

func Enter

func Enter(args *Arg, ptr interface{}) error

Enter recursively processes object configurations

func Eval

func Eval(ptrs ...interface{}) error

Eval one or more configuration structures

func EvalName

func EvalName(name string, ptrs ...interface{}) error

EvalName one or more configuration structures overriding the name

func Final

func Final()

Final freezes calling flag.Parse, no more additions to the configuration after Final

func FlagInit

func FlagInit()

FlagInit flags

func Flags

func Flags(ptrs ...interface{}) error

Flags alias of Eval

func Freeze

func Freeze()

Freeze flags

func HelpText

func HelpText(text string)

HelpText pre write text for help

func Init

func Init(ptrs ...interface{}) error

Init from a list of struct pointers

func IsMap

func IsMap(config interface{}) bool

func IsSet

func IsSet(name string) bool

IsSet returns if the flag has been set

func IsStructPtr

func IsStructPtr(config interface{}) bool

func Nest

func Nest(ptrs ...interface{}) error

func NestWrap

func NestWrap(prefix string, ptrs ...interface{}) error

NestWrap objects retaining object hierarchy with prefix

func Ok

func Ok(name string) bool

Ok returns if the flag has been set

func ParseStruct

func ParseStruct(args *Arg, ptr interface{}, prefix string, structField reflect.StructField) error

ParseStruct recursively processes object configurations

func RemovePkg

func RemovePkg(pkg string) string

RemovePkg from a type name

func Reprefix added in v1.5.0

func Reprefix(name string, ptrs ...interface{}) error

Reprefix replacing object name as prefix with name

func Required

func Required(name string) bool

Required returns if the flag has been set

func Reset added in v1.4.1

func Reset(name string)

Reset from frozen and enable re-evaluation with ErrorHandlerModel

func Run

func Run(args *Arg, ptrs ...interface{}) error

func Simple

func Simple(ptrs ...interface{}) error

Simple create env vars prefices

func SimpleFlags

func SimpleFlags(ptrs ...interface{}) error

SimpleFlags create env vars and flags without prefices

func Thaw added in v1.4.1

func Thaw()

Thaw flags

func ToCamelCase added in v1.2.12

func ToCamelCase(str string) string

ToCamelCase from either case test. Doesn't attempt to identify acronyms for text replacement; e.g. json_map isn't converted to JSONMap, instead this capitalizes the first letter of each snake or kebob cast subexpression: json-map and json_map wil both convert to JsonMap.

func ToLowerKebabCase

func ToLowerKebabCase(str string) string

ToLowerKebabCase lower kebab (hyphen case) case splitting from CamelCase hyphenating and lower casing camel-case

func ToLowerSnakeCase

func ToLowerSnakeCase(str string) string

ToLowerSnakeCase lower case after snake casing string splitting CamelCase separating with '_' underscores

func ToUpperKebabCase

func ToUpperKebabCase(str string) string

ToUpperKebabCase upper kebab (hyphen case) case splitting from CamelCase hyphenating and upper casing CAMEL-CASE

func ToUpperSnakeCase

func ToUpperSnakeCase(str string) string

ToUpperSnakeCase upper case after snake casing string splitting CamelCase separating with '_' underscores

func Type

func Type(config interface{}) string

func Undecorate

func Undecorate() bool

Undecorate structs with prefix

func Unprefix

func Unprefix()

func Unprefixed added in v1.5.0

func Unprefixed(ptrs ...interface{}) error

Unprefixed next struct names, without the object name as a prefix

func Unwrap

func Unwrap(ptrs ...interface{}) error

Unwrap alias of Simple create env vars without prefices

func Wrap

func Wrap(name string, ptrs ...interface{}) error

Wrap (optionally) with prefix and struct names create env vars without prefices

Types

type Adder

type Adder interface {
	AddStor(name string, o interface{})
}

Adder appends to configuration objects

type Arg

type Arg struct {
	Depth      int
	Prefix     string
	Prefixed   bool
	Unprefixed bool
	Reprefix   bool
	UseFlags   bool
}

Arg is the settings passed for recursion

func NewArg

func NewArg(name string) *Arg

NewArg sets values in Arg for cfg to process structs

type DeepCopier

type DeepCopier interface {
	DeepCopyInto(DeepCopier)
}

DeepCopier recurse and iterate over configuration structs internal representation Stor

type Field

type Field struct {
	reflect.StructField
	FieldPtr
	UseFlags   bool
	StructName string // The name of the current owning structure
	Name       string // from var name if tag name is present replace tag name with tag
	KeyName    string // ENV variable name prefix Prf + "_" + name CamelCase -> PRF_CAMEL_CASE
	Default    string // default from tag, empty string for default
	EnvText    string // environment text, empty string for default
	Short      string // short flag name
	Doc        string // description
	FlagName   string // Hyphenated flag name CamelCase -> camel-case
	Value      string // if env use, else if default tag use, else use type's default
	Omit       bool   // obey json:"...,omitempty" or json:"...,omit" or json:"-"
	Required   bool   // set to force field to have a value
	Depth      int    // struct nesting depth
	Ignore     bool   // don't store or load the corresponding Attribute
	Error      error
	Type       string
	Prefix     string
}

Field holds the parsed struct tag information

func (*Field) AddFlag

func (field *Field) AddFlag()

AddFlag if not created and warn if it is a duplicate

func (*Field) FlagNameFromCamelCase

func (field *Field) FlagNameFromCamelCase()

FlagNameFromCamelCase for flags CamelCase to camel-case hyphenated, split on camel case regular expression

func (*Field) Get

func (field *Field) Get(name string) string

Get a tag from the struct tags

func (*Field) KeyNameFromCamelCase

func (field *Field) KeyNameFromCamelCase()

KeyNameFromCamelCase split and upper case splitting from CamelCase hyphenating and lower casing CAMEL_CASE. If field.Prefix is set, prepend to the text for environment variables. Split via camel case regular expression.

func (*Field) SetDefault

func (field *Field) SetDefault()

SetDefault read tag default option and save the text

func (*Field) SetDoc

func (field *Field) SetDoc()

SetDoc read tag doc option and save the text

func (*Field) SetField

func (field *Field) SetField()

SetField from the struct tags, env, or interpolated values

func (*Field) SetFlagName

func (field *Field) SetFlagName()

SetFlagName read tag keyword option and save the text

func (*Field) SetIgnore

func (field *Field) SetIgnore()

SetIgnore read tag ignore option and save the text

func (*Field) SetKeyName

func (field *Field) SetKeyName()

SetKeyName read tag keyword option and save the text

func (*Field) SetName

func (field *Field) SetName()

SetName read tag name option and save the text

func (*Field) SetOmit

func (field *Field) SetOmit()

SetOmit read tag omit option and set when enabled, via ,omit ,omitempty or '-' the hyphen option

func (*Field) SetRequired

func (field *Field) SetRequired()

SetIgnore read tag required option and save the text

func (*Field) SetShort

func (field *Field) SetShort()

SetShort read tag short option and save the text

func (*Field) SetType

func (field *Field) SetType()

SetType read tag keyword option and save the text

func (*Field) SetValueFromEnv

func (field *Field) SetValueFromEnv()

SetValueFromEnv uses the value from the environment for this structure tag replacing the default tag value

func (*Field) String

func (field *Field) String() string

String formats args as yaml string

func (*Field) ToLowerKebabCase added in v1.2.12

func (field *Field) ToLowerKebabCase()

ToLowerKebabCase for flags CamelCase to camel-case hyphenated, split on camel case regular expression

type FieldPtr

type FieldPtr interface{}

FieldPtr for the struct field field

type Loader

type Loader interface {
	Load(filename string)
}

Loader reads input configuration from a store

type SFWrap

type SFWrap struct {
	reflect.StructField
}

func (*SFWrap) GetName

func (sfwrap *SFWrap) GetName() string

GetName from reflect struct field tag or struct name

type Stor

type Stor map[string]interface{}

Stor configuration representation, restorable object from, saveable to persistence.

func NewStor

func NewStor() Stor

NewStor returns a Stor object for persistence

func (Stor) AddStor

func (stor Stor) AddStor(name string, o interface{})

AddStor appends an object to a Stor persistence

func (Stor) Bytes

func (stor Stor) Bytes() []byte

String stor interfaceable

func (Stor) DeepCopyInto

func (stor Stor) DeepCopyInto(dst interface{}, depthArgs ...int)

DeepCopyInto ...

func (*Stor) Load

func (stor *Stor) Load(filename string) error

Load object from persistence

func (Stor) Save

func (stor Stor) Save(filename string) error

Save object to persistence

func (Stor) Stor

func (stor Stor) Stor(filename string) error

Stor object to persistence

func (Stor) String

func (stor Stor) String() string

String stor interfaceable

type Storer

type Storer interface {
	Store(filename string)
}

Storer writes configurations to store

Directories

Path Synopsis
cmd
app
cfg

Jump to

Keyboard shortcuts

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