env

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2020 License: MIT Imports: 10 Imported by: 0

README


go-env

Struct-based environment parsing for Go


Declare command line envuments for your program by defining a struct.

var envs struct {
	Foo string
	Bar bool
}
env.MustParse(&envs)
fmt.Println(envs.Foo, envs.Bar)
$ foo=hello bar=true ./example
hello true

Installation

go get github.com/Alex616/go-env

Required environments

var envs struct {
	ID      int `env:"required"`
	Timeout time.Duration
}
env.MustParse(&envs)
$ ./example
error: id is required

Help strings

var envs struct {
	Input    string
	Output   []string
	Dataset  string   `help:"dataset to use"`
	Optimize int      `help:"optimization level"`
}
p, _ := env.MustParse(&envs)
fmt.Fprintln(p.Help())
$ ./example
Environments:
  dataset    dataset to use
  optimize   optimization level

Default values

var envs struct {
	Foo string `default:"abc"`
	Bar bool
}
env.MustParse(&envs)
var envs struct {
	Foo string
	Bar bool
}
env.Foo = "abc"
env.MustParse(&envs)

Environments with multiple values

var envs struct {
	Database string
	IDs      []int64
}
env.MustParse(&envs)
fmt.Printf("Fetching the following IDs from %s: %q", envs.Database, envs.IDs)
database=foo ids=1,2,3 ./example
Fetching the following IDs from foo: [1 2 3]

Overriding option names

var envs struct {
	Short         string  `env:"name:s"`
	Long          string  `env:"name:custom-long-option"`
	ShortAndLong  string  `env:"name:my-option"`
}
env.MustParse(&envs)
$ ./example

Environments:
  short
  custom-long-option
  my-option

Embedded structs

The fields of embedded structs are treated just like regular fields:


type DatabaseOptions struct {
	Host     string
	Username string
	Password string
}

type LogOptions struct {
	LogFile string
	Verbose bool
}

func main() {
	var envs struct {
		DatabaseOptions
		LogOptions
	}
	env.MustParse(&envs)
}

As usual, any field tagged with env:"-" is ignored.

Custom parsing

Implement encoding.TextUnmarshaler to define your own parsing logic.

// Accepts command line envuments of the form "head.tail"
type NameDotName struct {
	Head, Tail string
}

func (n *NameDotName) UnmarshalText(b []byte) error {
	s := string(b)
	pos := strings.Index(s, ".")
	if pos == -1 {
		return fmt.Errorf("missing period in %s", s)
	}
	n.Head = s[:pos]
	n.Tail = s[pos+1:]
	return nil
}

func main() {
	var envs struct {
		Name NameDotName
	}
	env.MustParse(&envs)
	fmt.Printf("%#v\n", envs.Name)
}
$ name=foo.bar ./example
main.NameDotName{Head:"foo", Tail:"bar"}

$ name=oops ./example
error: error processing name: missing period in "oops"

Custom parsing with default values

Implement encoding.TextMarshaler to define your own default value strings:

// Accepts command line envuments of the form "head.tail"
type NameDotName struct {
	Head, Tail string
}

func (n *NameDotName) UnmarshalText(b []byte) error {
	// same as previous example
}

// this is only needed if you want to display a default value in the usage string
func (n *NameDotName) MarshalText() ([]byte, error) {
	return []byte(fmt.Sprintf("%s.%s", n.Head, n.Tail)), nil
}

func main() {
	var envs struct {
		Name NameDotName `default:"file.txt"`
	}
	env.MustParse(&envs)
	fmt.Printf("%#v\n", envs.Name)
}
$ ./example
main.NameDotName{Head:"file", Tail:"txt"}

Description strings

type envs struct {
	Foo string
}

func (envs) Description() string {
	return "this program does this and that"
}

func main() {
	var envs envs
	p, _ := env.MustParse(&envs)
	fmt.Fprintln(p.Help())
}
$ ./example
this program does this and that

Environments:
  foo FOO

Documentation

Overview

Package env parses environments using the fields from a struct.

For example,

var envs struct {
	Iter int
	Debug bool
}
env.MustParse(&envs)

defines two environments, which can be set using any of

iter=1 debug=true ./example  // debug is a boolean flag so its value is set to true

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrorFieldIsNotWritable field is not writable.
	ErrorFieldIsNotWritable = errors.New("field is not writable")
	// ErrorFieldIsRequired field is required.
	ErrorFieldIsRequired = errors.New("field is required")
	// ErrorNotPointers source is not pointers.
	ErrorNotPointers = errors.New("must be pointers")
	// ErrorNotStruct source is not structs.
	ErrorNotStruct = errors.New("must be structs")
	// ErrorRequiredWithDefault error when required used with default value.
	ErrorRequiredWithDefault = errors.New("'required' cannot be used when a default value is specified")
	// ErrorUnrecognizedTag unrecognized tag.
	ErrorUnrecognizedTag = errors.New("unrecognized tag")
	// ErrorFieldsAreNotSupported fields are not supported.
	ErrorFieldsAreNotSupported = errors.New("fields are not supported")
	// ErrorDefaultValueForSlice default value for slice are not supported.
	ErrorDefaultValueForSlice = errors.New("default values are not supported for slice fields")
)

Functions

func Parse

func Parse(dest ...interface{}) error

Parse processes command line arguments and stores them in dest.

Types

type Config

type Config struct{}

Config represents configuration options for an argument parser.

type Described

type Described interface {
	// Description returns the string that will be printed on a line by itself
	// at the top of the help message.
	Description() string
}

Described is the interface that the destination struct should implement to make a description string appear at the top of the help message.

type Parser

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

Parser represents a set of command line options with destination values.

func MustParse

func MustParse(dest ...interface{}) (*Parser, error)

MustParse processes command line arguments and exits upon failure.

func NewParser

func NewParser(config Config, dests ...interface{}) (*Parser, error)

NewParser constructs a parser from a list of destination structs.

func (*Parser) Help

func (p *Parser) Help() string

Help writes the usage string followed by the full help string for each option.

func (*Parser) Parse

func (p *Parser) Parse() error

Parse processes the given command line option, storing the results in the field of the structs from which NewParser was constructed.

Jump to

Keyboard shortcuts

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