cli

package
v0.0.16 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

README

cli

This project is a Go library for building powerful and user-friendly command-line interfaces (CLIs). The library makes it easy to create and manage complex command structures, parse command-line arguments, and provide helpful error messages and usage information to the user.



Installation

go get go.nandlabs.io/commons/cli

Features

  • Easy to use API for building complex command structures
  • Argument parsing and validation
  • Automatically generates usage and help information
  • Written in Go and follows best practices for Go programming

Usage

Default
package main

import (
	"fmt"
	"log"
	"os"

	"go.nandlabs.io/commons/cli"
)

func main() {
	app := &cli.App{
		Version: "v0.0.1",
		Action: func(ctx *cli.Context) error {
			fmt.Printf("Hello, Golang!")
			return nil
		},
	}

	if err := app.Execute(os.Args); err != nil {
		log.Fatal(err)
	}
}

CLI Command and Output

~ % go run main.go greet
Hello, Golang!
Subcommands
package main

import (
	"fmt"
	"log"
	"os"

	"go.nandlabs.io/commons/cli"
)

func main() {
	app := &cli.App{
		Version: "v0.0.1",
		Action: func(ctx *cli.Context) error {
			fmt.Printf("Hello, Golang!")
			return nil
		},
		Commands: []*cli.Command{
			{
				Name:    "test",
				Usage:   "this is a test command",
				Aliases: []string{"t"},
				Action: func(ctx *cli.Context) error {
					fmt.Println("hello from test command")
					return nil
				},
			},
			{
				Name:    "run",
				Usage:   "time to run",
				Aliases: []string{"r"},
				Action: func(ctx *cli.Context) error {
					fmt.Println("time to run away")
					return nil
				},
				Commands: []*cli.Command{
					{
						Name:  "slow",
						Usage: "run slow",
						Action: func(ctx *cli.Context) error {
							fmt.Println("time to run slow")
							return nil
						},
					},
					{
						Name:  "fast",
						Usage: "run fast",
						Action: func(ctx *cli.Context) error {
							fmt.Println("time to run fast")
							return nil
						},
					},
				},
			},
		},
	}

	if err := app.Execute(os.Args); err != nil {
		log.Fatal(err)
	}
}

CLI Commands and Output

~ % go run main.go test
hello from test command
~ % go run main.go run
time to run away
~ % go run main.go run fast
time to run fast
Flags
package main

import (
	"fmt"
	"log"
	"os"

	"go.nandlabs.io/commons/cli"
)

const (
	ProjectDir  = "pd"
	ProfileFile = "pf"
)

func main() {
	app := &cli.App{
		Version: "v0.0.1",
		Action: func(ctx *cli.Context) error {
			fmt.Printf("Hello, Golang!\n")
			fmt.Println(ctx.GetFlag(ProjectDir))
			fmt.Println(ctx.GetFlag(ProfileFile))
			return nil
		},
		Commands: []*cli.Command{
			{
				Name:    "test",
				Usage:   "this is a test command",
				Aliases: []string{"t"},
				Action: func(ctx *cli.Context) error {
					fmt.Println("hello from test command")
					fmt.Println(ctx.GetFlag(ProjectDir))
					fmt.Println(ctx.GetFlag(ProfileFile))
					return nil
				},
			},
			{
				Name:    "run",
				Usage:   "time to run",
				Aliases: []string{"r"},
				Action: func(ctx *cli.Context) error {
					fmt.Println("time to run away")
					fmt.Println(ctx.GetFlag(ProjectDir))
					fmt.Println(ctx.GetFlag(ProfileFile))
					return nil
				},
				Commands: []*cli.Command{
					{
						Name:  "slow",
						Usage: "run slow",
						Action: func(ctx *cli.Context) error {
							fmt.Println("time to run slow")
							fmt.Println(ctx.GetFlag(ProjectDir))
							fmt.Println(ctx.GetFlag(ProfileFile))
							return nil
						},
					},
					{
						Name:  "fast",
						Usage: "run fast",
						Action: func(ctx *cli.Context) error {
							fmt.Println("time to run fast")
							fmt.Println(ctx.GetFlag(ProjectDir))
							fmt.Println(ctx.GetFlag(ProfileFile))
							return nil
						},
					},
				},
			},
		},
		// global app flags
		Flags: []*cli.Flag{
			{
				Name:    ProjectDir,
				Aliases: []string{"pd"},
				Default: "",
				Usage:   "Directory of the project to be built",
			},
			{
				Name:    ProfileFile,
				Aliases: []string{"pf"},
				Default: "",
				Usage:   "Profile file name to be used",
			},
		},
	}

	if err := app.Execute(os.Args); err != nil {
		log.Fatal(err)
	}
}

CLI Commands and Output

~ % go run main.go test -pd="test" -pf="dev"
Hello, Golang!
test
dev
~ % go run main.go run -pd="test" -pf="dev"
time to run away
test
dev
~ % go run main.go run fast -pd="test" -pf="dev"
time to run fast
test
dev

Documentation

Overview

Package cli provides functionality for handling command-line arguments.

Package cli provides a command-line interface (CLI) framework for Go applications.

This package offers a set of utilities and abstractions to build command-line interfaces with ease. It includes features such as command parsing, flag handling, and subcommand support.

