Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/agent/tools/shell.go
3434 views
1
package tools
2
3
import (
4
"bytes"
5
"context"
6
"errors"
7
"github.com/kardolus/chatgpt-cli/agent/types"
8
"os/exec"
9
"time"
10
)
11
12
type Shell interface {
13
Run(
14
ctx context.Context,
15
workDir string,
16
name string,
17
args ...string,
18
) (types.Result, error)
19
}
20
21
type ExecShellRunner struct{}
22
23
func NewExecShellRunner() *ExecShellRunner {
24
return &ExecShellRunner{}
25
}
26
27
func (r *ExecShellRunner) Run(
28
ctx context.Context,
29
workDir string,
30
name string,
31
args ...string,
32
) (types.Result, error) {
33
start := time.Now()
34
35
cmd := exec.CommandContext(ctx, name, args...)
36
cmd.Dir = workDir
37
38
var outb, errb bytes.Buffer
39
cmd.Stdout = &outb
40
cmd.Stderr = &errb
41
42
err := cmd.Run()
43
44
exit := 0
45
if err != nil {
46
var ee *exec.ExitError
47
if errors.As(err, &ee) {
48
exit = ee.ExitCode()
49
}
50
}
51
52
return types.Result{
53
Stdout: outb.String(),
54
Stderr: errb.String(),
55
ExitCode: exit,
56
Duration: time.Since(start),
57
}, nil
58
}
59
60