gocli

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2023 License: MIT Imports: 6 Imported by: 0

README

GoCLI - Command Line Interface Toolkit

Introduction

GoCLI is a versatile toolkit for building command-line interfaces (CLI) in Go. It simplifies parsing command-line arguments and executing associated commands. Whether you're building a simple tool or a complex application, GoCLI offers a structured way to handle user inputs efficiently.

Workflow

  1. Argument Parsing: GoCLI leverages os.Args to receive command-line arguments.

  2. Argument Structure:

    • Commands: One or more actions to be performed.
    • Flags: Prefixed with -- or - followed by a key and a value (alphanumeric).
    • Options: Prefixed with - followed by uppercase words.

    Format: app.exe command1 command2 command3 --flag1 value1 -flag2 value2 -OPTION1 -OPTION2

Fundamental Blocks

// CLI struct wraps the commands, parser, and commander.
type CLI struct {
    Parser    // Parses CLI input.
    Commander // Manages command execution.
}
  • Parser: Validates each part of the args (commands, flags, options) and structures them into an Input object.
  • Commander: Facilitates adding commands with a name and a handler. Allows nested commands or groups.

Usage

Basic Example
package main

import (
    "fmt"
    "github.com/LNMMusic/gocli"
    "github.com/LNMMusic/optional"
)

func main() {
    // Initialize CLI with default parser and commander
    cli := gocli.NewCLI(
        gocli.NewParserDefault(optional.None[gocli.ConfigParserDefault]()),
        gocli.NewCommanderManager("basic", "basic example"),
    )

    // Add command 'hello'
    cli.AddCommand(gocli.Command{
        Name: "hello",
        Description: "Prints hello world and shows input info",
        Handler: func(i gocli.Input) error {
            fmt.Println("hello world")
            fmt.Printf("-command: %s\n-chain: %v\n-flags: %v\n-options: %v\n", i.CommandInput.Command, i.CommandInput.Chain, i.Flags, i.Options)
            return nil
        },
    })

    // Execute CLI
    if err := cli.Run(); err != nil {
        fmt.Println(err)
        return
    }
}
Group Commands Example
package main

import (
    "fmt"
    "github.com/LNMMusic/gocli"
    "github.com/LNMMusic/optional"
)

func main() {
    // Initialize CLI
    cli := gocli.NewCLI(
        gocli.NewParserDefault(optional.None[gocli.ConfigParserDefault]()),
        gocli.NewCommanderManager("group", "example with groups"),
    )

    // Create a command group
    group := cli.Group("group", "Represents 'ping' and 'hello' commands")

    // Add 'ping' command to the group
    group.AddCommand(gocli.Command{
        Name: "ping",
        Description: "Prints pong",
        Handler: func(i gocli.Input) error {
            fmt.Println("pong")
            return nil
        },
    })

    // Add 'hello' command to the group
    group.AddCommand(gocli.Command{
        Name: "hello",
        Description: "Prints hello world and shows input info",
        Handler: func(i gocli.Input) error {
            fmt.Println("hello world")
            fmt.Printf("-command: %s\n-chain: %v\n-flags: %v\n-options: %v\n", i.CommandInput.Command, i.CommandInput.Chain, i.Flags, i.Options)
            return nil
        },
    })

    // Execute CLI
    if err := cli.Run(); err != nil {
        fmt.Println(err)
        return
    }
}

Conclusion

GoCLI is designed to make CLI development in Go more intuitive and structured. By abstracting the complexity of argument parsing and command handling, it allows developers to focus on implementing the core logic of their applications.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrCommandHandlerNotFound is the error that returns when the command is not found.
	ErrCommandHandlerNotFound = errors.New("command not found")
	// ErrCommandManagerNotFound is the error that returns when the command manager is not found.
	ErrCommandManagerNotFound = errors.New("command manager not found")
)
View Source
var (
	// ErrInvalidArgs is the error that occurs when the command is invalid.
	ErrInvalidArgs = errors.New("invalid args")
	// ErrInvalidCommands is the error that occurs when the command chain is invalid.
	ErrInvalidCommands = errors.New("invalid commands")
)

Functions

This section is empty.

Types

type CLI

type CLI struct {
	// Parser is the parser of the CLI.
	// it returns the Input of the command handler.
	Parser
	// Commander is the commander of the CLI.
	// helps finding the command handler from the input.
	Commander
}

CLI is the struct that wraps the commands.

func NewCLI

func NewCLI(p Parser, c Commander) (r CLI)

NewCLI is the function that returns a new CLI.

func (CLI) Run

func (c CLI) Run() (err error)

Run is the method that runs the CLI.

type Command

type Command struct {
	// Name is the name of the command.
	Name string
	// Description is the description of the command.
	Description string
	// Handler is the handler of the command.
	Handler CommandHandler
}

Command is an struct that represents a command.

type CommandHandler

type CommandHandler func(i Input) (err error)

CommandHandler is the type that represents a command function.

type CommandInput

type CommandInput struct {
	// Chain is the chain of the command.
	Chain []string
	// Command is the command.
	Command string
}

