/* Copyright © 2025 Jake jake.young.dev@gmail.com */ package cmd import ( "errors" "fmt" "strings" "code.jakeyoungdev.com/jake/mctl/client" "github.com/spf13/cobra" "github.com/spf13/viper" ) // runCmd represents the run command var runCmd = &cobra.Command{ Use: "run args...", Example: "mctl run savedcmd 63 jake", SilenceUsage: true, Short: "Runs a previously saved command with supplied arguments on remote server", Long: `Loads a saved command, injects the supplied arguments into the command, and sends the command to the remove server printing the response`, Run: func(cmd *cobra.Command, args []string) { //check for command map var cm map[string]any cmdMap := viper.Get("customcmd") if cmdMap == nil { cm = make(map[string]any, 0) } else { cm = cmdMap.(map[string]any) } //is this an existing command cmdRun, ok := cm[args[0]] if !ok { fmt.Printf("command %s not found", args[0]) return } //convert arguments to interface var nargs []any for _, a := range args[1:] { nargs = append(nargs, a) } //inject arguments fixed := fmt.Sprintf(cmdRun.(string), nargs...) fmt.Printf("Running saved command %s\n", fixed) //create client and send command cli, err := client.New() cobra.CheckErr(err) defer cli.Close() res, err := cli.Command(fixed) cobra.CheckErr(err) fmt.Println(res) }, PreRunE: func(cmd *cobra.Command, args []string) error { //ensure configuration has been setup if viper.Get("server") == "" || viper.Get("password") == "" || viper.Get("port") == 0 { return errors.New("the 'config' command must be run before you can interact with servers") } //ensure we have a command name al := len(args) if al == 0 { return errors.New("name argument is required") } cmdMap := viper.Get("customcmd").(map[string]any) count := strings.Count(cmdMap[args[0]].(string), "%s") //make sure enough arguments are sent to fill command placeholders if al < count+1 { return fmt.Errorf("not enough arguments to populate command. Supplied: %d, Needed: %d", al-1, count) } return nil }, } func init() { rootCmd.AddCommand(runCmd) }