cliutil

package
v0.0.0-...-5681d2b Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2025 License: MIT Imports: 15 Imported by: 0

README

cliutil Package

The cliutil package provides a comprehensive command-line interface framework for the Scout MCP server. It offers a structured approach to building CLI commands with argument parsing, flag handling, help systems, and output abstraction.

Overview

This package implements a command-based CLI architecture that separates I/O concerns from business logic, making commands easily testable and maintainable. The framework supports nested command structures, comprehensive help systems, and flexible output management.

Key Components

Command Framework
  • CmdBase: Base command structure with common functionality
  • CmdRunner: Command execution and routing logic
  • Commands: Global command registry and management
Argument and Flag Processing
  • ArgDef: Argument definition and validation
  • FlagDef: Flag definition and parsing
  • FlagSet: Collection management for multiple flags
I/O Abstraction
  • Output: Flexible output handling for CLI and testing
  • Terminal: Terminal interaction and formatting utilities
Utilities
  • Config: Configuration management for CLI applications
  • Logger: Logging integration for CLI operations
  • Util: Common utility functions and helpers

Architecture

The cliutil package follows a "Clear Path" coding style with:

  • Single return points per function
  • Minimal nesting through helper functions
  • Comprehensive error handling
  • Separation of I/O from business logic
I/O Separation

The package maintains clear separation between:

  • MCP Protocol I/O: Communication with Claude Desktop via stdio
  • CLI User Output: User-facing command output and help text

This separation enables comprehensive testing and prevents interference between protocol communication and user interface elements.

Usage

Commands are typically defined by embedding CmdBase and implementing the command interface:

type MyCommand struct {
    *cliutil.CmdBase
}

func (c *MyCommand) Handle(ctx context.Context, args *cliutil.RunArgs) error {
    // Command implementation
    return nil
}

The framework handles argument parsing, validation, and routing automatically based on command definitions and flag configurations.

Testing

The package includes comprehensive testing utilities:

  • Mock output writers for capturing command output
  • Test helpers for command execution
  • Fixture management for test scenarios

Dependencies

  • Standard library packages for core functionality
  • Internal Scout packages for logging and utilities
  • Third-party libraries for enhanced CLI features

Documentation

Index

Constants

View Source
const (
	NoResponse     = 'n'
	YesResponse    = 'y'
	AllResponse    = 'a'
	DelayResponse  = 'd'
	CancelResponse = 'c'
)

Variables

This section is empty.

Functions

func BuildCommandTree

func BuildCommandTree() (err error)

BuildCommandTree builds the command hierarchy from registrations This should be called by gmover.Initialize() after all init() functions complete

func Errorf

func Errorf(format string, args ...interface{})

Errorf writes formatted error output

func Initialize

func Initialize(w OutputWriter) (err error)

func IsTerminalError

func IsTerminalError(err error) (isTermErr bool)

IsTerminalError checks if an error is related to terminal/input operations These errors should abort the entire operation rather than continue

func Printf

func Printf(format string, args ...interface{})

Printf writes formatted output

func RegisterCommand

func RegisterCommand(cmd Command, parents ...Command)

RegisterCommand registers a command with optional parent type declarations First argument is the actual command, remaining arguments are parent type prototypes Example: RegisterCommand(&JobRunCmd{...}, &JobCmd{})

func SetLogger

func SetLogger(l *slog.Logger)

SetLogger sets the slog.Logger to use

func ShowCmdHelp

func ShowCmdHelp(cmdName string) (err error)

ShowCmdHelp displays help for a specific command

func ShowMainHelp

func ShowMainHelp() (err error)

ShowMainHelp displays the main help screen

func ValidateCmds

func ValidateCmds() (err error)

ValidateCmds ensures all registered commands have handlers

func ValidateCommands

func ValidateCommands() (err error)

Types

type ApprovalFunc

type ApprovalFunc = func(context.Context, string) (ar ApprovalResponse, err error)

ApprovalFunc is called before moving each message Returns: approved (move this message), approveAll (auto-approve remaining), error Context allows cancellation via Ctrl-C

type ApprovalResponse

type ApprovalResponse = byte

func PromptForApproval

func PromptForApproval(ctx context.Context, prompt string) (ar ApprovalResponse, err error)

type ArgDef

type ArgDef struct {
	Name     string
	Usage    string
	Required bool
	String   *string // Where to assign the argument value
}

ArgDef defines a positional command argument

type CmdArgs

type CmdArgs struct {
	Name        string
	Usage       string
	Description string
	DelegateTo  Command
	FlagDefs    []FlagDef  // Legacy flag definitions (will be deprecated)
	FlagSets    []*FlagSet // New FlagSet-based approach
	ArgDefs     []*ArgDef  // Positional argument definitions
}

type CmdBase

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

CmdBase provides common functionality for all commands It implements the cliutil.Cmd interface

func NewCmdBase

func NewCmdBase(args CmdArgs) *CmdBase

NewCmdBase creates a new command base

func (*CmdBase) AddParent

func (c *CmdBase) AddParent(r reflect.Type)

func (*CmdBase) AddSubCommand

func (c *CmdBase) AddSubCommand(cmd Command)

