cmd

package module
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2023 License: MIT Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Idiomatic Go Package for cli subcommands

GoDev

This package is intended to be used in conjunction with the Go flag package for maping subcommands to their respective flagset.

The primary features of cmd are:

  • Use the standerd flag packege. cmd does not implement its own flag parsing. Instead it integrates nicely with the standerd flag package.

  • Common API, style and behavior closely follows that of the standers flag packege.

  • Minimal feature set, does not attempt to be a "one size fits all" solution.

  • Optionaly enable/disable extra command argument support (besides flags) for subcommands.

Install

go get -u github.com/meblum/cmd

Example usage

import (
	"flag"
	"fmt"

	"github.com/meblum/cmd"
)

func main() {
	greeter := greetHandler{
		greetType: "hello",
		greetName: "Anonymous",
	}

	greetFlagSet := flag.NewFlagSet("greet", flag.ExitOnError)
	greetFlagSet.StringVar(&greeter.greetType, "type", greeter.greetType, "greet type (hello|bye)")
	greetFlagSet.StringVar(&greeter.greetName, "name", greeter.greetName, "name to print greeting for")

	version := versionHandler{
		version: "1.0.0",
		verbose: false,
	}

	versionFlagSet := flag.NewFlagSet("version", flag.ExitOnError)
	versionFlagSet.BoolVar(&version.verbose, "verbose", version.verbose, "output version with additional information")

	c := &cmd.CmdSet{}
	c.Add("print greeting", greetFlagSet, greeter, false)
	c.Add("print version", versionFlagSet, version, false)
	c.HandleCmd(nil, flag.ExitOnError)
}

type greetHandler struct {
	greetType string
	greetName string
}

func (g greetHandler) Handle(c *cmd.Cmd) error {
	switch g.greetType {
	case "hello":
		fmt.Printf("Hello, %v! Nice to meet you :)", g.greetName)
	case "bye":
		fmt.Printf("Hello, %v! Nice to meet you :)", g.greetName)
	default:
		return fmt.Errorf("invalid greet type %v, valid options are 'hello' or 'bye'", g.greetType)
	}
	return nil
}

type versionHandler struct {
	version string
	verbose bool
}

func (g versionHandler) Handle(c *cmd.Cmd) error {
	if g.verbose {
		fmt.Printf("You are using Greeter version %v", g.version)
	}
	fmt.Print(g.version)
	return nil
}


See the documentation for more information.

License

MIT - See LICENSE file

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cmd

type Cmd struct {
	Info      string
	FlagSet   *flag.FlagSet
	AllowArgs bool
	Handler   Handler
}

A Cmd is a single subcommand with a set of flags.

type CmdSet

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

A CmdSet contains a set of subcommands.

The zero value of CmdSet contains no commands. Use CmdSet.Add to add subcommands.

func (*CmdSet) Add

func (c *CmdSet) Add(usage string, flags *flag.FlagSet, handler Handler, allowArgs bool) *Cmd

Add adds a subcommand with specified usage string and flag set. The command name is derived from flags.Name. Use the allowArgs argument to specify wheather additional args should be allowed. For easy mapping from command to the relevant handler, supply a handler which will be added to the Cmd returned from Parse(). Returns the addded command.

Command names must be unique within a CommandSet. An attempt to define a command whose name is an emty string or whose name is already in use will cause a panic.

func (*CmdSet) HandleCmd added in v1.1.0

func (c *CmdSet) HandleCmd(arguments []string, errorHandling flag.ErrorHandling) error

HandleCmd is equivilant to Parse followed by calling the handler of the returned Cmd. If Parse fails, the reulting error is returned, otherwise the result from handle is returned.

func (*CmdSet) Parse

func (c *CmdSet) Parse(arguments []string, errorHandling flag.ErrorHandling) (*Cmd, error)

Parse parses the subcommand from arguments[0] and its flags from arguments[1:] with the error handling specified by errorHandling. Returns the supplied Subcommand if a match was found.

Must be called after all subcommands are defined and before flags are accessed by the program. If arguments is nil, will default to `os.Args[1:]`.

func (*CmdSet) PrintUsage

func (c *CmdSet) PrintUsage()

PrintUsage prints usage information to standard error.

func (*CmdSet) Visit

func (c *CmdSet) Visit(f func(*Cmd))

Visit runs f on every command currently in c. Most commonly used to apply global flags to a command set.

type Handler added in v1.1.0

type Handler interface {
	Handle(*Cmd) error
}

Handler defines the interface of a Cmd handler

Jump to

Keyboard shortcuts

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