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