|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + "os/exec" |
| 8 | + "path" |
| 9 | + "path/filepath" |
| 10 | + "runtime" |
| 11 | + "strconv" |
| 12 | + "strings" |
| 13 | + "syscall" |
| 14 | + |
| 15 | + "ssh-wrapper/pkg/process" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + MUTAGEN_SSH_CONFIG = "MUTAGEN_SSH_CONFIG" |
| 20 | + MUTAGEN_CONNECT_TIMEOUT_IN_SECONDS = 20 |
| 21 | +) |
| 22 | + |
| 23 | +func ProcessArgs() []string { |
| 24 | + sshConfig := os.Getenv(MUTAGEN_SSH_CONFIG) |
| 25 | + if sshConfig == "" { |
| 26 | + fmt.Fprintln(os.Stderr, "Error: MUTAGEN_SSH_CONFIG environment variable is not set") |
| 27 | + os.Exit(1) |
| 28 | + } |
| 29 | + |
| 30 | + // Increase the default timeout |
| 31 | + args := os.Args[1:] |
| 32 | + for i, arg := range args { |
| 33 | + if strings.HasPrefix(arg, "-oConnectTimeout=") { |
| 34 | + args[i] = fmt.Sprintf("-oConnectTimeout=%d", MUTAGEN_CONNECT_TIMEOUT_IN_SECONDS) |
| 35 | + break |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return append([]string{fmt.Sprintf("-F%s", sshConfig)}, args...) |
| 40 | +} |
| 41 | + |
| 42 | +func WrapRunAndExit(command *exec.Cmd) { |
| 43 | + command.Stdin = os.Stdin |
| 44 | + command.Stdout = os.Stdout |
| 45 | + command.Stderr = os.Stderr |
| 46 | + |
| 47 | + if err := command.Run(); err != nil { |
| 48 | + if exiterr, ok := err.(*exec.ExitError); ok { |
| 49 | + if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { |
| 50 | + os.Exit(status.ExitStatus()) |
| 51 | + } |
| 52 | + } |
| 53 | + os.Exit(1) |
| 54 | + } |
| 55 | + os.Exit(0) |
| 56 | +} |
| 57 | + |
| 58 | +func Grun(commandName string, args ...string) { |
| 59 | + args = append([]string{strconv.Itoa(os.Getpid()), commandName}, args...) |
| 60 | + |
| 61 | + self, err := os.Executable() |
| 62 | + if err != nil { |
| 63 | + fmt.Fprintln(os.Stderr, "Error: cannot get current executable path") |
| 64 | + os.Exit(1) |
| 65 | + } |
| 66 | + |
| 67 | + grun := path.Join(filepath.Dir(self), process.ExecutableName("grun", runtime.GOOS)) |
| 68 | + command := exec.CommandContext(context.Background(), grun, args...) |
| 69 | + WrapRunAndExit(command) |
| 70 | +} |
0 commit comments