golib/gconsole/console.go

115 lines
1.9 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.
//
2023-10-15 00:54:45 +08:00
package gconsole
2023-06-15 21:22:51 +08:00
import (
"fmt"
"os"
)
2023-10-15 00:54:45 +08:00
type App struct {
2023-06-15 21:22:51 +08:00
name string
version string
desc string
cmds map[string]ICommand
about ActionHandler
}
2023-10-15 00:54:45 +08:00
func New(name, desc string) *App {
app := &App{
2023-06-15 21:22:51 +08:00
name: name,
version: "v0.1.0",
desc: desc,
cmds: make(map[string]ICommand),
}
app.AddCmd(NewAboutCmd(app))
app.AddCmd(NewAirCmd(app))
app.AddCmd(NewGenCmd(app))
2023-06-15 21:22:51 +08:00
app.AddCmd(NewListCmd(app))
app.AddCmd(NewHelpCmd(app))
return app
}
2023-10-15 00:54:45 +08:00
func (s *App) GetCmds() map[string]ICommand {
2023-06-15 21:22:51 +08:00
return s.cmds
}
2023-10-15 00:54:45 +08:00
func (s *App) GetName() string {
2023-06-15 21:22:51 +08:00
return s.name
}
2023-10-15 00:54:45 +08:00
func (s *App) GetDesc() string {
2023-06-15 21:22:51 +08:00
return s.desc
}
2023-10-15 00:54:45 +08:00
func (s *App) GetVersion() string {
2023-06-15 21:22:51 +08:00
return s.version
}
2023-10-15 00:54:45 +08:00
func (s *App) AddCmd(cmd ICommand) {
2023-06-15 21:22:51 +08:00
s.cmds[cmd.GetName()] = cmd
}
2023-10-15 00:54:45 +08:00
func (s *App) HasCmd(cmd string) bool {
2023-06-15 21:22:51 +08:00
_, ok := s.cmds[cmd]
return ok
}
2023-10-15 00:54:45 +08:00
func (s *App) SetExtraAbout(about ActionHandler) {
2023-06-15 21:22:51 +08:00
s.about = about
}
2023-10-15 00:54:45 +08:00
func (s *App) GetExtraAbout() ActionHandler {
2023-06-15 21:22:51 +08:00
return s.about
}
2023-10-15 00:54:45 +08:00
func (s *App) Run(args []string) {
2023-06-15 21:22:51 +08:00
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)
}
}
type ICommand interface {
Init(args []string)
GetName() string
GetDesc() string
GetAction() ActionHandler
GetHelp() string
}
type IConsole interface {
GetCmds() map[string]ICommand
GetName() string
GetDesc() string
GetVersion() string
GetExtraAbout() ActionHandler
}
type ActionHandler func() error