Files
ssh-hub/cmd/exec/exec.go
Denys Seredenko 121c2505e6
All checks were successful
Build and Test / build-test (1.23.4) (push) Successful in 1m37s
* showing help by basic call
* autocompletion for exec
2025-02-18 19:34:15 +01:00

88 lines
2.1 KiB
Go

package exec
import (
"errors"
"fmt"
"git.denysoft.de/CubeBit/ssh-hub/util"
"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",
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
data := viper.GetStringMapString("data")
return util.AutocompleteConfig(&data, toComplete), cobra.ShellCompDirectiveNoFileComp
},
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
}