artillery

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: MIT Imports: 11 Imported by: 1

README

artillery

An interactive shell/REPL and CLI parser for golang

Artillery can function both as an interactive shell or REPL, as well as a single command CLI parser. In interactive mode, it uses NilShell for the command line editor, completion, and history.

A basic interactive shell/REPL

import (
    "github.com/hashibuto/artillery"
)

	processor := artillery.NewProcessor()

	cmds := []*artillery.Command{
		&artillery.Command{
            Name:        "hello",
            Description: "prints hello to the console",
            Arguments: []*artillery.Argument{
                {
                    Name:        "name",
                    Description: "name of the person to which to say hello",
                },
            },
            Options: []*artillery.Option{
                {
                    Name:        "shout",
                    Description: "shout mode",
                    ShortName:   's',
                    Type:        artillary.Bool
                    Value:       true,
                },
            },
            OnExecute: func(ns artillery.Namespace, processor *artillery.Processor) error {
                var args struct {
                    Name  string
                    Shout bool
                }
                err := artillery.Reflect(ns, &args)
                if err != nil {
                    return err
                }

                message := fmt.Sprintf("hello %s!", args.Name)
                if args.Shout {
                    message = strings.ToUpper(message)
                }
                return nil
            },
        },
	}

	for _, c := range cmds {
		err := processor.AddCommand(c)
		if err != nil {
			log.Fatal(err)
		}
	}

	processor.Shell().ReadUntilTerm()

Parse a single CLI command (non-interactive)

import (
    "github.com/hashibuto/artillery"
    "os"
)

helloCmd := &artillery.Command{
    Name:        "hello",
    Description: "prints hello to the console",
    Arguments: []*artillery.Argument{
        {
            Name:        "name",
            Description: "name of the person to which to say hello",
        },
    },
    Options: []*artillery.Option{
        {
            Name:        "shout",
            Description: "shout mode",
            ShortName:   's',
            Type:        artillary.Bool
            Value:       true,
        },
    },
    OnExecute: func(ns artillery.Namespace, processor *artillery.Processor) error {
        var args struct {
            Name  string
            Shout bool
        }
        err := artillery.Reflect(ns, &args)
        if err != nil {
            return err
        }

        message := fmt.Sprintf("hello %s!", args.Name)
        if args.Shout {
            message = strings.ToUpper(message)
        }
        return nil
    },
}

processor := artillery.NewProcessor()
processor.RemoveBuiltins(false)
err := processor.AddCommands(helloCmd)
if err != nil {
    panic(err)
}

err = processor.Process(os.Args[1:])

Special commands / keystrokes

  • clear clears the terminal
  • !<command> execs the command ie !cat /home/user/something for bash do !bash -c "cat /home/user/something | grep whatever"
  • exit exits
  • <ctrl+r> reverse search
  • <up> move up backwards through the command history
  • <down> move forwards through the command history
  • <ctrl+d> exit
  • <tab> autocomplete

Example

Example showcasing most features

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Debug bool = false

Functions

func CreateEmptyArrayOfType added in v0.2.0

func CreateEmptyArrayOfType(arrType ArgType) any

func Reflect

func Reflect(namespace Namespace, obj any) error

Reflect attempts to reflect the data in namespace to the provided object

Types

type ArgType

type ArgType string
const (
	String ArgType = "string"
	Int    ArgType = "int"
	Bool   ArgType = "bool"
	Float  ArgType = "float"
)

type Argument

type Argument struct {
	Name           string
	Description    string
	Type           ArgType        // String is the default argument type
	Default        any            // Default value (only valid in the final argument position)
	MemberOf       []string       // When value must be a member of a limited collection (strings only)
	CompletionFunc CompletionFunc // Used to dynamically list member values, with a prefix for optimization
	IsArray        bool           // When true, argument becomes an array (must be in the final argument position)
}

func (*Argument) Apply

func (arg *Argument) Apply(inp string, namespace Namespace) error

Apply will apply the input to the target. If input is nil then the default will be applied

func (*Argument) ApplyArrayDefaults added in v0.2.2

func (arg *Argument) ApplyArrayDefaults(namespace Namespace)

ApplyArrayDefaults applies array defaults to the target if empty after processing

func (*Argument) ApplyDefault

func (arg *Argument) ApplyDefault(namespace Namespace)

ApplyDefault applies the default value to the target

func (*Argument) Usage

func (arg *Argument) Usage() string

Usage displays the usage pattern string

func (*Argument) Validate

func (arg *Argument) Validate(isLast bool) error

