redant

package module
v0.0.7-alpha.1 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 32 Imported by: 25

README

Redant 命令行框架

Redant 是一个用于构建大型 Go 命令行程序的框架,提供命令树、选项系统、中间件链、帮助系统与多格式参数解析能力。

文档导航

README 仅保留“快速上手 + 能力入口”。详细设计与流程请跳转:

核心能力

  • 命令树与子命令继承(支持嵌套)
  • 选项多来源配置(命令行、环境变量、默认值)
  • 中间件链式编排
  • 自动帮助信息与全局标志
  • 多格式参数解析(位置参数、查询串、表单、JSON)
  • Busybox 风格 argv0 调度(软链接命令入口)
  • MCP 工具暴露(将命令树映射为 Model Context Protocol Tools)
  • Web 控制台(web 子命令):可视化选择命令、填写 Flags/Args、查看调用过程与执行结果

快速开始

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/pubgo/redant"
)

func main() {
    cmd := redant.Command{
        Use:   "echo <text>",
        Short: "输出传入文本",
        Handler: func(ctx context.Context, inv *redant.Invocation) error {
            if len(inv.Args) == 0 {
                return fmt.Errorf("缺少文本参数")
            }
            fmt.Fprintln(inv.Stdout, inv.Args[0])
            return nil
        },
    }

    if err := cmd.Invoke().WithOS().Run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

常用能力速览

参数与标志
  • 子命令支持空格路径与冒号路径(如 app repo commit / app repo:commit)。
  • 参数支持位置参数、query、form、JSON 四种形态。
  • 推荐写法:app <command> [flags...] [args...]

常用全局标志:

  • --help, -h
  • --list-commands
  • --list-flags
  • --env, -e KEY=VALUE
  • --env-file FILE
  • --args VALUE(内部隐藏,用于覆盖位置参数)

详细解析规则见:docs/USAGE_AT_A_GLANCE.md

Web 调试界面
app web
app web --addr 127.0.0.1:18080 --open=false

Web 控制台支持可视化填写 flags/args,并展示 curl 与多行 CLI 调用过程。更多说明见:docs/USAGE_AT_A_GLANCE.md

MCP 集成
app mcp list
app mcp list --format text
app mcp serve --transport stdio

MCP 输入/输出协议、Schema 规则与排查建议见:docs/MCP.md

示例目录

  • example/demo:综合示例
  • example/echo:最小命令示例
  • example/env-test:环境变量示例
  • example/globalflags:全局标志示例
  • example/args-test:参数解析示例

开发与维护

许可证

本项目采用 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, inv *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

	// Arg0 is the executable name used to invoke the program (typically os.Args[0]).
	// It enables busybox-style dispatch where the binary name maps directly to
	// a subcommand.
	Arg0 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) WithArgv0 added in v0.0.6

func (inv *Invocation) WithArgv0(arg0 string) *Invocation

WithArgv0 overrides the executable name used for busybox-style dispatch. This is primarily useful for testing or when simulating invocation via symlinked binaries.

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
internal

Jump to

Keyboard shortcuts

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