/
nickolasfox
/
kek
Обзор
Документация
Войти
/
nickolasfox
/
kek
Код
Запросы
0
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
pkg/plugins/complete.go
107 строк
3 KB
Nickolas Fox
Alpha version
29 мар 2024, 20:17
29 мар 2024, 20:17
f14be9d
Код
Авторство
О чём код?
package plugins import ( "errors" "fmt" "strings" "github.com/spf13/cobra" ) var ( // ErrNoExecutable if not executable (including scripts) found. ErrNoExecutable = errors.New("no executable found") ) // Completer describes the interface for bundling CLI complete auxiliary. type Completer interface { Complete(cmd *cobra.Command, args []string) (err error) } // Executer describes the interface for bundling CLI executor. type Executer interface { Execute(cmd *cobra.Command, args []string) ExecuteE(cmd *cobra.Command, args []string) (err error) } // Interface represents standard runner interface to complete and execute commands. type Interface interface { Completer Executer } // Complete reflects simplifier to run different commands collected regarding // - configuration manifest files // - kek-<app-name> executables (including scripts) type Complete struct { plugins []*Plugin } // NewComplete initializes Complete with plugins found localy. func NewComplete() *Complete { return &Complete{ plugins: LoadPlugins(), } } // Complete provides chain completion for command and sub-commands. func (c *Complete) Complete(cmd *cobra.Command, args []string) (err error) { app := args[0] // show found commands if len(args) == 1 { if commands, found := c.lookup(app); found { _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\n", strings.Join(commands, "\n")) } return } return c.pluginComplete(cmd, args) } // pluginComplete tries to run completion sequence for identified plugin. // call plugin complete only if you are ensured that amount of arguments is bigger than 1 func (c *Complete) pluginComplete(cmd *cobra.Command, args []string) (err error) { app := args[0] var plugin *Plugin for _, p := range c.plugins { if app == p.Name { plugin = p } } if plugin == nil || !plugin.Completion.Enabled { // log -> no app is found to invoke further calls -> exit return nil } return plugin.Complete(cmd, args) } func (c *Complete) lookup(prefix string) (output []string, found bool) { for _, plugin := range c.plugins { if strings.HasPrefix(plugin.Name, prefix) { output = append(output, fmt.Sprintf("%s\t%s", plugin.Name, plugin.Description)) found = true } } return } // Execute executes plugin regarding its configuration (compatible with cobra.Run signature) func (c *Complete) Execute(cmd *cobra.Command, args []string) { _ = c.ExecuteE(cmd, args) } // ExecuteE executes plugin regarding its configuration (compatible with cobra.RunE signature) func (c *Complete) ExecuteE(cmd *cobra.Command, args []string) (err error) { // plugins has a priority appName := args[0] for _, plugin := range c.plugins { if appName == plugin.Name { return plugin.Execute(cmd, args[1:]) } } return ErrNoExecutable }