cmdflag

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 6, 2019 License: BSD-3-Clause Imports: 9 Imported by: 29

README

cmdflag : command support to the standard library flag package

Overview GoDoc Go Report Card

Building on top of the excellent flag package from the standard library, cmdflag adds a simple way of specifying nested commands. Its intent is to blend with the usage of flag by keeping its idioms and simply augment it with commands.

Install

go get github.com/pierrec/cmdflag

Usage

A Command is a set of flags (flag.FlagSet) with a (potentially empty) set of other Commands (sometimes referred to as subcommands). To define a subcommand, Command.Add an Application defining its properties:

  • Name - the subcommand name
  • Descr - a short desciption of the subcommand
  • Args - the list of arguments expected by the subcommand
  • Help - a long description of the subcommand
  • Err - what to do in case of error (same as in the flag package)
  • Init - the function to be run once the subcommand is encountered (lazily initialized)

Nested commands are supported, so a subcommand can also have its own subcommands.

Example

./chef cook -toppings cheese,mushrooms pizza

c := cmdflag.New(nil)
c.Add(cmdflag.Application{
    Name: "cook",
    Init: func(fs *flag.FlagSet) cmdflag.Handler {
        var toppings string
        fs.StringVar(&toppings, "toppings", "", "coma separated list of toppings")
        
        return func(args ...string) (int, error) {
            fmt.Printf("courses: %v\n", args)
            fmt.Printf("toppings: %v\n", strings.Split(toppings, ","))
            return len(args), nil
        }
    }
}

Extra features

To make life easier, a few common uses of a command line library are provided and can be easily activated:

  • flags: defining them as a flag activates them
    • -version - see VersionBoolFlag
    • -fullversion - see FullVersionBoolFlag
    • the standard -h and -help flags are supported to display the usage of the command they apply to
  • commands:
    • help - provides a way to display Application.Help for a given command (activated by Command.AddHelp)

Contributing

Contributions welcome via pull requests. Please provide tests.

Documentation

Overview

Package cmdflag provides simple command line commands processing on top of the standard library flag package.

It strives to be lightweight (only relying on the standard library) and fits naturally with the usage of the flag package.

Index

Examples

Constants

View Source
const (
	// VersionBoolFlag is the flag name to be used as a boolean flag to display the program version.
	// Declaring a boolean flag with that name will automatically implement version display.
	VersionBoolFlag = "version"
	// FullVersionBoolFlag is the flag name to be used as a boolean flag to display the full program version,
	// Declaring a boolean flag with that name will automatically implement displaying the program version,
	// including its modules and compiler versions.
	FullVersionBoolFlag = "fullversion"
)
View Source
const HelpCommand = "help"

HelpCommand is the command name used to display the help of a given command. If no command is supplied, the usage is displayed.

To display the help of a command (Application.Help), do:

./myprogram help commandname

Variables

This section is empty.

Functions

This section is empty.

Types

type Application

type Application struct {
	Name  string                      // Command name
	Descr string                      // Short description
	Args  string                      // Description of the expected arguments
	Help  string                      // Displayed when used with the help command
	Err   flag.ErrorHandling          // Arguments error handling
	Init  func(*flag.FlagSet) Handler // Initialize the arguments when the command is matched
}

Application defines the attributes of a Command.

type Command

type Command struct {
	Application
	// Usage is the function used to display the usage description.
	Usage func()
	// contains filtered or unexported fields
}

Command represents a command line command.

func New

func New(fset *flag.FlagSet) *Command

New instantiates the top level command based on the provided flag set. If no flag set is supplied, then it defaults to flag.CommandLine.

func (*Command) Add

func (c *Command) Add(app Application) (*Command, error)

Add adds a new command with its name and description and returns the new command.

It is safe to be called from multiple go routines (typically in init functions).

The command initializer is called only when the command is present on the command line. The handler is called with the remaining arguments once the command flags have been parsed successfully.

Command names must be unique and non empty.

Example
package main

import (
	"flag"
	"fmt"
	"github.com/pierrec/cmdflag"
)

func main() {
	// Declare the `split` cmdflag.
	c := cmdflag.New(flag.CommandLine)
	_, _ = c.Add(
		cmdflag.Application{
			Name:  "split",
			Descr: "splits files into fixed size chunks",
			Args:  "[sep ...]",
			Help: `split can split multiple files into chunks
e.g. split -size 1M file1 file2
will generate files of 1M or maybe less for the last one, as follow:
file1_0
file1_1
...
file1_x
file2_00
file2_01
...
file2_yy`,
			Err: flag.ExitOnError,
			Init: func(fs *flag.FlagSet) cmdflag.Handler {
				// Declare the cmdflag specific flags.
				var s string
				fs.StringVar(&s, "s", "", "string to be split")

				// Return the handler to be executed when the cmdflag is found.
				return func(sep ...string) (int, error) {
					i := len(s) / 2
					fmt.Printf("%s %v %s", s[:i], sep, s[i:])
					return 1, nil
				}
			},
		})

	// ./program split -s hello & @
	if err := c.Parse("split", "-s", "hello", "&", "@"); err != nil {
		panic(err)
	}

}
Output:

he [& @] llo

func (*Command) AddHelp

func (c *Command) AddHelp() error

AddHelp adds a help command to display additional information for commands.

func (*Command) Commands

func (c *Command) Commands() []*Command

Commands returns all the commands defined on c.

func (*Command) MustAdd

func (c *Command) MustAdd(app Application) *Command

MustAdd is similar to Add but panics if an error is encountered.

func (*Command) MustAddHelp added in v0.0.2

func (c *Command) MustAddHelp()

MustAddHelp is similar to AddHelp but panics if an error is encountered.

func (*Command) Output

func (c *Command) Output() io.Writer

Output returns the output used for usage. It defaults to os.Stderr.

func (*Command) Parse

func (c *Command) Parse(args ...string) error

Parse parses the command line arguments from the argument list, which should not include the command name and including the global flags and, if any, the command and its flags.

To be called in lieu of flag.Parse().

If no arguments are supplied, it defaults to os.Args[1:]. If the VersionBoolFlag is defined as a global boolean flag, then the program version is displayed and the program stops. If the FullVersionBoolFlag is defined as a global boolean flag, then the full program version is displayed and the program stops.

type Error

type Error string

Error defines the error type for this package.

const (
	// ErrNoCommand is returned when no command was found on the command line.
	ErrNoCommand Error = "no command specified"
	// ErrMissingCommandName is returned for an invalid command name (empty).
	ErrMissingCommandName Error = "missing command name"
	// ErrMissingInitializer is returned when a command does not have its initializer defined.
	ErrMissingInitializer Error = "missing command initializer"
	// ErrDuplicateCommand is returned when a command is redefined.
	ErrDuplicateCommand Error = "duplicated command"
)

func (Error) Error

func (e Error) Error() string

type Handler

type Handler func(args ...string) (int, error)

Handler is the function called when a matching command is found. It returns the number of arguments consumed or an error.

Directories

Path Synopsis
examples
sqldump Module

Jump to

Keyboard shortcuts

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