snek

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2021 License: MIT Imports: 8 Imported by: 2

README

snek

Go Reference

snek is a Go package that implements lightweight subcommands for a command-line application.

An example of a main entry point:

var Program = snek.NewProgram("", os.Args)

func main() {
	Program.Main()
}

An example of a subcommand:

func init() {
	Program.Register(snek.Def{
		Name:        "echo",
		Summary:     "Display text.",
		Arguments:   "[-n] [TEXT...]",
		Description: `Write the given arguments to standard output.`,
		New:         func() snek.Command { return &EchoCommand{} },
	})
}

type EchoCommand struct {
	NoNewline bool
}

func (c *EchoCommand) SetFlags(flags snek.FlagSet) {
	flags.BoolVar(&c.NoNewline, "n", false, "Suppress trailing newline.")
}

func (c EchoCommand) Run(opt snek.Options) error {
	if err := opt.ParseFlags(); err != nil {
		return err
	}
	out := strings.Join(opt.Args(), " ")
	fmt.Print(out)
	if !c.NoNewline {
		fmt.Print("\n")
	}
	return nil
}

Documentation

Overview

The snek package implements lightweight subcommands for a command-line application.

An example of a main entry point:

var Program = snek.NewProgram("", os.Args)

func main() {
	Program.Main()
}

An example of a subcommand:

func init() {
	Program.Register(snek.Def{
		Name:        "echo",
		Summary:     "Display text.",
		Arguments:   "[-n] [TEXT...]",
		Description: `Write the given arguments to standard output.`,
		New:         func() snek.Command { return &EchoCommand{} },
	})
}

type EchoCommand struct {
	NoNewline bool
}

func (c *EchoCommand) SetFlags(flags snek.FlagSet) {
	flags.BoolVar(&c.NoNewline, "n", false, "Suppress trailing newline.")
}

