package exec import ( "errors" "fmt" "github.com/creack/pty" "github.com/spf13/cobra" "github.com/spf13/viper" "golang.org/x/term" "io" "os" "os/exec" "syscall" ) var execCmd = &cobra.Command{ Use: "exec", Short: "Execute command of specific alias", Args: func(cmd *cobra.Command, args []string) error { if err := cobra.ExactArgs(1)(cmd, args); err != nil { return err } data := viper.GetStringMapString("data") if _, ok := data[args[0]]; !ok { return errors.New("such alias was not found") } return nil }, Run: func(cmd *cobra.Command, args []string) { data := viper.GetStringMapString("data") commandStr, ok := data[args[0]] if !ok { fmt.Fprintf(os.Stderr, "No command found for alias '%s'\n", args[0]) os.Exit(1) } command := exec.Command("bash", "-c", commandStr) command.Env = append(os.Environ(), "TERM=xterm-256color") ptmx, err := pty.Start(command) if err != nil { fmt.Fprintf(os.Stderr, "Error starting PTY: %v\n", err) os.Exit(1) } defer func() { _ = ptmx.Close() }() go func() { for { if err := pty.InheritSize(os.Stdin, ptmx); err != nil { fmt.Fprintf(os.Stderr, "Error resizing PTY: %v\n", err) break } } }() oldState, err := term.MakeRaw(int(os.Stdin.Fd())) if err != nil { fmt.Fprintf(os.Stderr, "Error setting raw mode: %v\n", err) os.Exit(1) } defer func() { _ = term.Restore(int(os.Stdin.Fd()), oldState) }() go func() { _, _ = io.Copy(ptmx, os.Stdin) }() _, _ = io.Copy(os.Stdout, ptmx) if err := command.Wait(); err != nil { if exitError, ok := err.(*exec.ExitError); ok { if ws, ok := exitError.Sys().(syscall.WaitStatus); ok { os.Exit(ws.ExitStatus()) } } fmt.Fprintf(os.Stderr, "Command execution failed: %v\n", err) } }, } func Cmd() *cobra.Command { return execCmd }