lots o progress
- added 'command' subcommand - removed viper - setup commands added - still a WIP - readme TODO update
This commit is contained in:
87
cmd/run.go
87
cmd/run.go
@@ -1,87 +0,0 @@
|
||||
/*
|
||||
Copyright © 2025 Jake jake.young.dev@gmail.com
|
||||
*/
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"code.jakeyoungdev.com/jake/mctl/client"
|
||||
"code.jakeyoungdev.com/jake/mctl/database"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// runCmd represents the run command
|
||||
var runCmd = &cobra.Command{
|
||||
Use: "run <name> 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) {
|
||||
db, err := database.New()
|
||||
cobra.CheckErr(err)
|
||||
defer db.Close()
|
||||
|
||||
sc, err := db.GetCmd(args[0])
|
||||
if err == sql.ErrNoRows {
|
||||
fmt.Printf("command %s not found", args[0])
|
||||
return
|
||||
}
|
||||
cobra.CheckErr(err)
|
||||
|
||||
//convert arguments to interface
|
||||
var nargs []any
|
||||
for _, a := range args[1:] {
|
||||
nargs = append(nargs, a)
|
||||
}
|
||||
|
||||
//inject arguments
|
||||
fixed := fmt.Sprintf(sc, 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 config command has been run
|
||||
if !viper.IsSet("server") || !viper.IsSet("password") || !viper.IsSet("port") {
|
||||
return errors.New("the 'config' command must be run before you can interact with servers")
|
||||
}
|
||||
|
||||
if !viper.IsSet("customcmd") {
|
||||
return errors.New("no saved commands to run")
|
||||
}
|
||||
|
||||
//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)
|
||||
}
|
||||
Reference in New Issue
Block a user