115 lines
1.9 KiB
Go
115 lines
1.9 KiB
Go
//
|
||
// cli.go
|
||
// Copyright (C) 2022 tiglog <me@tiglog.com>
|
||
//
|
||
// Distributed under terms of the MIT license.
|
||
//
|
||
|
||
package gconsole
|
||
|
||
import (
|
||
"fmt"
|
||
"os"
|
||
)
|
||
|
||
type App struct {
|
||
name string
|
||
version string
|
||
desc string
|
||
cmds map[string]ICommand
|
||
about ActionHandler
|
||
}
|
||
|
||
func New(name, desc string) *App {
|
||
app := &App{
|
||
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))
|
||
app.AddCmd(NewListCmd(app))
|
||
app.AddCmd(NewHelpCmd(app))
|
||
return app
|
||
}
|
||
|
||
func (s *App) GetCmds() map[string]ICommand {
|
||
return s.cmds
|
||
}
|
||
|
||
func (s *App) GetName() string {
|
||
return s.name
|
||
}
|
||
|
||
func (s *App) GetDesc() string {
|
||
return s.desc
|
||
}
|
||
|
||
func (s *App) GetVersion() string {
|
||
return s.version
|
||
}
|
||
|
||
func (s *App) AddCmd(cmd ICommand) {
|
||
s.cmds[cmd.GetName()] = cmd
|
||
}
|
||
|
||
func (s *App) HasCmd(cmd string) bool {
|
||
_, ok := s.cmds[cmd]
|
||
return ok
|
||
}
|
||
|
||
func (s *App) SetExtraAbout(about ActionHandler) {
|
||
s.about = about
|
||
}
|
||
|
||
func (s *App) GetExtraAbout() ActionHandler {
|
||
return s.about
|
||
}
|
||
|
||
func (s *App) 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)
|
||
}
|
||
}
|
||
|
||
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
|