cli

package module
Version: v0.0.0-...-9961a87 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2018 License: MIT Imports: 8 Imported by: 8

README

= go-cli image:https://travis-ci.org/motemen/go-cli.svg?branch=master["Build Status", link="https://travis-ci.org/motemen/go-cli"] image:http://godoc.org/github.com/motemen/go-cli?status.svg["GoDoc", link="http://godoc.org/github.com/motemen/go-cli"] image:http://gocover.io/_badge/github.com/motemen/go-cli["Test Coverage", link="http://gocover.io/github.com/motemen/go-cli"]

Yet another CLI app builder with commands, based on documentation.

== Example

[source,go]
----
package main

import (
    "flag"
    "os"

    "github.com/motemen/go-cli"
)

func main() {
    cli.Use(&cli.Command{
        Name:  "foo",
        Short: "description in one line",
        Long: `foo [-v] <arg>

Description in paragraphs, starting with a usage line.
Blah blah blah`,
        Action: func(flags *flag.FlagSet, args []string) error {
            // Initialize and parse flags inside Action
            verbose := flags.Bool("v", false, "set verbosity")
            flags.Parse(args)

            args = flags.Args()
            if len(args) < 1 {
                // Return cli.ErrUsage to show the command usage to the user
                return cli.ErrUsage
            }

            ...

            return nil
        },
    })
    cli.Run(os.Args[1:])
}
----

Example output:

----
% prog
Usage: prog <command> [<args>]

Commands:
    foo    description in one line
----

----
% prog foo -h
Usage: foo [-v] <arg>

Description in paragraphs, starting with a usage line.
Blah blah blah

Options:
  -v=false: set verbosity
----

== Registering commands using documentation

You may use github.com/motemen/go-cli/gen to automatically register commands and
their usages using comment documentation. An example documentation for the
example above:

[source,go]
----

// +command foo - description in one line
//
//   foo [-v] <arg>
//
// Description in paragraphs after a usage line.
// Blah blah blah
func actionFoo(flags *flag.FlagSet, args []string) error {
    ...
}
----

You can use gen.Generate() to generate a source file like below:

[source,go]
----
// auto-generated file

package main

import "github.com/motemen/go-cli"

func init() {
    cli.Use(
        &cli.Command{
            Name:   "foo",
            ...
        },
    )
}
----

Include this file to the build and you can maintain CLI commands using documentation. For complete example, refer to the _example directory.

== Author

motemen <motemen@gmail.com>

Documentation

Overview

Package cli is a simple framework for creating CLI apps with commands. Its subpackage github.com/motemen/go-cli/gen provides a way to generate commands from document comments in the code.

Example
cli.Default.Name = "eg"             // defaults to os.Args[0]
cli.Default.ErrorWriter = os.Stdout // defaults to os.Stderr

cli.Use(&cli.Command{
	Name:  "foo",
	Short: "description in one line",
	Long: `foo [-v] <arg>

Description in paragraphs, starting with a usage line.
Blah blah blah`,
	Action: func(flags *flag.FlagSet, args []string) error {
		verbose := flags.Bool("v", false, "set verbosity")
		flags.Parse(args)

		args = flags.Args()
		if len(args) < 1 {
			return cli.ErrUsage
		}

		if *verbose {
			log.Println("showing foo...")
		}

		fmt.Println("foo", args[0])

		if *verbose {
			log.Println("succeeded.")
		}

		return nil
	},
})
cli.Run(os.Args[1:])
Output:

Usage: eg <command> [<args>]

Commands:
    foo    description in one line

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Default implementation of App. Its name is set to os.Args[0].
	Default = &App{
		Commands:          Commands,
		ErrorWriter:       os.Stderr,
		FlagErrorHandling: flag.ExitOnError,
	}
	// Commands is default value of Default.Commands.
	Commands = map[string]*Command{}
)
View Source
var ErrUsage = fmt.Errorf("usage error")

ErrUsage is the error indicating the user had wrong usage.

Functions

func Dispatch

func Dispatch(args []string) error

Dispatch is shortcut for Default.Dispatch.

func Run

func Run(args []string)

Run is a shortcut for Default.Run.

func Use

func Use(cmd *Command)

Use is a shortcut for Default.Use.

Types

type App

type App struct {
	Name     string
	Commands map[string]*Command

	ErrorWriter       io.Writer
	FlagErrorHandling flag.ErrorHandling
}

App represents for a CLI program with commands.

func (*App) Dispatch

func (app *App) Dispatch(args []string) error

Dispatch is yet another entry point which returns error

func (*App) PrintUsage

func (app *App) PrintUsage()

PrintUsage prints out the usage of the program with its commands listed.

func (*App) Run

func (app *App) Run(args []string)

Run is the entry point of the program. It recognizes the first element of args as a command name, and dispatches a command with rest arguments.

func (*App) Use

func (app *App) Use(cmd *Command)

Use registers a app command cmd.

type Command

type Command struct {
	Name string

	// Short (one line) description of the command. Used when the program as
	// invoked without a command name
	Short string

	// Long description of the command. The first line of Long should be a
	// usage line i.e. it starts with the command name. Used when invoked with -h
	Long string

	// The actual implementation of the command. The function will receive two
	// arguments, namely flags and args.  flags is an flag.FlagSet and args are
	// the command line arguments after the command name.  flags is not
	// initialized, so declaring flag variables and arguments parsing with
	// flags.Parse(args) should be called inside the function.
	//
	// Return ErrUsage if you want to show user the command usage.
	Action func(flags *flag.FlagSet, args []string) error
}

Command represents one of commands of App.

func (Command) Usage

func (c Command) Usage(flags *flag.FlagSet) string

Usage returns a usage documentation of a command.

Source Files

Directories

Path Synopsis
Package gen generates github.com/motemen/go-cli.Command from function docs in files specified.
Package gen generates github.com/motemen/go-cli.Command from function docs in files specified.

Jump to

Keyboard shortcuts

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