xflag

package module
Version: v0.0.0-...-61e102d Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2016 License: BSD-2-Clause Imports: 6 Imported by: 0

README

xflag

Package xflag is a hybrid configuration library that combines Go's standard flag package, INI or other configuration files, and environment variables. Plus, provides support of slice flags.

GoDoc Build Status Windows Build Status Coverage Go Report Card

Installation

Use -u ("update") flag to make sure the latest version of package is installed.

go get -u github.com/goaltools/xflag
Basic Principles
  1. Every flag has its own default value.
  2. That default value can be overridden by INI or some other configuration file. The configuration file may contain Environment Variables, e.g. ${OPENSHIFT_PORT}.
  3. It is possible to override values of the configuration file when running your app using flags.
Usage

By default, INI configuration files are expected.

package main

import (
	"flag"

	"github.com/goaltools/xflag"
)

var (
	someFlag = flag.String("someFlag", "default value", "Description of the flag.")

	name = flag.String("name", "John Doe", "Your full name.")
	age  = flag.Int("age", 18, "Your age.")
)

func main() {
	err := xflag.Parse("/path/to/file1.ini")
	if err != nil {
		panic(err)
	}
}

The program above has default age = 18. We can override it by adding to /path/to/file1.ini:

age = 55

So, now the value is age = 55. But if we run the program above as $ main --age 99 the value will be age = 99 no matter what inside the configuration file is.

Multiple Files

Function xflag.Parse(...) may get any number of paths to INI files. E.g.:

xflag.Parse("file1.ini", "file2.ini", "file3.ini")

Every subsequent file will override values conflicting with the previous one. I.e. file3.ini has higher priority than file2.ini. And if both contain name = ..., the value from file3.ini will be used.

INI Sections

INI file may contain sections, e.g.:

[user]
name = James Bond

[database]
port = 28015

[app]
addr = https://${OPENSHIFT_HOST}:${OPENSHIFT_PORT}

Code for use of such kind of configuration file will look as follows (note the flag names):

name = flag.String("user:name", "...", "...")
port = flag.Int("database:port", 0, "...")

And the values can be overriden by running your app as $ main --user:name "Jane Roe" --database:port 8888.

Slice Flags

Standard flag package supports simple types such as string, int, etc. Package xflag/cflag brings support of complex types including slices:

var (
	names = cflag.Strings("names", []string{"John", "Joe"}, "A list of names.")
	ages  = cflag.Ints("ages", []int{16, 18}, "A list of ages.")
)

A list of related functions includes: Bools, Durations, Float64s, Ints, Int64s, Strings, Uints, Uint64s.

Your configuration file may look as follows:

names[] = Name1
names[] = Name2

ages[] = 35
ages[] = 46

And in order to pass an array of parameters using console line, repeat the same flag name multiple times:

$ ./main --names[] James --names[] Bob
Custom Configuration Format

To add support of a custom configuration format, implement the config.Interface. Then use it as follows:

package main

import (
	"os"

	"github.com/goaltools/xflag"
)

func init() {
	// Allocate a new xflag context.
	c := xflag.New(MyCustomConfig, os.Args[1:])

	// Parse the configuration files you need.
	if err := c.Files("/path/to/file1.xxx", "...", "/path/to/fileN.xxx"); err != nil {
		panic(err)
	}

	// Parse the flag set.
	if err := c.Parse(); err != nil {
		panic(err)
	}
}
License

Distributed under the BSD 2-clause "Simplified" License unless otherwise noted.

Documentation

Overview

Package xflag is an abstraction around the Go's standard "flag" package, INI or other configuration files, and environment variables.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse(files ...string) error

Parse is a shorthand for the following code:

c := xflag.New(INIConfigParser, os.Args[1:])
err := c.Files(files...)
if err != nil {
	...
}
err = c.Parse()
if err != nil {
	...
}

Types

type Context

type Context struct {

	// Separator is a string that separates different objects or
	// section from key in flag names.
	// By default ":" is used as a separator if Context is allocated
	// using the New constructor.
	// Flag name with the separator may look as "mySection:myKey".
	Separator string

	// ArrLiteral is a string that is if included at the end of a flag
	// name means that the flag must be treated as an array rather than
	// as a scalar type.
	// By default "[]" is used as an array literal if Context is allocated
	// using the New constructor.
	// Flag name with the array literal may look as "mySection:myKey[]".
	ArrLiteral string
	// contains filtered or unexported fields
}

Context represents a single instance of xflag. It contains available arguments and parsed configuration files.

func New

func New(conf config.Interface, args []string) *Context

New allocates and returns a new Context. A slice of input arguments should not include the command name.

func (*Context) Files

func (c *Context) Files(files ...string) error

Files method gets a number of INI configuration files and parses them. An error is returned if some of the files do not exist or their format is not valid. Every subsequent file overrides conflicting values of the previous one.

func (*Context) Parse

func (c *Context) Parse() error

Parse is an equivalent of ParseSet with flag.CommandLine as a flag set input parameter.

func (*Context) ParseSet

func (c *Context) ParseSet(fset *flag.FlagSet) error

ParseSet parses flag definitions using the following sources: 1. Configuration files (that may contain Environment variables); 2. Command line arguments list. The latter has higher priority.

Source Files

Directories

Path Synopsis
Package cflag is an extension to the standard flag package that brings support of complex types.
Package cflag is an extension to the standard flag package that brings support of complex types.
types
Package types implements flag.Value interface for a number of complex types such as []string, []int, []bool, etc.
Package types implements flag.Value interface for a number of complex types such as []string, []int, []bool, etc.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL