redant

package module
v0.0.4 Latest Latest
Warning

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

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

README

Redant

Redant is a powerful Go CLI framework designed for building large CLI applications. It is based on the Cobra framework and provides more flexible option configuration, excellent default help output, and a middleware-based composition pattern.

Features

  • Command tree structure: Supports complex nested command structures, subcommands can inherit options from parent commands
  • Multi-source configuration: Options can be set from multiple sources including command line flags and environment variables
  • Middleware system: Middleware system based on Chi router pattern, facilitating feature extension
  • Excellent help system: Inspired by the help output style of Go toolchain
  • Easy to test: Clearly separates standard input/output, making unit tests easier to write
  • Colon-separated commands: Supports command:sub-cmd format command paths
  • Flexible parameter formats: Supports query string and form data parameter formats
  • Global flag system: Provides unified global flag management

Quick Start

Basic Usage
package main

import (
    "context"
    "fmt"
    "os"
    
    "github.com/pubgo/redant"
)

func main() {
    cmd := redant.Command{
        Use:   "echo <text>",
        Short: "Prints the given text to the console.",
        Handler: func(ctx context.Context, inv *redant.Invocation) error {
            if len(inv.Args) == 0 {
                return fmt.Errorf("missing text")
            }
            fmt.Fprintln(inv.Stdout, inv.Args[0])
            return nil
        },
    }

    err := cmd.Invoke().WithOS().Run()
    if err != nil {
        panic(err)
    }
}
Command with Options
package main

import (
    "context"
    "fmt"
    "os"
    "strings"
    
    "github.com/pubgo/redant"
)

func main() {
    var upper bool
    cmd := redant.Command{
        Use:   "echo <text>",
        Short: "Prints the given text to the console.",
        Options: redant.OptionSet{
            {
                Flag:        "upper",
                Description: "Prints the text in upper case.",
                Value:       redant.BoolOf(&upper),
            },
        },
        Args: redant.ArgSet{
            {},
        },
        Handler: func(ctx context.Context, inv *redant.Invocation) error {
            if len(inv.Args) == 0 {
                inv.Stderr.Write([]byte("error: missing text\n"))
                os.Exit(1)
            }

            text := inv.Args[0]
            if upper {
                text = strings.ToUpper(text)
            }

            inv.Stdout.Write([]byte(text))
            return nil
        },
    }

    err := cmd.Invoke().WithOS().Run()
    if err != nil {
        panic(err)
    }
}
Nested Commands
package main

import (
    "github.com/pubgo/redant"
)

func main() {
    rootCmd := &redant.Command{
        Use:   "app",
        Short: "An example app.",
    }
    
    subCmd := &redant.Command{
        Use:   "sub",
        Short: "A subcommand.",
    }
    
    rootCmd.Children = append(rootCmd.Children, subCmd)
    
    err := rootCmd.Invoke().WithOS().Run()
    if err != nil {
        panic(err)
    }
}

Parameter Formats

Redant supports multiple parameter formats:

  1. Positional parameters: command arg1 arg2 arg3
  2. Query string format: command "name=value&age=30"
  3. Form data format: command "name=value age=30"
  4. JSON format: command '{"name":"value","age":30}'

Middleware

Redant supports middleware pattern:

cmd := redant.Command{
    Use:   "echo <text>",
    Middleware: redant.Chain(
        redant.RequireNArgs(1),
        func(next redant.HandlerFunc) redant.HandlerFunc {
            return func(ctx context.Context, inv *redant.Invocation) error {
                // Log execution
                fmt.Printf("Executing command: %s\n", inv.Command.Name())
                return next(ctx, inv)
            }
        },
    ),
    Handler: func(ctx context.Context, inv *redant.Invocation) error {
        // ...
    },
}

Examples

For more examples, please check the example directory.

Documentation

For detailed design documentation, please check docs/DESIGN.md.

License

This project is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DiscardValue discardValue

DiscardValue does nothing but implements the pflag.Value interface. It's useful in cases where you want to accept an option, but access the underlying value directly instead of through the Option methods.

Functions

func ParseFormArgs

func ParseFormArgs(form string) (map[string][]string, error)

ParseFormArgs parses form formatted arguments into a map Format: key1=value1 key2=value2 key3="value with spaces" Values containing spaces should be quoted with single or double quotes

func ParseJSONArgs

func ParseJSONArgs(jsonStr string) (map[string][]string, error)

ParseJSONArgs parses JSON formatted arguments into a map JSON can be either an object like {"name":"value","age":18} or an array like ["value1","value2"]

func ParseQueryArgs

func ParseQueryArgs(query string) (map[string][]string, error)

ParseQueryArgs parses query string formatted arguments into a map

func PrintCommands

func PrintCommands(cmd *Command)

PrintCommands prints all commands in a formatted list with full paths, using help formatting style

func PrintFlags

func PrintFlags(rootCmd *Command)

PrintFlags prints all flags for all commands, using help formatting style

func Version

func Version() string

Types

type Arg

type Arg struct {
	Name        string `json:"name,omitempty"`
	Description string `json:"description,omitempty"`
	// Required means this value must be set by some means.
	// If `Default` is set, then `Required` is ignored.
	Required bool `json:"required,omitempty"`

	// Default is the default value for this argument.
	Default string `json:"default,omitempty"`

	// Value includes the types listed in values.go.
	// Used for type determination and automatic parsing.
	Value pflag.Value `json:"value,omitempty"`
}

type ArgSet

type ArgSet []Arg

type Bool

type Bool bool

func BoolOf

func BoolOf(b *bool) *Bool

func (*Bool) NoOptDefValue

func (*Bool) NoOptDefValue() string

func (*Bool) Set

func (b *Bool) Set(s string) error

func (Bool) String

func (b Bool) String() string

func (Bool) Type

func (Bool) Type() string

func (Bool) Value

func (b Bool) Value() bool

type Command

type Command struct {

	// Children is a list of direct descendants.
	Children []*Command

	// Use is provided in form "command [flags] [args...]".
	Use string

	// Aliases is a list of alternative names for the command.
	Aliases []string

	// Short is a one-line description of the command.
	Short string

	// Hidden determines whether the command should be hidden from help.
	Hidden bool

	// Deprecated indicates whether this command is deprecated.
	// If empty, the command is not deprecated.
	// If set, the value is used as the deprecation message.
	Deprecated string `json:"deprecated,omitempty"`

	// RawArgs determines whether the command should receive unparsed arguments.
	// No flags are parsed when set, and the command is responsible for parsing
	// its own flags.
	RawArgs bool

	// Long is a detailed description of the command,
	// presented on its help page. It may contain examples.
	Long    string
	Options OptionSet
	Args    ArgSet

	// Middleware is called before the Handler.
	// Use Chain() to combine multiple middlewares.
	Middleware MiddlewareFunc
	Handler    HandlerFunc
	// contains filtered or unexported fields
}

Command describes an executable command.

func (*Command) FullName

func (c *Command) FullName() string

FullName returns the full invocation name of the command, as seen on the command line.

func (*Command) FullOptions

func (c *Command) FullOptions() OptionSet

FullOptions returns the options of the command and its parents.

func (*Command) FullUsage

func (c *Command) FullUsage() string

func (*Command) GetGlobalFlags

func (c *Command) GetGlobalFlags() OptionSet

GetGlobalFlags returns the global flags from the root command All non-hidden options in the root command are considered global flags

func (*Command) Invoke

func (c *Command) Invoke(args ...string) *Invocation

Invoke creates a new invocation of the command, with stdio discarded.

The returned invocation is not live until Run() is called.

func (*Command) Name

func (c *Command) Name() string

Name returns the first word in the Use string.

func (*Command) Parent added in v0.0.3

func (c *Command) Parent() *Command

Parent returns the parent command of this command.

func (*Command) Run added in v0.0.2

func (c *Command) Run(ctx context.Context) error

type Duration

type Duration time.Duration

func DurationOf

func DurationOf(d *time.Duration) *Duration

func (*Duration) MarshalYAML

func (d *Duration) MarshalYAML() (any, error)

func (*Duration) Set

func (d *Duration) Set(v string) error

func (*Duration) String

func (d *Duration) String() string

func (Duration) Type

func (Duration) Type() string

func (*Duration) UnmarshalYAML

func (d *Duration) UnmarshalYAML(n *yaml.Node) error

func (*Duration) Value

