gocli

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2022 License: MIT Imports: 20 Imported by: 0

README

gocli

golang终端命令工具(可插件式加载指令)

//todo

Documentation

Index

Constants

View Source
const ExportPlugin = "Plugin"

Variables

View Source
var (
	LogFlag   = NewFlag("logf", "-logf ./app.log 指定日志文件")
	UiFlag    = NewFlag("ui", "程序启用GUI,输入指令会忽略")
	PluginDir = NewFlag("pdir", "-pdir {dir} 添加插件目录,可多个")
	LogFLevel = NewFlag("logl", "-logl {0-5} 日志输出级别(0-5)对应 debug-error")
	WorkDir   = NewFlag("wdir", "-wdir 指定工作目录")
	CheckSum  = NewFlag("check", "-check") //验证插件签名
)
View Source
var DefaultDateFormatter = "20060102.15:04:05.999"
View Source
var NotImplementsMessage = NewMessage(0, "该功能还没实现", LOG_WARN)

Functions

func DirEnsure

func DirEnsure(dest string, create bool) (abspath string, created bool, err error)

func FirstNoneNilResult

func FirstNoneNilResult[T any](values ...T) T

func ParseFlag

func ParseFlag[T any](fm FlagMap, f Flag) (T, bool)

func ParseInputArgs

func ParseInputArgs(args []string) (Args, FlagMap)

func ParseLine

func ParseLine(input string) (Args, FlagMap)

func RenderPluginFile

func RenderPluginFile(bean *PluginBean, dest string) (err error)

func SplitLines

func SplitLines(txt string, width int, indent int, firstIndent bool) (fmtstr string)

Types

type AlignField

type AlignField struct {
	Content    string
	AlignWidth int
	Padding    PaddingType
	// contains filtered or unexported fields
}

func (*AlignField) Indent

func (field *AlignField) Indent(indent int) *AlignField

func (*AlignField) NewLine

func (field *AlignField) NewLine() *AlignField

func (*AlignField) SplitFixedWidthLine

func (field *AlignField) SplitFixedWidthLine(width int, indent int, firstIndent bool) *AlignField

func (*AlignField) SplitLine

func (field *AlignField) SplitLine(indent int, firstIndent bool) *AlignField

func (*AlignField) WriteAppend

func (field *AlignField) WriteAppend(w io.Writer)

type AlignWriter

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

func NewAlignWriter

func NewAlignWriter() *AlignWriter

func ScreenAlignWriter

func ScreenAlignWriter(screenWidth int) *AlignWriter

func (*AlignWriter) AlignAppend

func (aw *AlignWriter) AlignAppend(content string, width int, pad PaddingType) *AlignField

func (*AlignWriter) LeftPaddingAppend

func (aw *AlignWriter) LeftPaddingAppend(context string) *AlignField

func (*AlignWriter) MaskString

func (aw *AlignWriter) MaskString(align int, endln bool) string

func (*AlignWriter) MaskWirte

func (aw *AlignWriter) MaskWirte(align int, writer io.Writer)

func (*AlignWriter) NopaddingAppend

func (aw *AlignWriter) NopaddingAppend(context string) *AlignField

func (*AlignWriter) RightPaddingAppend

func (aw *AlignWriter) RightPaddingAppend(context string) *AlignField

type Args

type Args = []string

func MergeFlagMap

func MergeFlagMap(args []string, fmap FlagMap) Args

type BootStrap

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

func CLI

func CLI() *BootStrap

func (*BootStrap) Run

func (boot *BootStrap) Run(args []string) Message

type Command

type Command interface {
	Key() string
	Usage() string
	Run(ctx Context, args []string, flagmap FlagMap) Message
	Flags() []Flag
}

func NewCommand

func NewCommand(key string, usage string, do ExecFunc) Command

func NewFlagsCommand

func NewFlagsCommand(key string, usage string, do ExecFunc, flags ...Flag) Command

func NewRootCommand

func NewRootCommand(key string, usage string) Command

type CommandInputs

type CommandInputs struct {
	Args  Args
	Flags FlagMap
}

type CommandVisitor

type CommandVisitor = func(key string, command map[string]Command) (next bool)

type Console

type Console interface {
	//文件logger,如过没有设置,则使用指定文件记录日志
	Log() (Log, bool)
	Std() StandConsole
	//只在终端输出
	StandConsole
}

控制台打印

func NewConsole

func NewConsole(term io.Writer, logf *Logger) Console

type Context