Usage: To use this package, import it in your Go code:

import "github.com/nandlabs/go-commons/cli"

Example: Here's a simple example that demonstrates how to use the `cli` package:

package main

import (
    "fmt"
    "github.com/nandlabs/go-commons/cli"
)

func main() {
    app := cli.NewApp()
    app.Name = "myapp"
    app.Usage = "A simple CLI application"

    app.Action = func(c *cli.Context) error {
        fmt.Println("Hello, World!")
        return nil
    }

    err := app.Run(os.Args)
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

For more information and examples, please refer to the package documentation at:

https://github.com/nandlabs/go-commons/cli

Index

Constants

This section is empty.

Variables

View Source
var AppHelpTemplate = `` /* 242-byte string literal not displayed */
View Source
var CommandHelpTemplate = `` /* 170-byte string literal not displayed */
View Source
var HelpFlag = &Flag{
	Name:    "help",
	Usage:   "show help",
	Aliases: []string{"-h", "--help"},
	Default: "",
}

HelpFlag is a built-in flag that represents the help flag.

View Source
var HelpFlags = [2]string{"--help", "-h"}

HelpFlags defines the flags used to display help.

View Source
var PrintCustomHelp helpCustomPrinter = printCustomHelp

PrintCustomHelp is a function that prints custom help information using the provided template, data, and custom functions.

View Source
var PrintHelp helpPrinter = printHelp

PrintHelp is a function that prints the help information using the provided template and data.

Functions

func ShowAppHelp

func ShowAppHelp(conTxt *Context) error

ShowAppHelp displays help information for the entire application.

func ShowCommandHelp

func ShowCommandHelp(conTxt *Context) error

ShowCommandHelp displays help information for a specific command.

Types

type ActionFunc

type ActionFunc func(conTxt *Context) error

type App

type App struct {
	// Name is the application name.
	Name string
	// Usage is the application usage information.
	Usage string
	// HelpName is the name used in the help command.
	HelpName string
	// ArgsUsage is the usage information for command arguments.
	ArgsUsage string
	// UsageText is the custom usage text for the application.
	UsageText string
	// Version is the application version.
	Version string
	// HideVersion determines whether to hide the version information.
	HideVersion bool
	// Action is the function to be invoked on default execution.
	Action ActionFunc
	// Flags are the global flags for the application.
	Flags []*Flag
	// Commands are the application commands.
	Commands []*Command
	// Writer is the output writer for the application.
	Writer io.Writer
	// HideHelp determines whether to hide the help command.
	HideHelp bool
	// HideHelpCommand determines whether to hide the help command in the list of commands.
	HideHelpCommand bool
	// CommandVisible determines whether the commands are visible.
	CommandVisible bool
	// contains filtered or unexported fields
}

App represents a CLI application.

func (*App) Command

func (app *App) Command(name string) *Command

Command returns the command with the given name.

func (*App) Execute

func (app *App) Execute(arguments []string) error

Execute executes the application with the given arguments.

func (*App) ExecuteContext

func (app *App) ExecuteContext(ctx context.Context, arguments []string) error

ExecuteContext executes the application with the given context and arguments.

func (*App) VisibleCommands

func (app *App) VisibleCommands() []*Command

VisibleCommands returns the visible commands of the application.

type Args

type Args interface {
	Get(n int) string
	First() string
	FetchArgs() *ArgsCli
}

Args is an interface that defines methods for retrieving command-line arguments.

type ArgsCli added in v0.0.13

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

ArgsCli is a struct that holds the parsed command-line arguments.

type Command

type Command struct {
	// command name used to invoke from CLI
	Name string
	// command usage information
	Usage     string
	ArgsUsage string
	// the array of aliases to invoke the commands
	Aliases []string
	// execute on the command invocation
	Action ActionFunc
	// command specific flags
	Flags []*Flag
	// subcommands of the root command
	Commands             []*Command
	HelpName             string
	UsageText            string
	SubCommandsAvailable bool
}

func (*Command) HasName

func (command *Command) HasName(name string) bool

func (*Command) Names

func (command *Command) Names() []string

func (*Command) Run

func (command *Command) Run(conTxt *Context, arguments ...string) error

func (*Command) VisibleCommands

func (command *Command) VisibleCommands() []*Command

type Context

type Context struct {
	context.Context
	App     *App
	Command *Command
	// contains filtered or unexported fields
}

func NewContext

func NewContext(app *App, parentCtx *Context) *Context

func (*Context) Args

func (conTxt *Context) Args() Args

func (*Context) GetFlag

func (conTxt *Context) GetFlag(name string) interface{}

type Flag added in v0.0.13

type Flag struct {
	Name    string      // Name of the flag.
	Usage   string      // Usage description of the flag.
	Aliases []string    // Aliases for the flag.
	Default interface{} // Default value of the flag.
	Value   interface{} // Current value of the flag.
}

Flag represents a command-line flag.

func (*Flag) AddFlagToSet added in v0.0.13

func (f *Flag) AddFlagToSet()

AddFlagToSet adds the flag to the flag set.

func (*Flag) AddHelpFlag added in v0.0.13

func (f *Flag) AddHelpFlag()

AddHelpFlag adds the help flag to the flag set.

Jump to

Keyboard shortcuts

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