cli

package
v1.13.4 Latest Latest
Warning

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

Go to latest
Published: Jan 19, 2017 License: MIT, Apache-2.0 Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseArgs

func ParseArgs(cxt cookoo.Context, params *cookoo.Params) (interface{}, cookoo.Interrupt)

Parse arguments for a "subcommand"

The cookoo.cli.RequestResolver allows you to specify global level flags. This command allows you to augment those with subcommand flags. Example:

$ myprog -foo=yes subcommand -bar=no

In the above example, `-foo` is a global flag (set before the subcommand), while `-bar` is a local flag. It is specific to `subcommand`. This command lets you parse an arguments list given a pointer to a `flag.FlagSet`.

Like the cookoo.cli.RequestResolver, this will place the parsed params directly into the context. For this reason, you ought not use the same flag names at both global and local flag levels. (The local will overwrite the global.)

Params:

  • args: (required) A slice of arguments. Typically, this is `cxt:args` as set by cookoo.cli.RequestResolver.
  • flagset: (required) A set if flags (see flag.FlagSet) to parse.

A slice of all non-flag arguments remaining after the parse are returned into the context.

For example, if ['-foo', 'bar', 'some', 'other', 'data'] is passed in, '-foo' and 'bar' will be parsed out, while ['some', 'other', 'data'] will be returned into the context. (Assuming, of course, that the flag definition for -foo exists, and is a type that accepts a value).

Thus, you will have `cxt:foo` available (with value `bar`) and everything else will be available in the slice under this command's context entry.

func RunSubcommand

func RunSubcommand(cxt cookoo.Context, params *cookoo.Params) (interface{}, cookoo.Interrupt)

Run a subcommand.

Params:

  • args: a string[] of arguments, like you get from os.Args. This will assume the first arg is a subcommand. If you have options, you should parse those out first with ParseArgs.
  • default: The default subcommand to run if none is found.
  • offset: By default, this assumes an os.Args, and looks up the item in os.Args[1]. You can override this behavior by setting offset to something else.
  • ignoreRoutes: A []string of routes that should not be executed.

func ShiftArgs

func ShiftArgs(c cookoo.Context, params *cookoo.Params) (interface{}, cookoo.Interrupt)

Shift the args N (default 1) times, returning the last shifted value.

Params:

  • n: The number of times to shift. Only the last value is returned.
  • args: The name of the context slice/array to modify. This value will be retrieved from the context. Default: "os.Args"

func ShowHelp

func ShowHelp(cxt cookoo.Context, params *cookoo.Params) (interface{}, cookoo.Interrupt)

Show help. This command is useful for placing at the front of a CLI "subcommand" to have it output help information. It will only trigger when "show" is set to true, so another command can, for example, check for a "-h" or "-help" flag and set "show" based on that.

Params:

  • show (bool): If `true`, show help.
  • summary (string): A one-line summary of the command.
  • description (string): A short description of what the command does.
  • usage (string): usage information.
  • flags (FlagSet): Flags that are supported. The FlagSet will be converted to help text.
  • writer (Writer): The location that this will write to. Default is os.Stdout
  • subcommands ([]string): A list of subcommands. This will be formatted as help text.

Types

type RequestResolver

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

A CLI-centered request resolver with support for command line flags.

When this resolver finds "globalFlags" in the base context, it attempts to parse out the flags from the `path` string.

You must specify arguments as a `flag.FlagSet` (see the Go documentation).

Parsed commanline arguments are put directly into the context (though later we may put them in a datasource instead). Currently, all parameter values -- even booleans -- are stored as strings. If it is important to you to store them as more complex types, you may need to use `FlagSet.*Var()` functions.

Splitting the path string into arguments is done naively by splitting the string on the space (%20) character.

Arguments are parsed when the request resolver is asked to resolve (no earlier). Thus the FlagSet may be placed into the context at any time prior to cookoo.Router.HandleRequest().

CONTEXT VALUES - globalFlags: A `flag.FlagSet`. If this is present and not empty, the path will be parsed.

func (*RequestResolver) Init

func (r *RequestResolver) Init(registry *cookoo.Registry)

func (*RequestResolver) Resolve

func (r *RequestResolver) Resolve(path string, cxt cookoo.Context) (string, error)

type Runner

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

Runner is a CLI runner.