func (d *Duration) Value() time.Duration

type Enum

type Enum struct {
	Choices []string
	Value   *string
}

func EnumOf

func EnumOf(v *string, choices ...string) *Enum

func (*Enum) MarshalYAML

func (e *Enum) MarshalYAML() (any, error)

func (*Enum) Set

func (e *Enum) Set(v string) error

func (*Enum) String

func (e *Enum) String() string

func (*Enum) Type

func (e *Enum) Type() string

func (*Enum) UnmarshalYAML

func (e *Enum) UnmarshalYAML(n *yaml.Node) error

type EnumArray

type EnumArray struct {
	Choices []string
	Value   *[]string
}

func EnumArrayOf

func EnumArrayOf(v *[]string, choices ...string) *EnumArray

func (*EnumArray) Append

func (e *EnumArray) Append(s string) error

func (*EnumArray) GetSlice

func (e *EnumArray) GetSlice() []string

func (*EnumArray) Replace

func (e *EnumArray) Replace(ss []string) error

func (*EnumArray) Set

func (e *EnumArray) Set(v string) error

func (*EnumArray) String

func (e *EnumArray) String() string

func (*EnumArray) Type

func (e *EnumArray) Type() string

type Float64

type Float64 float64

func Float64Of

func Float64Of(f *float64) *Float64

func (*Float64) Set

func (f *Float64) Set(s string) error

func (Float64) String

func (f Float64) String() string

func (Float64) Type

func (Float64) Type() string

func (Float64) Value

func (f Float64) Value() float64

type HandlerFunc

type HandlerFunc func(ctx context.Context, i *Invocation) error

HandlerFunc handles an Invocation of a command.

func DefaultHelpFn

func DefaultHelpFn() HandlerFunc

DefaultHelpFn returns a function that generates usage (help) output for a given command.

type HostPort

type HostPort struct {
	Host string
	Port string
}

HostPort is a host:port pair.

func (*HostPort) MarshalJSON

func (hp *HostPort) MarshalJSON() ([]byte, error)

func (*HostPort) MarshalYAML

func (hp *HostPort) MarshalYAML() (any, error)

func (*HostPort) Set

func (hp *HostPort) Set(v string) error

func (*HostPort) String

func (hp *HostPort) String() string

func (*HostPort) Type

func (*HostPort) Type() string

func (*HostPort) UnmarshalJSON

func (hp *HostPort) UnmarshalJSON(b []byte) error

func (*HostPort) UnmarshalYAML

func (hp *HostPort) UnmarshalYAML(n *yaml.Node) error

type Int64

type Int64 int64

func Int64Of

func Int64Of(i *int64) *Int64

func (*Int64) Set

func (i *Int64) Set(s string) error

func (Int64) String

func (i Int64) String() string

func (Int64) Type

func (Int64) Type() string

func (Int64) Value

func (i Int64) Value() int64

type Invocation

type Invocation struct {
	Command *Command
	Flags   *pflag.FlagSet

	// Args is reduced into the remaining arguments after parsing flags
	// during Run.
	Args []string

	Stdout io.Writer
	Stderr io.Writer
	Stdin  io.Reader

	// Annotations is a map of arbitrary annotations to attach to the invocation.
	Annotations map[string]any
	// contains filtered or unexported fields
}

Invocation represents an instance of a command being executed.

func (*Invocation) Context

func (inv *Invocation) Context() context.Context

func (*Invocation) CurWords

func (inv *Invocation) CurWords() (prev, cur string)

func (*Invocation) ParsedFlags

func (inv *Invocation) ParsedFlags() *pflag.FlagSet

func (*Invocation) Run

func (inv *Invocation) Run() (err error)

Run executes the command. If two command share a flag name, the first command wins.

func (*Invocation) SignalNotifyContext

func (inv *Invocation) SignalNotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)

SignalNotifyContext is equivalent to signal.NotifyContext, but supports being overridden in tests.

func (*Invocation) WithContext

func (inv *Invocation) WithContext(ctx context.Context) *Invocation

WithContext returns a copy of the Invocation with the given context.

func (*Invocation) WithOS

func (inv *Invocation) WithOS() *Invocation

WithOS returns the invocation as a main package, filling in the invocation's unset fields with OS defaults.