Validate ensures the validity of the argument

type Command

type Command struct {
	Name        string
	Group       string // If specified, group will be presented in the help and similar items will be displayed together
	Description string
	SubCommands []*Command

	// Commands which have subcommands cannot have any of the following
	Options            []*Option
	Arguments          []*Argument
	OnExecute          func(Namespace, *Processor) error
	OnCompleteOverride func(cmd *Command, tokens []any, processor *Processor) []*ns.AutoComplete
	// contains filtered or unexported fields
}

func (*Command) CompressTokens

func (cmd *Command) CompressTokens(tokens []any) ([]any, error)

CompressTokens compresses any token/value pairs where required into a single *Option.

func (*Command) DisplayHelp

func (cmd *Command) DisplayHelp()

DisplayHelp displays contextual help for the command

func (*Command) Execute

func (cmd *Command) Execute(tokens []any, processor *Processor, fromShell bool) error

Execute attempts to execute the supplied argument tokens after evaluating the input against the specified rules.

func (*Command) Fullname added in v0.1.6

func (cmd *Command) Fullname() string

Fullname returns the command include the parent command

func (*Command) OnComplete

func (cmd *Command) OnComplete(tokens []any, processor *Processor) []*ns.AutoComplete

func (*Command) Prepare

func (cmd *Command) Prepare() error

Prepare establishes the validity of the command as well as prepares various optimizations, and returns an error on the first validation violation

func (*Command) Process

func (cmd *Command) Process(cliArgs []string) error

Process processes the supplied cliArgs as though this were a standalone commmand. This is useful for processing arguments directly from the cli

type CompletionFunc

type CompletionFunc func(prefix string, processor *Processor) []string

type Namespace

type Namespace map[string]any

type Option

type Option struct {
	ShortName   byte
	Name        string
	Description string
	Type        ArgType
	Value       any // When value is specified, the option has an implicit value and cannot be provided with --opt=value
	Default     any
	IsArray     bool // When true, argument can be reused multiple times
	IsRequired  bool // When true a value is required to be set
}

func (*Option) Apply

func (opt *Option) Apply(inp *OptionInput, namespace Namespace) error

Apply will apply the input to the namespace. If input is nil then the default will be applied

func (*Option) ApplyArrayDefaults added in v0.2.0

func (opt *Option) ApplyArrayDefaults(namespace Namespace)

ApplyArrayDefaults applies array defaults to the target if empty after processing

func (*Option) ApplyDefault

func (opt *Option) ApplyDefault(namespace Namespace)

ApplyDefault applies the default value to the target

func (*Option) ArgTypeDisplay

func (opt *Option) ArgTypeDisplay() string

ArgTypeDisplay returns the argument data type for display

func (*Option) DefaultValueDisplay

func (opt *Option) DefaultValueDisplay() string

DefaultValueDisplay returns the default value for display purposes

func (*Option) InvocationDisplay

func (opt *Option) InvocationDisplay() string

InvocationDisplay returns the help name for the option

func (*Option) Validate

func (opt *Option) Validate() error

Validate ensures the validity of the option

type OptionInput

type OptionInput struct {
	Name  string
	Value string
}

type Processor

type Processor struct {
	DefaultHeading  string
	DisableBuiltins bool
	// contains filtered or unexported fields
}

func NewProcessor

func NewProcessor() *Processor

func (*Processor) AddCommand

func (p *Processor) AddCommand(cmd *Command) error

AddCommand adds a command to the processor. If the command is in some way invalid, an error will be returned here.

func (*Processor) AddCommands added in v0.1.6

func (p *Processor) AddCommands(cmds ...*Command) error

AddCommands adds several commands to the processor at once

func (*Processor) OnComplete

func (p *Processor) OnComplete(beforeAndCursor string, afterCursor string, full string) []*ns.AutoComplete

func (*Processor) OnExecute

func (p *Processor) OnExecute(nilShell *ns.NilShell, input string)

func (*Processor) Process

func (p *Processor) Process(cliArgs []string) error

Process processes the supplied cliArgs as though this were a standalone commmand. This is useful for processing arguments directly from the cli

func (*Processor) RemoveBuiltins added in v0.1.4

func (p *Processor) RemoveBuiltins(removeHelp bool)

RemoveBuiltins removes all builtin commands including the help command if specified

func (*Processor) Shell

func (p *Processor) Shell() *ns.NilShell

Shell returns the underlying NilShell instance

Directories

Path Synopsis
pkg
tg

Jump to

Keyboard shortcuts

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