github.com/wawandco/oxplugins@v0.7.11/tools/cli/help/command.go (about) 1 package help 2 3 import ( 4 "context" 5 "errors" 6 7 "github.com/wawandco/oxplugins/plugins" 8 ) 9 10 var ( 11 // Help is a Command 12 _ plugins.Command = (*Command)(nil) 13 14 ErrSubCommandNotFound = errors.New("Subcommand not found") 15 ) 16 17 // Help command that prints 18 type Command struct { 19 commands []plugins.Command 20 } 21 22 func (h Command) Name() string { 23 return "help" 24 } 25 26 func (h Command) ParentName() string { 27 return "" 28 } 29 30 // HelpText for the Help command 31 func (h Command) HelpText() string { 32 return "prints help text for the commands registered" 33 } 34 35 // Run the help command 36 func (h *Command) Run(ctx context.Context, root string, args []string) error { 37 command, names := h.findCommand(args) 38 if command == nil { 39 h.printTopLevel() 40 return nil 41 } 42 43 h.printSingle(command, names) 44 45 return nil 46 } 47 48 func (h *Command) findCommand(args []string) (plugins.Command, []string) { 49 if len(args) < 2 { 50 return nil, nil 51 } 52 53 var commands = h.commands 54 var command plugins.Command 55 var argIndex = 1 56 var fndNames []string 57 58 for { 59 var name = args[argIndex] 60 for _, c := range commands { 61 // TODO: If its a subcommand check also the SubcommandName 62 if c.Name() != name { 63 continue 64 } 65 fndNames = append(fndNames, c.Name()) 66 command = c 67 break 68 } 69 70 argIndex++ 71 if argIndex >= len(args) { 72 break 73 } 74 75 sc, ok := command.(plugins.Subcommander) 76 if !ok { 77 break 78 } 79 80 var sbcm []plugins.Command 81 for _, subc := range sc.Subcommands() { 82 sbcm = append(sbcm, subc.(plugins.Command)) 83 } 84 85 commands = sbcm 86 } 87 88 return command, fndNames 89 } 90 91 // Receive the plugins and stores the Commands for 92 // later usage on the help text. 93 func (h *Command) Receive(pl []plugins.Plugin) { 94 for _, plugin := range pl { 95 ht, ok := plugin.(plugins.Command) 96 if ok && ht.ParentName() == "" { 97 h.commands = append(h.commands, ht) 98 } 99 } 100 }