func (c *EchoCommand) Run(opt snek.Options) error {
	if err := opt.ParseFlags(); err != nil {
		return err
	}
	out := strings.Join(opt.Args(), " ")
	fmt.Print(out)
	if !c.NoNewline {
		fmt.Print("\n")
	}
	return nil
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Command

type Command interface {
	// Run executes the subcommand.
	Run(Options) error
}

Command is an instance of a subcommand definition.

Command may optionally implement FlagSetter, if it has flags.

type Def

type Def struct {
	// Name is the name of the subcommand.
	Name string

	// Doc is the documentation of the subcommand.
	Doc

	// New returns a new instance of the command.
	New func() Command

	// Init further initializes the definition.
	Init func(Def) Def
}

Def describes a subcommand.

type Doc added in v0.3.0

type Doc struct {
	// Summary is a short description of the subcommand.
	Summary string

	// Arguments describes the arguments passed to the subcommand. When
	// displayed, it is prefixed with the name of the program, then the name of
	// the subcommand. ("program subcommand <arguments>")
	Arguments string

	// Description is a detailed description of the subcommand.
	Description string
}

Doc encapsulates the documentation of a subcommand.

type FlagSet

type FlagSet interface {
	Bool(name string, value bool, usage string) *bool
	BoolVar(p *bool, name string, value bool, usage string)
	Duration(name string, value time.Duration, usage string) *time.Duration
	DurationVar(p *time.Duration, name string, value time.Duration, usage string)
	Float64(name string, value float64, usage string) *float64
	Float64Var(p *float64, name string, value float64, usage string)
	Func(name, usage string, fn func(string) error)
	Int(name string, value int, usage string) *int
	Int64(name string, value int64, usage string) *int64
	Int64Var(p *int64, name string, value int64, usage string)
	IntVar(p *int, name string, value int, usage string)
	String(name string, value string, usage string) *string
	StringVar(p *string, name string, value string, usage string)
	Uint(name string, value uint, usage string) *uint
	Uint64(name string, value uint64, usage string) *uint64
	Uint64Var(p *uint64, name string, value uint64, usage string)
	UintVar(p *uint, name string, value uint, usage string)
	Var(value flag.Value, name string, usage string)
}

FlagSet is used to define flags. Each method corresponds to the method in flag.FlagSet.

type FlagSetter

type FlagSetter interface {
	SetFlags(FlagSet)
}

FlagSetter is implemented by any type that can define flags on a FlagSet.

type Input

type Input struct {
	// Program is the name of the program (e.g. os.Args[0]).
	Program string

	// Arguments are the arguments passed to the program (e.g. os.Args[1:]), or
	// to the subcommand.
	Arguments []string

	// Stdin is the file handle to be used as standard input.
	Stdin ReadFile

	// Stdout is the file handle to be used as standard output.
	Stdout WriteFile

	// Stderr is the file handle to be used as standard error.
	Stderr WriteFile

	// GlobalUsage specifies a description for the entire program. It is
	// expected to be a format string, where the first argument is the program
	// name, and the second argument is a list of subcommand summaries. If
	// empty, a default message is displayed.
	GlobalUsage string
}

Input contains inputs to a program or subcommand.

func (Input) WriteUsageOf

func (i Input) WriteUsageOf(w io.Writer, def Def)

WriteUsageOf writes to w (or Stderr if w is nil) the usage of the given command definition.

type Options

type Options struct {
	// FlagSet is an embedded set of flags for the subcommand.
	*flag.FlagSet

	// Input contains the inputs to the subcommand, with the fields inherited
	// from Program. The Arguments field is the unprocessed arguments after the
	// subcommand name.
	Input

	// Def is the definition of the running command.
	Def Def
	// contains filtered or unexported fields
}

Options contains input and flags passed to a subcommand.

func (Options) Get

func (r Options) Get(name string) Def

Get returns the definition of the subcommand mapped to the given name.

func (Options) Has

func (r Options) Has(name string) bool

Has returns whether name is a registered subcommand.

func (Options) List

func (r Options) List() []Def

List returns a list of subcommand definitions, sorted by name.

func (Options) ParseFlags

func (opt Options) ParseFlags() error

ParseFlags parses the embedded FlagSet using opt.Arguments.

func (Options) SetDoc added in v0.3.0

func (r Options) SetDoc(name string, doc Doc)

SetDoc replaces the Doc of the subcommand mapped to the given name. Does nothing if the subcommand does not exist.

func (Options) WriteGlobalUsage

func (opt Options) WriteGlobalUsage(w io.Writer)

WriteGlobalUsage writes the GlobalUsage message to w, or Stderr if w is nil.

func (Options) WriteSummary

func (r Options) WriteSummary(w io.Writer)

WriteSummary writes to w a list of each registered subcommand and its summary.

type Program

type Program struct {
	Input
	// contains filtered or unexported fields
}

Program represents a command-line program.

func NewProgram

func NewProgram(name string, args []string) *Program

NewProgram returns a Program initialized with the given raw arguments (e.g. os.Args).

name is the name of the program. If empty, then the first argument is used instead.

The program is initialized with a default "help" subcommand. If necessary, this command can be removed with the NoHelp method.

func (Program) Get

func (r Program) Get(name string) Def

Get returns the definition of the subcommand mapped to the given name.

func (Program) Has

func (r Program) Has(name string) bool

Has returns whether name is a registered subcommand.

func (Program) List

func (r Program) List() []Def

List returns a list of subcommand definitions, sorted by name.

func (*Program) Main

func (p *Program) Main()

Main provides a convenient entrypoint to the program.

If the program has at least one argument, the subcommand corresponding to the first argument is run with the remaining arguments. If the first argument is not a registered subcommand, then an error is printed to Stderr, along with the global usage message.

If the program has no arguments, then Main runs the "help" subcommand. If no help subcommand has been registered, then the global usage message is written to Stderr.

If a subcommand returns an error, then the error is printed to Stderr. If the error is flag.ErrHelp, then a usage message of the command is written to Stderr instead.

func (*Program) NoHelp

func (p *Program) NoHelp() *Program

NoHelp unregisters the "help" subcommand.

func (*Program) Prepare

func (p *Program) Prepare() (name string, input Input)

Prepare prepares a subcommand. Expects the first argument of p to be the name of a subcommand to run. Returns the name and an input to be passed to the subcommand.

If there are not enough arguments, or no subcommand of the specified name is registered, then an empty string is returned.

func (*Program) Register

func (p *Program) Register(def Def)

Register registers a subcommand under def.Name. Panics if def.Name is empty, if def.New is nil, or if a subcommand was already registered with the name.

func (*Program) Run

func (p *Program) Run(name string) error

Run is like RunWithInput by assuming that the first argument to the program is the given name, and passing the remaining arguments to the subcommand. If there are no arguments, then the subcommand runs without arguments.

func (*Program) RunWithInput

func (p *Program) RunWithInput(name string, input Input) error

RunWithInput executes the subcommand mapped to the given name with the given input. Returns an UnknownCommand error if the name is not a registered subcommand.

func (Program) SetDoc added in v0.3.0

func (r Program) SetDoc(name string, doc Doc)

SetDoc replaces the Doc of the subcommand mapped to the given name. Does nothing if the subcommand does not exist.

func (*Program) Usage

func (p *Program) Usage(usage string) *Program

Usage sets the GlobalUsage field.

func (Program) WriteSummary

func (r Program) WriteSummary(w io.Writer)

WriteSummary writes to w a list of each registered subcommand and its summary.

func (*Program) WriteUsage

func (p *Program) WriteUsage(w io.Writer)

WriteUsage prints the GlobalUsage message to w, or Stderr if w is nil.

type ReadFile

type ReadFile = fs.File

FileReader represents a file that can be read from.

type UnknownCommand

type UnknownCommand struct {
	Name string
}

UnknownCommand indicates an unknown subcommand was received.

func (UnknownCommand) Error

func (err UnknownCommand) Error() string

type WriteFile

type WriteFile interface {
	fs.File
	io.Writer
}

FileWriter represents a file that can be written to.

Jump to

Keyboard shortcuts

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