chinampa/internal/registry/registry.go

244 lines
7.1 KiB
Go
Raw Normal View History

2022-12-19 03:04:34 +00:00
// Copyright © 2022 Roberto Hidalgo <chinampa@un.rob.mx>
2022-12-31 05:53:24 +00:00
// SPDX-License-Identifier: Apache-2.0
2022-12-19 03:04:34 +00:00
package registry
import (
"fmt"
"os"
"sort"
"strings"
2022-12-31 05:53:24 +00:00
"git.rob.mx/nidito/chinampa/internal/commands"
2022-12-19 03:04:34 +00:00
"git.rob.mx/nidito/chinampa/pkg/command"
2022-12-31 05:53:24 +00:00
"git.rob.mx/nidito/chinampa/pkg/errors"
2023-03-20 06:15:53 +00:00
"git.rob.mx/nidito/chinampa/pkg/logger"
2023-03-24 06:44:47 +00:00
"git.rob.mx/nidito/chinampa/pkg/runtime"
2022-12-19 03:04:34 +00:00
"github.com/fatih/color"
"github.com/spf13/cobra"
2023-03-24 06:44:47 +00:00
"github.com/spf13/pflag"
2022-12-19 03:04:34 +00:00
)
2022-12-31 05:53:24 +00:00
// ContextKeyRuntimeIndex is the string key used to store context in a cobra Command.
const ContextKeyRuntimeIndex = "x-chinampa-runtime-index"
var ErrorHandler = errors.HandleCobraExit
2023-03-20 06:15:53 +00:00
var log = logger.Sub("registry")
2022-12-31 23:53:49 +00:00
2022-12-19 03:04:34 +00:00
var registry = &CommandRegistry{
kv: map[string]*command.Command{},
}
type ByPath []*command.Command
func (cmds ByPath) Len() int { return len(cmds) }
func (cmds ByPath) Swap(i, j int) { cmds[i], cmds[j] = cmds[j], cmds[i] }
func (cmds ByPath) Less(i, j int) bool { return cmds[i].FullName() < cmds[j].FullName() }
type CommandRegistry struct {
kv map[string]*command.Command
byPath []*command.Command
}
func Register(cmd *command.Command) {
2023-03-20 01:18:10 +00:00
log.Tracef("adding to registry: %s", cmd.FullName())
2022-12-19 03:04:34 +00:00
registry.kv[cmd.FullName()] = cmd
}
func Get(id string) *command.Command {
return registry.kv[id]
}
func CommandList() []*command.Command {
if len(registry.byPath) == 0 {
list := []*command.Command{}
for _, v := range registry.kv {
list = append(list, v)
}
sort.Sort(ByPath(list))
registry.byPath = list
}
return registry.byPath
}
2023-04-04 00:13:42 +00:00
func subOptions(m command.Options) command.Options {
m2 := make(map[string]*command.Option, len(m))
for id, opt := range m {
m2[id] = opt
}
return m2
}
2022-12-19 03:04:34 +00:00
func Execute(version string) error {
2022-12-31 23:53:49 +00:00
log.Debug("starting execution")
2022-12-19 03:04:34 +00:00
cmdRoot := command.Root
2022-12-29 19:05:58 +00:00
ccRoot := newCobraRoot(command.Root)
2022-12-19 03:04:34 +00:00
ccRoot.CompletionOptions.HiddenDefaultCmd = true
2023-03-24 06:44:47 +00:00
globalOptions := command.Options{}
cmdRoot.FlagSet().VisitAll(func(f *pflag.Flag) {
opt := command.Root.Options[f.Name]
if f.Name == "version" {
ccRoot.Flags().AddFlag(f)
} else {
ccRoot.PersistentFlags().AddFlag(f)
globalOptions[f.Name] = opt
}
if err := ccRoot.RegisterFlagCompletionFunc(f.Name, opt.CompletionFunction); err != nil {
log.Errorf("Failed setting up autocompletion for option <%s> of command <%s>", f.Name, cmdRoot.FullName())
}
})
2023-01-23 04:29:18 +00:00
if version != "" {
name := commands.VersionCommandName
ccRoot.Annotations["version"] = version
commands.Version.Hidden = strings.HasPrefix(name, "_")
commands.Version.Use = name
ccRoot.AddCommand(commands.Version)
}
2022-12-31 05:53:24 +00:00
ccRoot.AddCommand(commands.GenerateCompletions)
2022-12-19 03:04:34 +00:00
2023-03-24 06:44:47 +00:00
ccRoot.SetHelpFunc(cmdRoot.HelpRenderer(globalOptions))
2022-12-19 03:04:34 +00:00
for _, cmd := range CommandList() {
cmd := cmd
container := ccRoot
for idx, cp := range cmd.Path {
if idx == len(cmd.Path)-1 {
2023-04-04 00:13:42 +00:00
if cmd.Action != nil {
// nil actions come when the current command consists only
// of metadata for a "group parent" command
// and we don't wanna cobraize it like a regular, actionable one
leaf := ToCobra(cmd, globalOptions, container)
log.Tracef("cobra: %s => %s", leaf.Name(), container.CommandPath())
break
}
log.Tracef("Found command with no action: %s, assuming group parent action", cmd.Path)
2022-12-19 03:04:34 +00:00
}
query := []string{cp}
2022-12-31 05:53:24 +00:00
found := false
if len(query) == 1 && query[0] == "help" {
container = commands.Help
continue
}
2022-12-31 23:53:49 +00:00
for _, sub := range container.Commands() {
if sub.Name() == cp {
2023-04-04 00:13:42 +00:00
if parent := FromCobra(container); parent != nil {
log.Tracef("pflags to %s from %s", sub.Name(), parent.FullName())
fs := parent.FlagSet()
sub.PersistentFlags().AddFlagSet(fs)
}
2022-12-31 23:53:49 +00:00
container = sub
found = true
2022-12-31 05:53:24 +00:00
}
}
if !found {
2022-12-19 03:04:34 +00:00
groupName := strings.Join(query, " ")
2023-04-04 00:13:42 +00:00
cleanPath := append(cmd.Path[0:idx], query...)
groupPath := append(cmdRoot.Path, cleanPath...) // nolint:gocritic
cmdGlobalOptions := globalOptions
groupParent := Get(groupName)
if groupParent == nil {
log.Tracef("creating group parent for %s", groupPath)
groupParent = &command.Command{
Path: cleanPath,
Summary: fmt.Sprintf("%s subcommands", groupName),
Description: fmt.Sprintf("Runs subcommands within %s", groupName),
Arguments: command.Arguments{},
Options: command.Options{},
}
Register(groupParent)
} else {
log.Tracef("using pre-existing group parent for %s (%s)", groupPath, groupParent.Path)
}
2022-12-19 03:04:34 +00:00
cc := &cobra.Command{
Use: cp,
2023-04-04 00:13:42 +00:00
Short: groupParent.Summary,
2022-12-19 03:04:34 +00:00
DisableAutoGenTag: true,
SuggestionsMinimumDistance: 2,
SilenceUsage: true,
SilenceErrors: true,
Annotations: map[string]string{
2023-04-04 00:13:42 +00:00
ContextKeyRuntimeIndex: strings.Join(cleanPath, " "),
2022-12-19 03:04:34 +00:00
},
2023-03-20 06:15:53 +00:00
ValidArgs: []string{},
2022-12-19 03:04:34 +00:00
Args: func(cmd *cobra.Command, args []string) error {
if err := cobra.OnlyValidArgs(cmd, args); err == nil {
return nil
}
suggestions := []string{}
bold := color.New(color.Bold)
for _, l := range cmd.SuggestionsFor(args[len(args)-1]) {
suggestions = append(suggestions, bold.Sprint(l))
}
last := len(args) - 1
parent := cmd.CommandPath()
errMessage := fmt.Sprintf("Unknown subcommand %s of known command %s", bold.Sprint(args[last]), bold.Sprint(parent))
if len(suggestions) > 0 {
errMessage += ". Perhaps you meant " + strings.Join(suggestions, ", ") + "?"
}
return errors.NotFound{Msg: errMessage, Group: []string{}}
},
RunE: func(cc *cobra.Command, args []string) error {
if len(args) == 0 {
if cc.Name() == "help" {
return cc.Help()
}
2022-12-19 03:04:34 +00:00
return errors.NotFound{Msg: "No subcommand provided", Group: []string{}}
}
return errors.NotFound{Msg: fmt.Sprintf("Unknown subcommand %s", args[0]), Group: []string{}}
2022-12-19 03:04:34 +00:00
},
}
2023-04-04 00:13:42 +00:00
if len(groupParent.Options) > 0 {
fs := cmd.FlagSet()
cc.PersistentFlags().AddFlagSet(fs)
log.Debugf("adding sub-global option set to %s", groupName)
2022-12-19 03:04:34 +00:00
}
2023-04-04 00:13:42 +00:00
if container != cc.Root() {
cmdGlobalOptions = subOptions(globalOptions)
if p := FromCobra(container); p != nil {
for key, opt := range p.Options {
cmdGlobalOptions[key] = opt
}
}
}
cc.PersistentFlags().AddFlagSet(container.PersistentFlags())
cc.SetHelpFunc(groupParent.HelpRenderer(cmdGlobalOptions))
2022-12-31 23:53:49 +00:00
cc.SetHelpCommand(commands.Help)
2022-12-19 03:04:34 +00:00
container.AddCommand(cc)
container = cc
}
}
2022-12-30 07:00:26 +00:00
cmd.Path = append(cmdRoot.Path, cmd.Path...)
2022-12-19 03:04:34 +00:00
}
cmdRoot.SetCobra(ccRoot)
2023-03-24 06:44:47 +00:00
commands.Help.Long = strings.ReplaceAll(commands.Help.Long, "@chinampa@", runtime.Executable)
ccRoot.SetHelpCommand(commands.Help)
2022-12-19 03:04:34 +00:00
2022-12-31 05:53:24 +00:00
current, remaining, err := ccRoot.Find(os.Args[1:])
2022-12-19 03:04:34 +00:00
if err != nil {
2022-12-23 05:29:58 +00:00
current = ccRoot
}
2022-12-31 23:53:49 +00:00
log.Debugf("exec: found command %s with args: %s", current.CommandPath(), remaining)
2022-12-31 05:53:24 +00:00
if sub, _, err := current.Find(remaining); err == nil && sub != current {
2022-12-31 23:53:49 +00:00
log.Debugf("exec: found sub-command %s", sub.CommandPath())
2022-12-31 05:53:24 +00:00
current = sub
}
2022-12-31 23:53:49 +00:00
log.Debugf("exec: calling %s", current.CommandPath())
2022-12-19 03:04:34 +00:00
return ErrorHandler(current, current.Execute())
2022-12-19 03:04:34 +00:00
}