-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal.go
More file actions
58 lines (49 loc) · 1.14 KB
/
local.go
File metadata and controls
58 lines (49 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"context"
"fmt"
"os/exec"
"runtime"
"time"
)
// LocalExecutor runs commands on the local machine.
type LocalExecutor struct {
shell string
}
func NewLocalExecutor(shell string) *LocalExecutor {
if shell == "" {
if runtime.GOOS == "windows" {
shell = "cmd"
} else {
shell = "bash"
}
}
return &LocalExecutor{shell: shell}
}
func (e *LocalExecutor) Exec(command string, timeout int) (string, error) {
var ctx context.Context
var cancel context.CancelFunc
if timeout > 0 {
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(timeout)*time.Second)
defer cancel()
} else {
ctx = context.Background()
}
var cmd *exec.Cmd
if e.shell == "cmd" {
cmd = exec.CommandContext(ctx, "cmd", "/C", command)
} else {
cmd = exec.CommandContext(ctx, e.shell, "-c", command)
}
output, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
return string(output), fmt.Errorf("command timed out after %d seconds", timeout)
}
if err != nil {
return string(output) + "\nError: " + err.Error(), nil
}
return string(output), nil
}
func (e *LocalExecutor) Close() error {
return nil
}