golib/console/console.go

97 lines
1.5 KiB
Go
Raw Normal View History

2023-06-15 21:22:51 +08:00
//
// cli.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package console
import (
"fmt"
"os"
)
type sApp struct {
name string
version string
desc string
cmds map[string]ICommand
about ActionHandler
}
func New(name, desc string) *sApp {
app := &sApp{
name: name,
version: "v0.1.0",
desc: desc,
cmds: make(map[string]ICommand),
}
app.AddCmd(NewAboutCmd(app))
app.AddCmd(NewAirCmd(app))
app.AddCmd(NewListCmd(app))
app.AddCmd(NewHelpCmd(app))
return app
}
func (s *sApp) GetCmds() map[string]ICommand {
return s.cmds
}
func (s *sApp) GetName() string {
return s.name
}
func (s *sApp) GetDesc() string {
return s.desc
}
func (s *sApp) GetVersion() string {
return s.version
}
func (s *sApp) AddCmd(cmd ICommand) {
s.cmds[cmd.GetName()] = cmd
}
func (s *sApp) HasCmd(cmd string) bool {
_, ok := s.cmds[cmd]
return ok
}
func (s *sApp) SetExtraAbout(about ActionHandler) {
s.about = about
}
func (s *sApp) GetExtraAbout() ActionHandler {
return s.about
}
func (s *sApp) Run(args []string) {
cmd := "list"
if len(args) == 1 {
args = []string{cmd}
} else {
cmd = args[1]
args = args[2:]
}
if !s.HasCmd(cmd) {
fmt.Printf("%q is not valid command.\n", cmd)
os.Exit(2)
}
scmd := s.cmds[cmd]
scmd.Init(args)
act := scmd.GetAction()
if act == nil {
// fmt.Println("未定义 Action无法执行 Action.")
fmt.Println(scmd.GetHelp())
os.Exit(1)
}
err := act()
if err != nil {
fmt.Printf("执行异常:%v\n", err)
os.Exit(1)
}
}