2021-01-17 21:46:25 +08:00
|
|
|
// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
|
2019-09-05 11:38:36 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
|
|
|
//
|
|
|
|
|
|
|
|
package gcmd
|
|
|
|
|
|
|
|
import (
|
2021-10-11 21:41:56 +08:00
|
|
|
"github.com/gogf/gf/v2/errors/gcode"
|
|
|
|
"github.com/gogf/gf/v2/errors/gerror"
|
2019-09-05 11:38:36 +08:00
|
|
|
)
|
|
|
|
|
2021-10-21 18:22:47 +08:00
|
|
|
// BindHandle registers callback function `f` with `cmd`.
|
2019-09-05 11:38:36 +08:00
|
|
|
func (p *Parser) BindHandle(cmd string, f func()) error {
|
|
|
|
if _, ok := p.commandFuncMap[cmd]; ok {
|
2021-08-24 21:18:59 +08:00
|
|
|
return gerror.NewCode(gcode.CodeInvalidOperation, "duplicated handle for command:"+cmd)
|
2019-09-05 11:38:36 +08:00
|
|
|
} else {
|
|
|
|
p.commandFuncMap[cmd] = f
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-21 18:22:47 +08:00
|
|
|
// BindHandleMap registers callback function with map `m`.
|
2019-09-16 20:57:43 +08:00
|
|
|
func (p *Parser) BindHandleMap(m map[string]func()) error {
|
|
|
|
var err error
|
|
|
|
for k, v := range m {
|
|
|
|
if err = p.BindHandle(k, v); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-21 18:22:47 +08:00
|
|
|
// RunHandle executes the callback function registered by `cmd`.
|
2019-09-05 11:38:36 +08:00
|
|
|
func (p *Parser) RunHandle(cmd string) error {
|
|
|
|
if handle, ok := p.commandFuncMap[cmd]; ok {
|
|
|
|
handle()
|
|
|
|
} else {
|
2021-08-24 21:18:59 +08:00
|
|
|
return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd)
|
2019-09-05 11:38:36 +08:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// AutoRun automatically recognizes and executes the callback function
|
|
|
|
// by value of index 0 (the first console parameter).
|
|
|
|
func (p *Parser) AutoRun() error {
|
2021-10-21 18:22:47 +08:00
|
|
|
if cmd := p.GetArg(1); !cmd.IsEmpty() {
|
|
|
|
if handle, ok := p.commandFuncMap[cmd.String()]; ok {
|
2019-09-05 11:38:36 +08:00
|
|
|
handle()
|
|
|
|
} else {
|
2021-10-21 18:22:47 +08:00
|
|
|
return gerror.NewCode(gcode.CodeMissingConfiguration, "no handle found for command:"+cmd.String())
|
2019-09-05 11:38:36 +08:00
|
|
|
}
|
|
|
|
} else {
|
2021-08-24 21:18:59 +08:00
|
|
|
return gerror.NewCode(gcode.CodeMissingParameter, "no command found")
|
2019-09-05 11:38:36 +08:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|