type Context interface {
	Value(key any) any
	Interupt() bool
	WorkDir() string
	RegisteredPlugins() PluginVersionMap
	StdConsole() StandConsole
	Logger() (logger Log, enable bool)
	ValueOperator
}

func MockContext

func MockContext() Context

type ContextKey

type ContextKey = string

type ExecFunc

type ExecFunc = func(ctx Context, args []string, flagmap FlagMap) Message

func BuildRun

func BuildRun(exec ExecFunc, inputRules []InputValidator, paramRules ...ParamValiator) ExecFunc

type FParser

type FParser[T any] interface {
	Parse(args Args) (T, bool)
}

type Flag

type Flag interface {
	Name() string
	Alias() (string, bool)
	Usage() string
}

func BuildFlag

func BuildFlag[T any](name string, alias string, parser FlagParser[T]) Flag

func NewFlag

func NewFlag(nameUsageAlias ...string) Flag

type FlagExpected

type FlagExpected struct {
	Flag      Flag
	Required  bool
	Validator FlagValidator
	ErrMsg    Message
	DefVal    any
}

type FlagInputs

type FlagInputs = CommandInputs

type FlagMap

type FlagMap interface {
	GetString(key string) (v string, found bool)
	GetStrings(key string) (v Args, found bool)
	GetBool(key string) (v bool, found bool)
	GetInt(key string) (v int, found bool)
	Set(key string, values ...string)
	HasFlag(flag Flag) (Args, bool)
	Empty() bool
	// contains filtered or unexported methods
}

func NewFMap

func NewFMap(args []string) FlagMap

func NewFlagMap

func NewFlagMap() FlagMap

type FlagParser

type FlagParser[T any] func(args Args) (T, bool)

type FlagValidator

type FlagValidator = Validator[*FlagInputs]

type GeneralPlugin

type GeneralPlugin struct {
	ID       string
	Desc     string
	Ver      string
	Init     LifeHook
	PreRun   LifeHook
	Commands []Command
	Help     HelperFunc
}

func (*GeneralPlugin) BeforeRun

func (gp *GeneralPlugin) BeforeRun(ctx Context) error

func (*GeneralPlugin) Helper

func (gp *GeneralPlugin) Helper() HelperFunc

func (*GeneralPlugin) Name

func (gp *GeneralPlugin) Name() string

func (*GeneralPlugin) Registry

func (gp *GeneralPlugin) Registry() []Command

func (*GeneralPlugin) Setup

func (gp *GeneralPlugin) Setup(ctx Context) error

func (*GeneralPlugin) Usage

func (gp *GeneralPlugin) Usage() string

func (*GeneralPlugin) Version

func (gp *GeneralPlugin) Version() string

type HelperFunc

type HelperFunc = func() string

type InputValidRule

type InputValidRule = func(ctx Context, args []string, flags FlagMap) (bool, Message)

type InputValidator

type InputValidator = Validator[*CommandInputs]

func InputRules

func InputRules(rules ...InputValidator) []InputValidator

func NewInputValidRule

func NewInputValidRule(rule InputValidRule, fail Message) InputValidator

type LifeHook

type LifeHook = func(ctx Context) error

type LoadedPlugin

type LoadedPlugin struct {
	File     string
	Digest   string
	Verified bool
	Plugin
}

func LoadPlugin

func LoadPlugin(dirs []string, console Log) ([]*LoadedPlugin, int)

type Log

type Log interface {
	NewLogger(file string) Log
	StandConsole
}

type LogLevel

type LogLevel = int
const (
	LOG_DEBUG LogLevel = iota
	LOG_INFO
	LOG_SUCC
	LOG_WARN
	LOG_ERROR
)

type Logger

type Logger struct {
	Max     int64
	RStrage int
	// contains filtered or unexported fields
}

func NewDatePatternLogger

func NewDatePatternLogger(file string) *Logger

func NewLogger

func NewLogger(file string) *Logger

func NewParialLogger

func NewParialLogger(file string, maxMB int) *Logger

maxSize不低于2MB

func (*Logger) NFile

func (log *Logger) NFile(f string) *Logger

func (*Logger) PrependPrefix

func (log *Logger) PrependPrefix(values ...Prefix)

func (*Logger) PrependPrefixString

func (log *Logger) PrependPrefixString(values ...string)

func (*Logger) Write

func (log *Logger) Write(p []byte) (n int, err error)

type Message

type Message interface {
	// code < 0 程序应该中断
	Code() int
	Kind() int
	Msg() string
	Err() (error, bool)
}

func DebugMessage

func DebugMessage(code int, msg string, msgargs ...any) Message

func ErrMessage

