act

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2023 License: Apache-2.0, MIT Imports: 11 Imported by: 2

README

act

Microservices oriented 12-factor Go library for parsing environment variables and command line flags to arbitrary config struct using struct tags to define default values and to override flag names and environment variables' names.

Build Status Go Coverage Go Reference Go Report

This package in intended to be used to parse command line arguments and environment variables into an arbitrary config struct. This struct may contain multiple nested structs, they all will be processed recursively. Names of the flags and environment variables are automatically generated. Flags will be kebab case of the field name eventually preceded by parent fields in case of nested structs. Names of environment variables will be similar, but additionally prefixed with command name and then snake and upper cased. Description of each flag will also be automatically generated in a human friendly way as much as possible. Additionally, you may override these auto-generated names using the struct tags and you also may define default value.

  • flag - override generated flag name
  • env - override generated environment variable name
  • help - override generated flag description
  • def - override default (zero) value

Important: all struct fields should be exported.

Custom flag types

Besides the types supported by flag package, this package provides additional types:

  • act.StringSlice - doesn't support multiple flags but instead supports comma separated strings, i.e. "foo,bar"
  • act.IntSlice - doesn't support multiple flags but instead supports comma separated integers, i.e. "5,-8,0"
  • act.URL
  • act.Time - RFC3339 time

Order of precedence:

  • command line options
  • environment variables
  • default values

Examples

Run make test-verbose to see examples output.

Subcommands

These are handled just like by standard library's flag package.

package main

import (
	"log"
	"os"

	"go.ectobit.com/act"
)

func main() {
	subCmd := os.Args[1]
	switch subCmd {
	case "create":
		config := &struct{}{}
		createCmd := act.New("create")

		if err := createCmd.Parse(config, os.Args[2:]); err != nil {
			log.Println(err)
		}

		// Implementation

	case "delete":
		config := &struct{}{}
		deleteCmd := act.New("create")

		if err := deleteCmd.Parse(config, os.Args[2:]); err != nil {
			log.Println(err)
		}

		// Implementation
	}
}

TODO

  • support req struct tag to mark required values

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Documentation

Overview

Package act is a library for parsing command line flags, environment variables and default values defined by struct tag "def" respecting the order of precedence according to the 12-factor principles. It generates predefined flag names and environment variables names by the fields path of the supplied config, but allows this to be overridden by struct tags "flag" and "env".

Example (Advanced)
package main

import (
	"flag"
	"log"
	"time"

	"go.ectobit.com/act"
)

func main() {
	type config struct {
		Env   string `help:"environment [development|production]" def:"development"`
		Port  uint   `def:"3000"`
		Mongo struct {
			Hosts             act.StringSlice `def:"mongo"`
			ConnectionTimeout time.Duration   `def:"10s"`
			ReplicaSet        string
			MaxPoolSize       uint64 `def:"100"`
			TLS               bool
			Username          string
			Password          string
			Database          string `def:"cool"`
		}
		JWT struct {
			Secret                 string
			TokenExpiration        time.Duration `def:"24h"`
			RefreshTokenExpiration time.Duration `def:"168h"`
		}
		AWS struct {
			Region string `def:"eu-central-1"`
		}
		Start act.Time `def:"2002-10-02T10:00:00-05:00"`
	}

	cfg := &config{} //nolint:exhaustruct

	cmd := act.New("cool", act.WithErrorHandling(flag.ContinueOnError))

	if err := cmd.Parse(cfg, []string{"-h"}); err != nil {
		log.Println(err)
	}

}
Output:

Example (Basic)
package main

import (
	"flag"
	"log"

	"go.ectobit.com/act"
)

func main() {
	type config struct {
		Host string
		Port int
		DB   struct {
			Kind     string
			Postgres struct {
				Host string
			}
			Mongo struct {
				Host act.StringSlice
			}
		}
		Start act.Time
	}

	cfg := &config{} //nolint:exhaustruct

	cmd := act.New("mycmd", act.WithErrorHandling(flag.ContinueOnError))

	if err := cmd.Parse(cfg, []string{"-h"}); err != nil {
		log.Println(err)
	}

}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidConfigType = errors.New("invalid config type")
	ErrUnsupportedType   = errors.New("type not supported")
)

Errors.

Functions

This section is empty.

Types

type Act

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

Act is an abstraction of a CLI command.

func New

func New(name string, opts ...Option) *Act

New creates new act command.

func (*Act) Parse

func (a *Act) Parse(config interface{}, flags []string) error

Parse parses command line flags, environment variables and default values. It populates supplied pointer to configuration struct with values according to the order of precedence.

type IntSlice

type IntSlice []int

IntSlice implements flag.Getter interface for []int type.

func (*IntSlice) Get

func (f *IntSlice) Get() interface{}

Get returns flag's value.

func (*IntSlice) Set

func (f *IntSlice) Set(s string) error

Set sets flag's value by splitting provided comma separated string.

func (*IntSlice) String

func (f *IntSlice) String() string

String formats flag's value.

type Option

type Option func(a *Act)

Option defines optional parameters to the constructor.

func WithErrorHandling

func WithErrorHandling(errorHandling flag.ErrorHandling) Option

WithErrorHandling is an option to change error handling similar to flag package.

func WithLookupEnvFunc

func WithLookupEnvFunc(fn func(string) (string, bool)) Option

WithLookupEnvFunc may be used to override default os.LookupEnv function to read environment variables values.

func WithOutput

func WithOutput(w io.Writer) Option

WithOutput is an option to change the output writer similar as flag.SetOutput does.

func WithUsage added in v0.2.0

func WithUsage(parentCmdName string) Option

WithUsage allows to prefix your command name with a parent command name.

type StringSlice

type StringSlice []string

StringSlice implements flag.Getter interface for []string type.

func (*StringSlice) Get

func (f *StringSlice) Get() interface{}

Get returns flag's value.

func (*StringSlice) Set

func (f *StringSlice) Set(s string) error

Set sets flag's value by splitting provided comma separated string.

func (*StringSlice) String

func (f *StringSlice) String() string

String formats flag's value.

type Time added in v0.2.2

type Time struct {
	*time.Time
}

Time implements flag.Getter interface for time.Time type.

func (*Time) Get added in v0.2.2

func (f *Time) Get() interface{}

Get returns flag's value.

func (*Time) Set added in v0.2.2

func (f *Time) Set(s string) error

Set sets flag's value by parsing provided url.

func (*Time) String added in v0.2.2

func (f *Time) String() string

String formats flag's value.

type URL

type URL struct {
	*url.URL
}

URL implements flag.Getter interface for url.URL type.

func (*URL) Get

func (f *URL) Get() interface{}

Get returns flag's value.

func (*URL) Set

func (f *URL) Set(s string) error

Set sets flag's value by parsing provided url.

func (*URL) String

func (f *URL) String() string

String formats flag's value.

Jump to

Keyboard shortcuts

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