84 lines
2.4 KiB
Go
84 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"os/exec"
|
|
"sort"
|
|
"strings"
|
|
"syscall"
|
|
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// expandHostCommand substitutes each argument once, without shell evaluation.
|
|
func expandHostCommand(command config.HostCommand, host resolvedHost, extra []string) []string {
|
|
_, name := netbox.SplitTarget(host.Name)
|
|
replace := strings.NewReplacer("{host}", name, "{address}", host.IP, "{target}", host.Name)
|
|
argv := make([]string, 0, len(command.Args)+len(extra))
|
|
for _, arg := range command.Args {
|
|
argv = append(argv, replace.Replace(arg))
|
|
}
|
|
return append(argv, extra...)
|
|
}
|
|
|
|
func runCmd() *cobra.Command {
|
|
var dryRun bool
|
|
cmd := &cobra.Command{
|
|
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
|
|
Short: "Run a configured local command for a NetBox or static host",
|
|
Args: cobra.MinimumNArgs(2),
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
command, ok := cfg.Commands[args[0]]
|
|
if !ok {
|
|
return fmt.Errorf("unknown configured command %q", args[0])
|
|
}
|
|
host := resolveTarget(cfg, args[1])
|
|
argv := expandHostCommand(command, host, args[2:])
|
|
if dryRun {
|
|
for i, arg := range argv {
|
|
if i > 0 {
|
|
fmt.Fprint(cmd.OutOrStdout(), " ")
|
|
}
|
|
fmt.Fprintf(cmd.OutOrStdout(), "%q", arg)
|
|
}
|
|
fmt.Fprintln(cmd.OutOrStdout())
|
|
return nil
|
|
}
|
|
path, err := exec.LookPath(argv[0])
|
|
if err != nil {
|
|
return fmt.Errorf("%s not found in PATH: %w", argv[0], err)
|
|
}
|
|
return syscall.Exec(path, argv, os.Environ())
|
|
},
|
|
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
|
|
if len(args) == 0 {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
return nil, cobra.ShellCompDirectiveError
|
|
}
|
|
var names []string
|
|
for name := range cfg.Commands {
|
|
if strings.HasPrefix(name, prefix) {
|
|
names = append(names, name)
|
|
}
|
|
}
|
|
sort.Strings(names)
|
|
return names, cobra.ShellCompDirectiveNoFileComp
|
|
}
|
|
if len(args) == 1 {
|
|
return completeHosts(prefix), cobra.ShellCompDirectiveNoFileComp
|
|
}
|
|
return nil, cobra.ShellCompDirectiveNoFileComp
|
|
},
|
|
}
|
|
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
|
|
return cmd
|
|
}
|