forked from Sora233/DDBOT
/
commandRuntime.go
93 lines (85 loc) · 2.09 KB
/
commandRuntime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package lsp
import (
"fmt"
"github.com/starskim/DDBOT/lsp/concern"
"github.com/starskim/DDBOT/lsp/concern_type"
"github.com/starskim/DDBOT/lsp/parser"
localutils "github.com/starskim/DDBOT/utils"
"github.com/alecthomas/kong"
"io"
"strings"
)
type Runtime struct {
bot *localutils.HackedBot
l *Lsp
*parser.Parser
debug bool
exit bool
silence bool
}
func (r *Runtime) Exit(int) {
r.exit = true
}
func (r *Runtime) Debug() {
r.debug = true
}
func (r *Runtime) parseCommandSyntax(ast interface{}, name string, options ...kong.Option) (*kong.Context, string) {
args := r.GetArgs()
cmdOut := &strings.Builder{}
// kong 错误信息不太友好
options = append(options, kong.Name(name), kong.UsageOnError(), kong.Exit(r.Exit))
k, err := kong.New(ast, options...)
if err != nil {
logger.Errorf("kong new failed %v", err)
r.Exit(0)
return nil, ""
}
if r.silence {
k.Stdout = io.Discard
} else {
k.Stdout = cmdOut
}
ctx, err := k.Parse(args)
if r.exit {
logger.WithField("content", args).Debug("exit")
return ctx, cmdOut.String()
}
if err != nil {
logger.WithField("content", args).Errorf("kong parse failed %v", err)
r.Exit(0)
var out string
if !r.silence {
out = fmt.Sprintf("参数解析失败 - %v", err)
}
return nil, out
}
return ctx, ""
}
func (r *Runtime) ParseRawSiteAndType(rawSite string, rawType string) (string, concern_type.Type, error) {
site, ctype, err := concern.ParseRawSiteAndType(rawSite, rawType)
if err == concern.ErrSiteNotSupported {
err = fmt.Errorf("%v <%v>", err.Error(), rawSite)
}
if err == concern.ErrTypeNotSupported {
err = fmt.Errorf("%v <%v>", err.Error(), rawType)
}
return site, ctype, err
}
func (r *Runtime) ParseRawSite(rawSite string) (string, error) {
site, err := concern.ParseRawSite(rawSite)
if err == concern.ErrSiteNotSupported {
err = fmt.Errorf("%v <%v>", err.Error(), rawSite)
}
return site, err
}
func NewRuntime(l *Lsp, silence ...bool) *Runtime {
r := &Runtime{
bot: localutils.GetBot(),
l: l,
Parser: parser.NewParser(),
}
if len(silence) > 0 {
r.silence = silence[0]
}
return r
}