type Commander

type Commander interface {
	// Read-Operations
	// FindHandler is the method that finds a handler by name.
	FindHandler(commandName string, commandChain ...string) (h CommandHandler, err error)

	// Write-Operations
	// AddCommand is the method that adds a command to the registry.
	AddCommand(command Command) (err error)
	// Group is the method that groups a list of commands.
	Group(name string, description string) (cm Commander)
}

Commander is the interface that wraps the methods that a command registry must implement.

type CommanderManager

type CommanderManager struct {
	// Name is the name of the command composite.
	Name string
	// Description is the description of the command composite.
	Description string
	// Commands are the commands of the command composite.
	Cmds Commands
	// CommandManagers is the command composite of the command composite.
	CommandManagers []*CommanderManager
}

CommanderManager is the struct that represents a command manager.

func NewCommanderManager added in v1.0.1

func NewCommanderManager(name, description string) (cm *CommanderManager)

NewCommanderManager is the function that creates a new command manager.

func (*CommanderManager) AddCommand

func (c *CommanderManager) AddCommand(cmd Command) (err error)

AddCommand is the method that adds a command to the command manager.

func (*CommanderManager) FindCommandManager

func (c *CommanderManager) FindCommandManager(commandChain ...string) (cm *CommanderManager, err error)

FindCommandManager is the method that finds a command manager by name.

func (*CommanderManager) FindHandler

func (c *CommanderManager) FindHandler(commandName string, commandChain ...string) (h CommandHandler, err error)

FindHandler is the method that finds a handler by name.

func (*CommanderManager) Group

func (c *CommanderManager) Group(name, description string) (cm Commander)

Group is the method that groups a command manager.

type CommanderMock

type CommanderMock struct {
	mock.Mock
}

CommanderMock is the mock that implements the Commander interface.

func NewCommanderMock

func NewCommanderMock() (r *CommanderMock)

NewCommanderMock is the function that returns a new CommanderMock.

func (*CommanderMock) AddCommand

func (m *CommanderMock) AddCommand(command Command) (err error)

AddCommand is the method that adds a command to the registry.

func (*CommanderMock) FindHandler

func (m *CommanderMock) FindHandler(commandName string, commandChain ...string) (h CommandHandler, err error)

FindHandler is the method that finds a handler by name.

func (*CommanderMock) Group

func (m *CommanderMock) Group(name string, description string) (cm Commander)

Group is the method that groups a list of commands.

type Commands

type Commands []Command

Commands is the type that represents a list of commands.

func (Commands) FindHandler

func (c Commands) FindHandler(commandName string) (h CommandHandler, err error)

FindHandler is the method that finds a handler by name.

type ConfigParserDefault

type ConfigParserDefault struct {
	// PatternCLI is the regexp pattern of the full command line.
	PatternCLI string
	// PatternChain is the regexp pattern of the chain.
	PatternChain string
	// PatternFlags is the regexp pattern of the flag.
	PatternFlag string
	// PatternOptions is the regexp pattern of the option.
	PatternOption string
	// Trimmer is a white space trimmer in between.
	Trimmer string
}

ConfigParserDefault is the struct that wraps the configuration of the default parser.

type Input

type Input struct {
	// CommandInput is the input of the command.
	CommandInput CommandInput
	// Flags are the arguments of the command.
	Flags map[string]any
	// Options are the options of the command.
	Options map[string]int
}

Input is the struct that wraps the input of the command.

type Parser

type Parser interface {
	Parse(args string) (i Input, err error)
}

Parser is the interface that wraps the basic Parse method.

type ParserDefault

type ParserDefault struct {

	// Trimmer is a white space trimmer in between.
	// - default: `\s{2,}`
	Trimmer *regexp.Regexp
	// contains filtered or unexported fields
}

ParserDefault is the struct that wraps the default parser.

func NewParserDefault

func NewParserDefault(cfg optional.Option[ConfigParserDefault]) (p *ParserDefault)

NewParserDefault is the function that creates a new default parser.

func (*ParserDefault) Parse

func (p *ParserDefault) Parse(args string) (i Input, err error)

Parse is the method that parses the input.

func (*ParserDefault) ParseCommands

func (p *ParserDefault) ParseCommands(args string) (c CommandInput, err error)

ParseCommands is the method that parses the commands.

func (*ParserDefault) ParseFlags

func (p *ParserDefault) ParseFlags(args string) (f map[string]any)

ParseFlags is the method that parses the flags.

func (*ParserDefault) ParseOptions

func (p *ParserDefault) ParseOptions(args string) (o map[string]int)

ParseOptions is the method that parses the options.

type ParserMock

type ParserMock struct {
	mock.Mock
}

ParserMock is the mock that implements the Parser interface.

func NewParserMock

func NewParserMock() (r *ParserMock)

NewParserMock is the function that returns a new ParserMock.

func (*ParserMock) Parse

func (m *ParserMock) Parse(args string) (i Input, err error)

Parse is the method that parses the input.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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