func ErrMessage(code int, msg string, msgargs ...any) Message

func InfoMessage

func InfoMessage(code int, msg string, msgargs ...any) Message

func InteruptMessage

func InteruptMessage(msg string) Message

func NewMessage

func NewMessage(code int, msg string, kind int, msgargs ...any) Message

func NothingDo

func NothingDo(ctx Context, args []string, flagmap FlagMap) (msg Message)

func SuccMessage

func SuccMessage(code int, msg string, msgargs ...any) Message

func WarnMessage

func WarnMessage(code int, msg string, msgargs ...any) Message

type PaddingType

type PaddingType = int
const (
	SPLIT_LINE_WIDTH             = 140
	INDENT_NOLIMIT               = -1
	NONE_PADDING     PaddingType = iota
	RIGHT_PADDING
	LEFT_PADDING
)

type ParamRule

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

func (*ParamRule) Index

func (vp *ParamRule) Index() int

func (*ParamRule) Valid

func (vp *ParamRule) Valid(ctx Context, value string) (bool, Message)

type ParamValiator

type ParamValiator = ParamValidator[string]

func ParamRules

func ParamRules(rules ...ParamValiator) []ParamValiator

func ValidAllParam

func ValidAllParam(rule ParamValidRule) ParamValiator

func ValidParam

func ValidParam(index uint, rule ParamValidRule) ParamValiator

type ParamValidRule

type ParamValidRule = func(ctx Context, val string) (bool, Message)

type ParamValidator

type ParamValidator[T any] interface {
	// 返回值小于0,实用所有参数
	Index() int
	Validator[T]
}

type Plugin

type Plugin interface {
	Name() string
	Usage() string
	Version() string
	Setup(ctx Context) error
	//boot run 前检查
	BeforeRun(ctx Context) error
	Registry() []Command
	//all custom plugin's commands help info
	Helper() HelperFunc
}

type PluginBean

type PluginBean struct {
	Name       string
	Version    string
	ExportType string
	Usage      string
}

type PluginBundle

type PluginBundle interface {
	Version() string
	Name() string
	Md5() string
	File() string
	Dependencies() []PluginBundle
}

type PluginContext

type PluginContext interface {
	Context
	// contains filtered or unexported methods
}

func NewPContext

func NewPContext(ctx Context, ptr unsafe.Pointer) PluginContext

func NewPluginContext

func NewPluginContext(ctx Context, plugin Plugin) PluginContext

type PluginVersionMap

type PluginVersionMap = map[string]PluginBundle

key plugin name value plugin version

type PluginVisitor

type PluginVisitor = func(key string, plugins map[string]*RegisteredPlugin) (next bool)

type Prefix

type Prefix = func() string

type RegisteredCommand

type RegisteredCommand struct {
	From        unsafe.Pointer
	SubCommands SubCommand

	Command
	// contains filtered or unexported fields
}

func NewRegistryCommand

func NewRegistryCommand(ptr unsafe.Pointer, c Command) *RegisteredCommand

func NewRootRegistry

func NewRootRegistry(from unsafe.Pointer, key string) *RegisteredCommand

func (*RegisteredCommand) AddSub

func (c *RegisteredCommand) AddSub(ptr unsafe.Pointer, cmd Command) (add *RegisteredCommand, ok bool, err error)

func (*RegisteredCommand) AppendSub

func (c *RegisteredCommand) AppendSub(sub *RegisteredCommand) (ok bool, err error)

func (*RegisteredCommand) Children

func (c *RegisteredCommand) Children() (children []*RegisteredCommand, maxL int)

func (*RegisteredCommand) Flags

func (c *RegisteredCommand) Flags() []Flag

func (*RegisteredCommand) HasSub

func (c *RegisteredCommand) HasSub() (sub SubCommand, has bool)

func (*RegisteredCommand) Key

func (c *RegisteredCommand) Key() string

func (*RegisteredCommand) Range

func (*RegisteredCommand) RootCommand

func (c *RegisteredCommand) RootCommand(cmd Command)

func (*RegisteredCommand) Run

func (c *RegisteredCommand) Run(ctx Context, args []string, flagmap FlagMap) Message

func (*RegisteredCommand) SetSubs

func (c *RegisteredCommand) SetSubs(subs ...*RegisteredCommand)

func (*RegisteredCommand) Usage

func (c *RegisteredCommand) Usage() string

type RegisteredCommandVisitor

type RegisteredCommandVisitor = RootCommandVisitor

type RegisteredPlugin

type RegisteredPlugin struct {
	Plugin
	// contains filtered or unexported fields
}

