/* 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", 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) { //grab saved command cmdName := viper.Get(fmt.Sprintf("customCmd-%s", args[0])).(string) //convert arguments to interface var nargs []any for _, a := range args[1:] { nargs = append(nargs, a) } //inject arguments fixed := fmt.Sprintf(cmdName, 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 we have a command name al := len(args) if al == 0 { return errors.New("name argument is required") } cmdCheck := viper.Get(fmt.Sprintf("customCmd-%s", args[0])) count := strings.Count(cmdCheck.(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) }