func (*Invocation) WithTestParsedFlags

func (inv *Invocation) WithTestParsedFlags(
	_ testing.TB,
	parsedFlags *pflag.FlagSet,
) *Invocation

func (*Invocation) WithTestSignalNotifyContext

func (inv *Invocation) WithTestSignalNotifyContext(
	_ testing.TB,
	f func(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc),
) *Invocation

WithTestSignalNotifyContext allows overriding the default implementation of SignalNotifyContext. This should only be used in testing.

type MiddlewareFunc

type MiddlewareFunc func(next HandlerFunc) HandlerFunc

MiddlewareFunc returns the next handler in the chain, or nil if there are no more.

func Chain

func Chain(ms ...MiddlewareFunc) MiddlewareFunc

Chain returns a Handler that first calls middleware in order.

func RequireNArgs

func RequireNArgs(want int) MiddlewareFunc

func RequireRangeArgs

func RequireRangeArgs(start, end int) MiddlewareFunc

RequireRangeArgs returns a Middleware that requires the number of arguments to be between start and end (inclusive). If end is -1, then the number of arguments must be at least start.

type NoOptDefValuer

type NoOptDefValuer interface {
	NoOptDefValue() string
}

NoOptDefValuer describes behavior when no option is passed into the flag.

This is useful for boolean or otherwise binary flags.

type Option

type Option struct {
	// Flag is the long name of the flag used to configure this option. If unset,
	// flag configuring is disabled. This also serves as the option's identifier.
	Flag string `json:"flag,omitempty"`

	Description string `json:"description,omitempty"`

	// Required means this value must be set by some means. It requires
	// `ValueSourceType != ValueSourceNone`
	// If `Default` is set, then `Required` is ignored.
	Required bool `json:"required,omitempty"`

	// Shorthand is the one-character shorthand for the flag. If unset, no
	// shorthand is used.
	Shorthand string `json:"shorthand,omitempty"`

	// Envs is a list of environment variables used to configure this option.
	// The first non-empty environment variable value will be used.
	// If unset, environment configuring is disabled.
	Envs []string `json:"env,omitempty"`

	// Default is parsed into Value if set.
	Default string `json:"default,omitempty"`

	// Value includes the types listed in values.go.
	Value pflag.Value `json:"value,omitempty"`

	Hidden bool `json:"hidden,omitempty"`

	Deprecated string

	Category string

	// Action is called after the flag is parsed and set.
	// It receives the flag value and can perform additional validation or side effects.
	// If Action returns an error, command execution will fail.
	Action func(val pflag.Value) error `json:"-"`
}

Option is a configuration option for a CLI application.

func (Option) Type added in v0.0.3

func (o Option) Type() string

Type returns the type of the option value

type OptionSet

type OptionSet []Option

OptionSet is a group of options that can be applied to a command.

func GlobalFlags

func GlobalFlags() OptionSet

GlobalFlags returns the default global flags that should be added to every command

func (*OptionSet) Add

func (optSet *OptionSet) Add(opts ...Option)

Add adds the given Options to the OptionSet.

func (*OptionSet) Filter

func (optSet *OptionSet) Filter(filter func(opt Option) bool) OptionSet

Filter will only return options that match the given filter. (return true)

func (*OptionSet) FlagSet

func (optSet *OptionSet) FlagSet(name string) *pflag.FlagSet

type Regexp

type Regexp regexp.Regexp

func (*Regexp) MarshalJSON

func (r *Regexp) MarshalJSON() ([]byte, error)

func (*Regexp) MarshalYAML

func (r *Regexp) MarshalYAML() (any, error)

func (*Regexp) Set

func (r *Regexp) Set(v string) error

func (Regexp) String

func (r Regexp) String() string

func (Regexp) Type

func (Regexp) Type() string

func (*Regexp) UnmarshalJSON

func (r *Regexp) UnmarshalJSON(data []byte) error

func (*Regexp) UnmarshalYAML

func (r *Regexp) UnmarshalYAML(n *yaml.Node) error

func (*Regexp) Value

func (r *Regexp) Value() *regexp.Regexp

type RunCommandError

type RunCommandError struct {
	Cmd *Command
	Err error
}

func (*RunCommandError) Error

func (e *RunCommandError) Error() string

