2 Star 0 Fork 1

Plato / idl2lang

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
options.go 2.50 KB
一键复制 编辑 原始数据 按行查看 历史
package scli
import (
"github.com/urfave/cli/v2"
)
type (
Options struct {
// flags will set value which following --xxx to parameter
flags []cli.Flag
// commands will be trigger by flag xxx
commands []*cli.Command
}
BaseCfg struct {
//Name is the command full name
Name string
//Short is the command aliases name
Short string
//Usage is the description of command
Usage string
//Required is required
Required bool
}
//FlagCfg is the config of parameter
FlagCfg struct {
*BaseCfg
//Default value
Default string
//Dest is pointer of value
Dest interface{}
}
//CommandCfg is the config of command
CommandCfg struct {
*BaseCfg
Action func([]string) error
}
Option func(options *Options)
)
//WithStringFlag will create string flag
func WithStringFlag(flag *FlagCfg) Option {
if flag == nil {
panic("invalid flag config ")
}
if len(flag.Name) == 0 && len(flag.Short) == 0 {
panic("flag's name or short name must set value")
}
return func(o *Options) {
sf := &cli.StringFlag{
Name: flag.Name,
Aliases: []string{flag.Short},
Value: flag.Default,
Usage: flag.Usage,
Required: flag.Required,
Destination: flag.Dest.(*string),
}
o.flags = append(o.flags, sf)
}
}
func WithFlag(flag *FlagCfg) Option {
var opt Option
switch flag.Dest.(type) {
case *string:
opt = func(o *Options) {
sf := &cli.StringFlag{
Name: flag.Name,
Aliases: []string{flag.Short},
Value: flag.Default,
Usage: flag.Usage,
Required: flag.Required,
Destination: flag.Dest.(*string),
}
o.flags = append(o.flags, sf)
}
case *bool:
opt = func(o *Options) {
sf := &cli.BoolFlag{
Name: flag.Name,
Aliases: []string{flag.Short},
Value: false,
Usage: flag.Usage,
Required: flag.Required,
Destination: flag.Dest.(*bool),
}
o.flags = append(o.flags, sf)
}
default:
panic("unsupported flag type !")
}
return opt
}
func WithCommand(command *CommandCfg) Option {
if command == nil {
panic("invalid command config ")
}
if len(command.Name) == 0 && len(command.Short) == 0 {
panic("command's name or short name must set value")
}
return func(o *Options) {
cmd := &cli.Command{
Name: command.Name,
Usage: command.Usage,
Aliases: []string{command.Short},
}
act := command.Action
if act != nil {
cmd.Action = func(ctx *cli.Context) error {
return act(ctx.Args().Slice())
}
}
o.commands = append(o.commands, cmd)
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/dennis-kk/idl2lang.git
git@gitee.com:dennis-kk/idl2lang.git
dennis-kk
idl2lang
idl2lang
v0.2.1

搜索帮助

344bd9b3 5694891 D2dac590 5694891