confi

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2021 License: BSD-3-Clause Imports: 18 Imported by: 8

README

See the Go package documentation.

Documentation

Overview

Package confi is an ergonomic configuration parsing toolkit. The schema is declared using a struct type, and values can be read from TOML files or set via command-line flags.

A pointer to a preallocated configuration object of a user-defined struct type must be passed to all functions. The type can have an arbitrary number of nested structs (either embedded or through an initialized pointer). Only exported fields can be used. The object can be initialized with default values.

Slices of structs can be populated by appending TOML table arrays, or by indexing on the command line.

Dynamically created subtrees are supported via map[string]interface{} nodes. The map values must be struct pointers.

The field names are spelled in lower case in TOML files and on the command-line. The accessor functions and flag values use dotted paths to identify the field, such as "audio.samplerate".

Supported field types are bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, string, []string, and time.Duration.

The Get method is provided for completeness; the intended way to access configuration values is through direct struct field access.

Short example:

c := &myConfig{}

flag.Usage = confi.FlagUsage(nil, c)
flag.Var(confi.FileReader(c), "f", "read config from TOML files")
flag.Var(confi.Assigner(c), "c", "set config keys (path.to.key=value)")
flag.Parse()

Longer example:

package main

import (
	"flag"
	"fmt"
	"log"

	"import.name/confi"
)

type myConfig struct {
	Comment string

	Size struct {
		Width  uint32
		Height uint32
	}

	Audio struct {
		Enabled    bool
		SampleRate int
	}
}

func main() {
	c := new(myConfig)
	c.Size.Width = 640
	c.Size.Height = 480
	c.Audio.SampleRate = 44100

	if err := confi.ReadFileIfExists("defaults.toml", c); err != nil {
		log.Print(err)
	}

	if x, _ := confi.Get(c, "audio.samplerate"); x.(int) <= 0 {
		confi.MustSet(c, "audio.enabled", false)
	}

	dump := flag.Bool("dump", false, "create defaults.toml")
	flag.Var(confi.FileReader(c), "f", "read config from TOML files")
	flag.Var(confi.Assigner(c), "c", "set config keys (path.to.key=value)")
	flag.Usage = confi.FlagUsage(nil, c)
	flag.Parse()

	if *dump {
		if err := confi.WriteFile("defaults.toml", c); err != nil {
			log.Fatal(err)
		}
	}

	fmt.Printf("Comment is %q\n", c.Comment)
	fmt.Printf("Size is %dx%d\n", c.Size.Width, c.Size.Height)
	if c.Audio.Enabled {
		fmt.Printf("Sample rate is %d\n", c.Audio.SampleRate)
	}
}

Example usage output:

$ example -help
Usage of example:
  -c value
    	set config keys (path.to.key=value)
  -dump
    	create defaults.toml
  -f value
    	read config from TOML files

Configuration settings:
  comment string
  size.width uint32
  size.height uint32
  audio.enabled bool
  audio.samplerate int

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assign

func Assign(config interface{}, expr string) error

Assign a value to a field of the configuration object. The field's path and string representation are parsed from an expression of the form "path=repr".

See SetFromString for parsing rules.

func Assigner

func Assigner(config interface{}) flag.Value

Assigner is equivalent to FlagSetter(config, false).

func FileReader

func FileReader(config interface{}) flag.Value

FileReader is equivalent to FlagReader(config, false).

func FlagReader

func FlagReader(config interface{}, ignoreUnknown bool) flag.Value

FlagReader makes a “dynamic value” which reads files into the configuration as it receives filenames. Unknown keys are silently skipped if ignoreUnknown is true.

func FlagSetter

func FlagSetter(config interface{}, ignoreUnknown bool) flag.Value

FlagSetter makes a “dynamic value” which sets fields in the configuration as it receives assignment expressions. An error is not returned for unknown keys if ignoreUnknown is true.

func FlagUsage

func FlagUsage(flags *flag.FlagSet, config interface{}) func()

FlagUsage creates a function which may be used as flag.Usage. It includes the default usage and the configuration settings.

func Get

func Get(config interface{}, path string) (value interface{}, err error)

Get the value of a field of the configuration object.

func MustAssign

func MustAssign(config interface{}, expr string)

MustAssign is a panicking alternative to the Assign method. It panics if the field doesn't exist or parsing fails.

func MustSet

func MustSet(config interface{}, path string, value interface{})

MustSet a field of the configuration object. The value must have the same type as the field. Panic if the field doesn't exist or the types don't match.

func MustSetFromString

func MustSetFromString(config interface{}, path string, repr string)

MustSetFromString sets a field of the configuration object. The value representation is parsed according to the type of the field. Panic if the field doesn't exist or parsing fails.

See SetFromString for parsing rules.

func PrintSettings

func PrintSettings(w io.Writer, config interface{})

PrintSettings of the given configuration. Writer defaults to the default flag set's output.

func Read

func Read(r io.Reader, config interface{}) error

Read TOML into the configuration.

func ReadFile

func ReadFile(filename string, config interface{}) error

ReadFile containing TOML into the configuration.

func ReadFileIfExists

func ReadFileIfExists(filename string, config interface{}) error

ReadFileIfExists is a lenient alternative to the ReadFile method.. No error is returned if the file doesn't exist.

func Set

func Set(config interface{}, path string, value interface{}) (err error)

Set a field of the configuration object. The value must have the same type as the field.

func SetFromString

func SetFromString(config interface{}, path string, repr string) (err error)

SetFromString sets a field of the configuration object. The value representation is parsed according to the type of the field.

Valid boolean representations are "true", "false", "yes", "no", "y", "n", "on", and "off".

If the representation of a string list is the empty string, the field will be an empty list. If the representation starts with "[", it is assumed to be a JSON-encoded string array. Otherwise the length will be one, and repr will be the single item.

func Write

func Write(w io.Writer, config interface{}) error

Write the configuration as TOML.

func WriteFile

func WriteFile(filename string, config interface{}) (err error)

WriteFile containing the configuration as TOML.

Types

type Buffer

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

Buffer configuration files and assignments.

func NewBuffer

func NewBuffer(defaults ...string) *Buffer

NewBuffer with optional default absolute configuration filenames or glob patterns.

func (Buffer) Apply

func (b Buffer) Apply(config interface{}) error

Apply is equivalent to Flush(config, false).

func (*Buffer) Assigner

func (b *Buffer) Assigner() flag.Value

Assigner makes a “dynamic value” which buffers assignment expressions to be applied.

func (*Buffer) DirReader

func (b *Buffer) DirReader(pattern string) flag.Value

DirReader makes a “dynamic value” which buffers directories to read files from.

func (*Buffer) FileReader

func (b *Buffer) FileReader() flag.Value

FileReader makes a “dynamic value” which buffers file names to be read.

func (*Buffer) FileReplacer

func (b *Buffer) FileReplacer() flag.Value

FileReplacer makes a “dynamic value” which buffers file names to be read. It discards previously buffered values.

func (Buffer) Flush

func (b Buffer) Flush(config interface{}, ignoreUnknown bool) error

Flush files and assignments to the configuration. Unknown keys are silently skipped if ignoreUnknown is true.

type Setting

type Setting struct {
	Path    string
	Type    reflect.Type
	Default string
}

Setting documents a settable configuration path.

func Settings

func Settings(config interface{}) []Setting

Settings lists the settable configuration paths.

func (Setting) String

func (s Setting) String() string

Jump to

Keyboard shortcuts

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