func (*RunCommandError) Unwrap

func (e *RunCommandError) Unwrap() error

type String

type String string

func StringOf

func StringOf(s *string) *String

func (*String) NoOptDefValue

func (*String) NoOptDefValue() string

func (*String) Set

func (s *String) Set(v string) error

func (String) String

func (s String) String() string

func (String) Type

func (String) Type() string

func (String) Value

func (s String) Value() string

type StringArray

type StringArray []string

StringArray is a slice of strings that implements pflag.Value and pflag.SliceValue.

func StringArrayOf

func StringArrayOf(ss *[]string) *StringArray

func (*StringArray) Append

func (s *StringArray) Append(v string) error

func (*StringArray) GetSlice

func (s *StringArray) GetSlice() []string

func (*StringArray) Replace

func (s *StringArray) Replace(vals []string) error

func (*StringArray) Set

func (s *StringArray) Set(v string) error

func (StringArray) String

func (s StringArray) String() string

func (StringArray) Type

func (StringArray) Type() string

func (StringArray) Value

func (s StringArray) Value() []string

type Struct

type Struct[T any] struct {
	Value T
}

Struct is a special value type that encodes an arbitrary struct. It implements the flag.Value interface, but in general these values should only be accepted via config for ergonomics.

The string encoding type is YAML.

func (*Struct[T]) MarshalJSON

func (s *Struct[T]) MarshalJSON() ([]byte, error)

nolint:revive

func (*Struct[T]) MarshalYAML

func (s *Struct[T]) MarshalYAML() (any, error)

nolint:revive

func (*Struct[T]) Set

func (s *Struct[T]) Set(v string) error

func (*Struct[T]) String

func (s *Struct[T]) String() string

func (*Struct[T]) Type

func (s *Struct[T]) Type() string

func (*Struct[T]) UnmarshalJSON

func (s *Struct[T]) UnmarshalJSON(b []byte) error

nolint:revive

func (*Struct[T]) UnmarshalYAML

func (s *Struct[T]) UnmarshalYAML(n *yaml.Node) error

nolint:revive

type URL

type URL url.URL

func URLOf

func URLOf(u *url.URL) *URL

func (*URL) MarshalJSON

func (u *URL) MarshalJSON() ([]byte, error)

func (*URL) MarshalYAML

func (u *URL) MarshalYAML() (any, error)

func (*URL) Set

func (u *URL) Set(v string) error

func (*URL) String

func (u *URL) String() string

func (*URL) Type

func (*URL) Type() string

func (*URL) UnmarshalJSON

func (u *URL) UnmarshalJSON(b []byte) error

func (*URL) UnmarshalYAML

func (u *URL) UnmarshalYAML(n *yaml.Node) error

func (*URL) Value

func (u *URL) Value() *url.URL

type UnknownSubcommandError

type UnknownSubcommandError struct {
	Args []string
}

func (*UnknownSubcommandError) Error

func (e *UnknownSubcommandError) Error() string

type Validator

type Validator[T pflag.Value] struct {
	Value T
	// contains filtered or unexported fields
}

Validator is a wrapper around a pflag.Value that allows for validation of the value after or before it has been set.

func Validate

func Validate[T pflag.Value](opt T, validate func(value T) error) *Validator[T]

func (*Validator[T]) MarshalJSON

func (i *Validator[T]) MarshalJSON() ([]byte, error)

func (*Validator[T]) MarshalYAML

func (i *Validator[T]) MarshalYAML() (any, error)

func (*Validator[T]) Set

func (i *Validator[T]) Set(input string) error

func (*Validator[T]) String

func (i *Validator[T]) String() string

func (*Validator[T]) Type

func (i *Validator[T]) Type() string

func (*Validator[T]) Underlying

func (i *Validator[T]) Underlying() pflag.Value

func (*Validator[T]) UnmarshalJSON

func (i *Validator[T]) UnmarshalJSON(b []byte) error

func (*Validator[T]) UnmarshalYAML

func (i *Validator[T]) UnmarshalYAML(n *yaml.Node) error

Directories

Path Synopsis
cmds
example
args-test command
demo command
echo command
env-test command
fastcommit command
globalflags command
queryargs command

Jump to

Keyboard shortcuts

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