AddSubCommand returns the subcommands map

func (*CmdBase) AssignArgs

func (c *CmdBase) AssignArgs(args []string) (err error)

AssignArgs assigns positional arguments to their defined config fields

func (*CmdBase) DelegateTo

func (c *CmdBase) DelegateTo() Command

DelegateTo returns the command to delegate to, if any

func (*CmdBase) Description

func (c *CmdBase) Description() string

Description returns the command description with flag details

func (*CmdBase) FlagSets

func (c *CmdBase) FlagSets() []*FlagSet

func (*CmdBase) FullNames

func (c *CmdBase) FullNames() (names []string)

FullNames returns the command names prefixed with any parent names

func (*CmdBase) Name

func (c *CmdBase) Name() string

Name returns the command name

func (*CmdBase) ParentTypes

func (c *CmdBase) ParentTypes() []reflect.Type

func (*CmdBase) ParseFlagSets

func (c *CmdBase) ParseFlagSets(args []string, _ Config) (remainingArgs []string, err error)

ParseFlagSets parses flags using the new FlagSet-based approach

func (*CmdBase) SetDelegateTo

func (c *CmdBase) SetDelegateTo(cmd Command)

SetDelegateTo sets the command to delegate to

func (*CmdBase) Usage

func (c *CmdBase) Usage() string

Usage returns the command usage string with flags

type CmdRunner

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

func NewCmdRunner

func NewCmdRunner(args CmdRunnerArgs) *CmdRunner

func (CmdRunner) Run

func (cr CmdRunner) Run(ctx context.Context) (err error)

type CmdRunnerArgs

type CmdRunnerArgs struct {
	Config        Config
	GlobalFlagSet *FlagSet
	Args          []string
}

type Command

type Command interface {
	Name() string
	FullNames() []string
	Usage() string
	Description() string
	AddSubCommand(Command)
	DelegateTo() Command
	AddParent(reflect.Type)
	ParentTypes() []reflect.Type
	FlagSets() []*FlagSet
	ParseFlagSets([]string, Config) ([]string, error)
	AssignArgs([]string) error
}

Command interface for basic command metadata and delegation

func GetDefaultCommand

func GetDefaultCommand(path string, args []string) (cmd Command, _ string)

GetDefaultCommand retrieves a command or its default at any depth using dot notation

func GetExactCommand

func GetExactCommand(path string) Command

GetExactCommand retrieves a command at any depth using dot notation

func GetSubCmds

func GetSubCmds(path string) []Command

GetSubCmds returns all subcommands for a given path

func GetTopLevelCmds

func GetTopLevelCmds() []Command

GetTopLevelCmds returns all top-level commands sorted by name

type CommandHandler

type CommandHandler interface {
	Command
	Handle(context.Context, Config, []string) error
}

CommandHandler interface for commands that actually execute logic

type Config

type Config interface {
	Config()
}

type FlagDef

type FlagDef struct {
	Name           string
	Default        any
	Usage          string
	Required       bool
	Regex          *regexp.Regexp
	ValidationFunc ValidationFunc
	String         *string
	Bool           *bool
	Int64          *int64
}

FlagDef defines a command flag declaratively

func (*FlagDef) SetValue

func (fd *FlagDef) SetValue(value any)

func (*FlagDef) Type

func (fd *FlagDef) Type() (ft FlagType)

func (*FlagDef) ValidateValue

func (fd *FlagDef) ValidateValue(value any) error

ValidateValue validates the flag value using the defined validation rules

type FlagSet

type FlagSet struct {
	Name     string
	FlagSet  *flag.FlagSet
	FlagDefs []FlagDef
	Values   map[string]any
}

FlagSet combines a FlagSet with automatic config binding

func (*FlagSet) Assign

func (fs *FlagSet) Assign() (err error)

func (*FlagSet) Build

func (fs *FlagSet) Build() (err error)

func (*FlagSet) FlagNames

func (fs *FlagSet) FlagNames() (names []string)

func (*FlagSet) Parse

func (fs *FlagSet) Parse(args []string) (remainingArgs []string, err error)

Parse extracts flags and returns remaining args

func (*FlagSet) Validate

func (fs *FlagSet) Validate() (err error)

Validate validates all flag values using their defined validation rules

type FlagType

type FlagType int

FlagType represents the type of a command flag

const (
	UnknownFlagType FlagType = iota
	StringFlag
	BoolFlag
	Int64Flag
)

type GlobalFlagDefGetter

type GlobalFlagDefGetter interface {
	GlobalFlagDefs() []FlagDef
}

type NULL

type NULL = struct{}

type OutputWriter

type OutputWriter interface {
	Printf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
}

OutputWriter defines the interface for user-facing output

func GetOutput

func GetOutput() OutputWriter

GetOutput returns the current output writer

func NewOutputWriter

func NewOutputWriter() OutputWriter

NewOutputWriter creates a console output writer

func SetOutput

func SetOutput(writer OutputWriter) OutputWriter

SetOutput sets the global output writer (primarily for testing)

type ValidationFunc

type ValidationFunc func(value any) error

ValidationFunc validates a flag value and returns an error if invalid

Jump to

Keyboard shortcuts

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