subcommands

package module
v0.0.0-...-923a6cc Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2018 License: Apache-2.0 Imports: 4 Imported by: 0

README

subcommands

Sub-commands package for sub-commands handling. Mainly motivated to combine with peterbourgon/ff flag parsing library.

Usage

func main() {
	cmd := subcommands.NewCommand("myapp", flag.CommandLine, nil)
	
	var addr string
	fs := flag.NewFlagSet("serve", flag.ExitOnError)
	fs.StringVar(&addr, "addr", ":8080", "listening addr")
	cmd.AddCommand(subcommands.NewCommand(fs.Name(), fs, func() error {
		return http.ListenAndServe(addr, nil)
	})
	
	err := cmd.Execute(os.Args[1:], func(fs *flag.FlagSet, args []string) error {
		return ff.Parse(fs, args,
			ff.WithConfigFileFlag("config"),
			ff.WithConfigFileParser(ff.PlainParser),
			ff.WithEnvVarPrefix(strings.ToUpper(cmd.Name())),
		)
	})
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Command

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

Command represents a single command.

func NewCommand

func NewCommand(name string, flagSet *flag.FlagSet, run func() error) *Command

NewCommand returns a new command with the specified name, flags and runner. The runner could be nil in order to use the command as the root of other subcommands.

func (*Command) AddCommand

func (c *Command) AddCommand(subc *Command)

AddCommand adds a subcommand to the supported subcommands.

func (*Command) Execute

func (c *Command) Execute(args []string, p FlagParser) error

Execute executes the command and returns an error in case the runner fails.

func (*Command) Name

func (c *Command) Name() string

Name returns the name of the command.

type FlagParser

type FlagParser func(fs *flag.FlagSet, args []string) error

FlagParser parses a flag set with the specified arguments.

Jump to

Keyboard shortcuts

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