It provides a nice abstraction for simply and easily running CLI commands.

func New

func New(reg *cookoo.Registry, router *cookoo.Router, cxt cookoo.Context) *Runner

New creates a new CLI instance.

It takes a flagset for parsing command line options, and creates a new CLI application initialized. Flags are placed into the context.

By default, the `cookoo.BasicRequestResolver` is used for resolving request. This works well with the subcommand model of delegating commands.

If a '@startup' route is inserted into the registry, it will be run first upon any call to `Router.HandleRequest`. If not, the default startup will be run. That routine includes displaying help text if the -h or -help flags are passed in.

The `summary` is a one line explanation of the program used in help text.

The `usage` is a detailed help message, often several paragraphs.

The `globalFlags` are a `flag.FlagSet` for the top level of this program. If you use subcommands and want subcommand-specific flags, use the `ParseArgs` command in this package.

Typical usage:

package main

import(
	"github.com/Masterminds/cookoo"
	"github.com/Masterminds/cookoo/cli"
	"flag"
)

var Summary := "A program that does stuff."
var Description := `Full text description goes here.`
func main() {
	flags := flag.FlagSet("global", flag.PanicOnError)
	// Define any flags here...
	flags.Bool("h", false, "Show help text")

	reg, router, cxt := cookoo.Cookoo()
	reg.Route("hello", "Does nothing")

	cli.New(reg, router, cxt).Help(Summary, Description, flags).Run("hello")
}

The simple program above can be run any of these ways:

	$ mycli       # Will run 'hello', which does nothing
 $ mycli -h    # Will show help

If we were to substitute `RunSubcommand` instead of `Run`:

cli.New(reg, router, cxt).Help(Summary, Description, flags).RunSubcommand()

The above would do the following:

	$ mycli       # Will show help
 $ mycli -h    # Will show help
 $ mycli help  # Will show help
 $ mycli hello # Will run hte "hello" route, which does nothing.

func (*Runner) Help

func (r *Runner) Help(summary, usage string, flags *flag.FlagSet) *Runner

Help sets the help text and support flags for the app.

It is strongly advised to use this function for all CLI runner apps.

func (*Runner) Run

func (r *Runner) Run(route string) error

Run runs a given route.

It first runs the '@startup' route, and then runs whatever the named route is.

If the flags `-h` or `-help` are specified, then the presence of those flags will automatically trigger help text.

Additionally, the command `help` is predefined to generate help text.

func (*Runner) RunSubcommand

func (r *Runner) RunSubcommand() error

RunSubcommand uses the first non-flag argument in args as a route name.

For example:

$ mycli -foo=bar myroute

The above will see 'myroute' as a subcommand, and match it to a route named 'subcommand'. In the event that the route is not present, the help text will be displayed.

func (*Runner) Subcommand

func (r *Runner) Subcommand(name, summary, usage string, flags *flag.FlagSet) *cookoo.Registry
import (
	"github.com/Masterminds/cookoo"
	"github.com/Masterminds/cookoo/cli"
	"github.com/Masterminds/cookoo/fmt"

	"flag"
)

func main() {
	reg, router, cxt := cookoo.Cookoo()

	// global flags
	flags := flag.NewFlagSet("global", flag.PanicOnError)
	flags.Bool("h", false, "Print help")

	// Create a new app
	app := cli.New(reg, router, cxt).Help("Test", "test -h", flags)

	// Create a new subcommand on that app
	app.Subcommand("test", "A test route.", "example test", nil).
		Does(fmt.Println, "out").Using("content").WithDefault("Hello World")

	helloFlags := flag.NewFlagSet("test", flag.ContinueOnError)
	helloFlags.Bool("h", false, "Print help")
	helloFlags.String("n", "World!", "A name to greet.")
	app.Subcommand("hello", "Print hello.", "example hello -n Matt", helloFlags).
		Does(fmt.Printf, "out").
			Using("format").WithDefault("Hello %s\n").
			Using("0").WithDefault("World").From("cxt:n")

	// Run the app, and let it figure out which subcommand to run.
	app.RunSubcommand()
}

The above declares two subcommands: 'test' and 'hello'. If the flags argument is nil, the Subcommand will automatically create a default flagset with '-h' mapped to the help.

Any remaining arguments are placed into the context as "subcommand.Args"

Jump to

Keyboard shortcuts

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