func (*RegisteredPlugin) Append

func (rp *RegisteredPlugin) Append(c *RegisteredCommand) error

func (*RegisteredPlugin) Commands

func (rp *RegisteredPlugin) Commands() (commands []*RegisteredCommand, maxL int)

func (*RegisteredPlugin) Installed

func (rp *RegisteredPlugin) Installed()

type Registry

type Registry interface {
	RootCommand(key string) (RegisteredCommand, bool)
	// root command key max len
	RootKeyMaxLen() (int, bool)
	//支持 root command ,和subcommand
	Command(args []string) (RegisteredCommand, bool)
	CommandKeyMaxLen() (int, bool)
	Plugin(name string) (RegisteredPlugin, bool)
	FindPlugin(plugin Plugin) (RegisteredPlugin, bool)
	RegisterCommand(p Plugin, cmds ...Command) (ok bool, err error)
	RegisterPlugins(plugins ...Plugin)
	RangeRootCommand(RootCommandVisitor)
	RangePlugin(PluginVisitor)
	Finish(panicunfinished bool) (loaded int, failed int)
	Logger(log Log)
}

func NewRegistry

func NewRegistry() Registry

type RegistryCommands

type RegistryCommands []*RegisteredCommand

func (RegistryCommands) Len

func (g RegistryCommands) Len() int

func (RegistryCommands) Less

func (g RegistryCommands) Less(i, j int) bool

func (RegistryCommands) Swap

func (g RegistryCommands) Swap(i, j int)

type RootCommandVisitor

type RootCommandVisitor = func(key string, roots map[string]*RegisteredCommand) (next bool)

type RotateStrage

type RotateStrage = int
const (
	NONE RotateStrage = iota
	PARTIAL_NUMBER
	DATE_PATTERN
)

type ShortAction

type ShortAction = int
const (
	ActionExec ShortAction = iota
	ActionInput
)

type ShortCommand

type ShortCommand struct {
	Command string
	Action  ShortAction
	*ShortKey
}

type ShortCutCommands

type ShortCutCommands = []ShortCommand

func DefaultShortCut

func DefaultShortCut(custom ShortCutCommands) (ShortCutCommands, map[ShortCutKey]int)

type ShortCutKey

type ShortCutKey = int
const (
	KeyAlt1 ShortCutKey = 161
	KeyAlt2 ShortCutKey = 8482
	KeyAlt3 ShortCutKey = 163
	KeyAlt4 ShortCutKey = 162
	KeyAlt5 ShortCutKey = 8734
	KeyAlt6 ShortCutKey = 167
	KeyAlt7 ShortCutKey = 182
	KeyAlt8 ShortCutKey = 8226
	KeyAlt9 ShortCutKey = 170
	KeyAlt0 ShortCutKey = 186
	KeyAltW ShortCutKey = 8721 // clean console
)

type ShortKey

type ShortKey struct {
	Key   ShortCutKey
	Title string
}

func NewShortKey

func NewShortKey(key ShortCutKey) *ShortKey

type StandConsole

type StandConsole interface {
	Err(emsg string, args ...any)
	WError(err error)
	Warn(msg string, args ...any)
	Info(msg string, args ...any)
	Succ(msg string, args ...any)
	Debug(msg string, args ...any)
	Msg(msg Message)
	Level(level LogLevel)
	Prefix(prefix string, args ...any) Console
	AppendPrefix(prefix string, args ...any) Console
	PrependPrefix(prefix string, args ...any) Console
}

type SubCommand

type SubCommand = map[string]*RegisteredCommand

type UiOptions

type UiOptions struct {
	MaxHistoryItem int
	ShortCut       ShortCutCommands
}

type Validator

type Validator[T any] interface {
	Valid(ctx Context, value T) (bool, Message)
}

func EmptyArgs

func EmptyArgs() Validator[*CommandInputs]

func ExactlyLength

func ExactlyLength(size uint, emsg Message) Validator[*CommandInputs]

func ExpectLength

func ExpectLength(min int, max int, emsg Message) Validator[*CommandInputs]

func MustFlagged

func MustFlagged(flags ...*FlagExpected) Validator[*CommandInputs]

type ValueOperator

type ValueOperator interface {
	SetValueIfAbsent(key any, value any) (exist bool)
	SetValue(key any, value any)
	Remove(key any) (removed any, loaded bool)
}

type Window

type Window interface {
	Run(prompt string, ctx Context) Message
}

func ConfigUi

func ConfigUi(options UiOptions) Window

func NewUi

func NewUi() Window

Jump to

Keyboard shortcuts

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