62159
Sy
symb / files
symb / internal / shell / shell.go
3.7 KB
1package shell 2 3import ( 4 "bytes" 5 "context" 6 "errors" 7 "fmt" 8 "io" 9 "os" 10 "strings" 11 "sync" 12 13 "mvdan.cc/sh/v3/expand" 14 "mvdan.cc/sh/v3/interp" 15 "mvdan.cc/sh/v3/syntax" 16) 17 18// Shell provides an in-process POSIX shell with persistent cwd/env across calls. 19type Shell struct { 20 mu sync.Mutex 21 root string // project root — shell is anchored here 22 cwd string 23 env []string 24 blockFuncs []BlockFunc 25} 26 27// New creates a Shell rooted at cwd with the given block functions. 28// The shell is anchored to this directory — cd outside it is clamped back. 29func New(cwd string, blockers []BlockFunc) *Shell { 30 if cwd == "" { 31 cwd, _ = os.Getwd() 32 } 33 return &Shell{ 34 root: cwd, 35 cwd: cwd, 36 env: os.Environ(), 37 blockFuncs: blockers, 38 } 39} 40 41// Exec runs a command synchronously, returning stdout, stderr, and any error. 42func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) { 43 s.mu.Lock() 44 defer s.mu.Unlock() 45 46 var stdout, stderr bytes.Buffer 47 err := s.execCommon(ctx, command, &stdout, &stderr) 48 return stdout.String(), stderr.String(), err 49} 50 51// ExecStream runs a command, streaming output to the provided writers. 52func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error { 53 s.mu.Lock() 54 defer s.mu.Unlock() 55 56 return s.execCommon(ctx, command, stdout, stderr) 57} 58 59// Dir returns the current working directory. 60func (s *Shell) Dir() string { 61 s.mu.Lock() 62 defer s.mu.Unlock() 63 return s.cwd 64} 65 66func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr io.Writer) (err error) { 67 var runner *interp.Runner 68 defer func() { 69 if r := recover(); r != nil { 70 err = fmt.Errorf("command execution panic: %v", r) 71 } 72 if runner != nil { 73 s.updateFromRunner(runner, stderr) 74 } 75 }() 76 77 parsed, err := syntax.NewParser().Parse(strings.NewReader(command), "") 78 if err != nil { 79 return fmt.Errorf("could not parse command: %w", err) 80 } 81 82 runner, err = s.newInterp(stdout, stderr) 83 if err != nil { 84 return fmt.Errorf("could not create interpreter: %w", err) 85 } 86 87 return runner.Run(ctx, parsed) 88} 89 90func (s *Shell) newInterp(stdout, stderr io.Writer) (*interp.Runner, error) { 91 return interp.New( 92 interp.StdIO(nil, stdout, stderr), 93 interp.Interactive(false), 94 interp.Env(expand.ListEnviron(s.env...)), 95 interp.Dir(s.cwd), 96 interp.ExecHandlers(s.blockHandler()), 97 ) 98} 99 100func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc { 101 return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc { 102 return func(ctx context.Context, args []string) error { 103 if len(args) == 0 { 104 return next(ctx, args) 105 } 106 for _, bf := range s.blockFuncs { 107 if bf(args) { 108 return fmt.Errorf("command blocked: %q", args[0]) 109 } 110 } 111 return next(ctx, args) 112 } 113 } 114} 115 116// updateFromRunner persists cwd and exported env vars after execution. 117// If the runner's cwd escaped the project root, it is clamped back and a 118// warning is written to stderr so the LLM knows. 119func (s *Shell) updateFromRunner(runner *interp.Runner, stderr io.Writer) { 120 dir := runner.Dir 121 if !isSubdir(dir, s.root) { 122 fmt.Fprintf(stderr, "[cd rejected: you are anchored to %s]\n", s.root) 123 dir = s.root 124 } 125 s.cwd = dir 126 s.env = s.env[:0] 127 runner.Env.Each(func(name string, vr expand.Variable) bool { 128 if vr.Exported { 129 s.env = append(s.env, name+"="+vr.Str) 130 } 131 return true 132 }) 133} 134 135// isSubdir reports whether dir is equal to or under root. 136func isSubdir(dir, root string) bool { 137 return dir == root || strings.HasPrefix(dir, root+string(os.PathSeparator)) 138} 139 140// ExitCode extracts the exit code from an interpreter error. 141func ExitCode(err error) int { 142 if err == nil { 143 return 0 144 } 145 var exitErr interp.ExitStatus 146 if errors.As(err, &exitErr) { 147 return int(exitErr) 148 } 149 return 1 150}