shell.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. // Package shell provides cross-platform shell execution capabilities.
  2. //
  3. // This package provides Shell instances for executing commands with their own
  4. // working directory and environment. Each shell execution is independent.
  5. //
  6. // WINDOWS COMPATIBILITY:
  7. // This implementation provides POSIX shell emulation (mvdan.cc/sh/v3) even on
  8. // Windows. Commands should use forward slashes (/) as path separators to work
  9. // correctly on all platforms.
  10. package shell
  11. import (
  12. "bytes"
  13. "context"
  14. "errors"
  15. "fmt"
  16. "io"
  17. "os"
  18. "slices"
  19. "strings"
  20. "sync"
  21. "github.com/charmbracelet/x/exp/slice"
  22. "mvdan.cc/sh/moreinterp/coreutils"
  23. "mvdan.cc/sh/v3/expand"
  24. "mvdan.cc/sh/v3/interp"
  25. "mvdan.cc/sh/v3/syntax"
  26. )
  27. // ShellType represents the type of shell to use
  28. type ShellType int
  29. const (
  30. ShellTypePOSIX ShellType = iota
  31. ShellTypeCmd
  32. ShellTypePowerShell
  33. )
  34. // Logger interface for optional logging
  35. type Logger interface {
  36. InfoPersist(msg string, keysAndValues ...any)
  37. }
  38. // noopLogger is a logger that does nothing
  39. type noopLogger struct{}
  40. func (noopLogger) InfoPersist(msg string, keysAndValues ...any) {}
  41. // BlockFunc is a function that determines if a command should be blocked
  42. type BlockFunc func(args []string) bool
  43. // Shell provides cross-platform shell execution with optional state persistence
  44. type Shell struct {
  45. env []string
  46. cwd string
  47. mu sync.Mutex
  48. logger Logger
  49. blockFuncs []BlockFunc
  50. customExecHandlers []func(interp.ExecHandlerFunc) interp.ExecHandlerFunc
  51. }
  52. // Options for creating a new shell
  53. type Options struct {
  54. WorkingDir string
  55. Env []string
  56. Logger Logger
  57. BlockFuncs []BlockFunc
  58. ExecHandlers []func(interp.ExecHandlerFunc) interp.ExecHandlerFunc
  59. }
  60. // NewShell creates a new shell instance with the given options
  61. func NewShell(opts *Options) *Shell {
  62. if opts == nil {
  63. opts = &Options{}
  64. }
  65. cwd := opts.WorkingDir
  66. if cwd == "" {
  67. cwd, _ = os.Getwd()
  68. }
  69. env := opts.Env
  70. if env == nil {
  71. env = os.Environ()
  72. }
  73. logger := opts.Logger
  74. if logger == nil {
  75. logger = noopLogger{}
  76. }
  77. return &Shell{
  78. cwd: cwd,
  79. env: env,
  80. logger: logger,
  81. blockFuncs: opts.BlockFuncs,
  82. customExecHandlers: opts.ExecHandlers,
  83. }
  84. }
  85. // Exec executes a command in the shell
  86. func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
  87. s.mu.Lock()
  88. defer s.mu.Unlock()
  89. return s.exec(ctx, command, nil)
  90. }
  91. // ExecWithStdin executes a command in the shell with provided stdin
  92. func (s *Shell) ExecWithStdin(ctx context.Context, command string, stdin io.Reader) (string, string, error) {
  93. s.mu.Lock()
  94. defer s.mu.Unlock()
  95. return s.exec(ctx, command, stdin)
  96. }
  97. // ExecStream executes a command in the shell with streaming output to provided writers
  98. func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
  99. s.mu.Lock()
  100. defer s.mu.Unlock()
  101. return s.execStream(ctx, command, stdout, stderr)
  102. }
  103. // GetWorkingDir returns the current working directory
  104. func (s *Shell) GetWorkingDir() string {
  105. s.mu.Lock()
  106. defer s.mu.Unlock()
  107. return s.cwd
  108. }
  109. // SetWorkingDir sets the working directory
  110. func (s *Shell) SetWorkingDir(dir string) error {
  111. s.mu.Lock()
  112. defer s.mu.Unlock()
  113. // Verify the directory exists
  114. if _, err := os.Stat(dir); err != nil {
  115. return fmt.Errorf("directory does not exist: %w", err)
  116. }
  117. s.cwd = dir
  118. return nil
  119. }
  120. // GetEnv returns a copy of the environment variables
  121. func (s *Shell) GetEnv() []string {
  122. s.mu.Lock()
  123. defer s.mu.Unlock()
  124. env := make([]string, len(s.env))
  125. copy(env, s.env)
  126. return env
  127. }
  128. // SetEnv sets an environment variable
  129. func (s *Shell) SetEnv(key, value string) {
  130. s.mu.Lock()
  131. defer s.mu.Unlock()
  132. // Update or add the environment variable
  133. keyPrefix := key + "="
  134. for i, env := range s.env {
  135. if strings.HasPrefix(env, keyPrefix) {
  136. s.env[i] = keyPrefix + value
  137. return
  138. }
  139. }
  140. s.env = append(s.env, keyPrefix+value)
  141. }
  142. // SetBlockFuncs sets the command block functions for the shell
  143. func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
  144. s.mu.Lock()
  145. defer s.mu.Unlock()
  146. s.blockFuncs = blockFuncs
  147. }
  148. // CommandsBlocker creates a BlockFunc that blocks exact command matches
  149. func CommandsBlocker(cmds []string) BlockFunc {
  150. bannedSet := make(map[string]struct{})
  151. for _, cmd := range cmds {
  152. bannedSet[cmd] = struct{}{}
  153. }
  154. return func(args []string) bool {
  155. if len(args) == 0 {
  156. return false
  157. }
  158. _, ok := bannedSet[args[0]]
  159. return ok
  160. }
  161. }
  162. // ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
  163. func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
  164. return func(parts []string) bool {
  165. if len(parts) == 0 || parts[0] != cmd {
  166. return false
  167. }
  168. argParts, flagParts := splitArgsFlags(parts[1:])
  169. if len(argParts) < len(args) || len(flagParts) < len(flags) {
  170. return false
  171. }
  172. argsMatch := slices.Equal(argParts[:len(args)], args)
  173. flagsMatch := slice.IsSubset(flags, flagParts)
  174. return argsMatch && flagsMatch
  175. }
  176. }
  177. func splitArgsFlags(parts []string) (args []string, flags []string) {
  178. args = make([]string, 0, len(parts))
  179. flags = make([]string, 0, len(parts))
  180. for _, part := range parts {
  181. if strings.HasPrefix(part, "-") {
  182. // Extract flag name before '=' if present
  183. flag := part
  184. if idx := strings.IndexByte(part, '='); idx != -1 {
  185. flag = part[:idx]
  186. }
  187. flags = append(flags, flag)
  188. } else {
  189. args = append(args, part)
  190. }
  191. }
  192. return args, flags
  193. }
  194. func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  195. return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  196. return func(ctx context.Context, args []string) error {
  197. if len(args) == 0 {
  198. return next(ctx, args)
  199. }
  200. for _, blockFunc := range s.blockFuncs {
  201. if blockFunc(args) {
  202. return fmt.Errorf("command is not allowed for security reasons: %s", strings.Join(args, " "))
  203. }
  204. }
  205. return next(ctx, args)
  206. }
  207. }
  208. }
  209. // newInterp creates a new interpreter with the current shell state
  210. func (s *Shell) newInterp(stdin io.Reader, stdout, stderr io.Writer) (*interp.Runner, error) {
  211. opts := []interp.RunnerOption{
  212. interp.StdIO(stdin, stdout, stderr),
  213. interp.Interactive(false),
  214. interp.Env(expand.ListEnviron(s.env...)),
  215. interp.Dir(s.cwd),
  216. interp.ExecHandlers(s.execHandlers()...),
  217. }
  218. return interp.New(opts...)
  219. }
  220. // updateShellFromRunner updates the shell from the interpreter after execution
  221. func (s *Shell) updateShellFromRunner(runner *interp.Runner) {
  222. s.cwd = runner.Dir
  223. s.env = nil
  224. for name, vr := range runner.Vars {
  225. s.env = append(s.env, fmt.Sprintf("%s=%s", name, vr.Str))
  226. }
  227. }
  228. // execCommon is the shared implementation for executing commands
  229. func (s *Shell) execCommon(ctx context.Context, command string, stdin io.Reader, stdout, stderr io.Writer) error {
  230. line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
  231. if err != nil {
  232. return fmt.Errorf("could not parse command: %w", err)
  233. }
  234. runner, err := s.newInterp(stdin, stdout, stderr)
  235. if err != nil {
  236. return fmt.Errorf("could not run command: %w", err)
  237. }
  238. err = runner.Run(ctx, line)
  239. s.updateShellFromRunner(runner)
  240. s.logger.InfoPersist("command finished", "command", command, "err", err)
  241. return err
  242. }
  243. // exec executes commands using a cross-platform shell interpreter.
  244. func (s *Shell) exec(ctx context.Context, command string, stdin io.Reader) (string, string, error) {
  245. var stdout, stderr bytes.Buffer
  246. err := s.execCommon(ctx, command, stdin, &stdout, &stderr)
  247. return stdout.String(), stderr.String(), err
  248. }
  249. // execStream executes commands using POSIX shell emulation with streaming output
  250. func (s *Shell) execStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
  251. return s.execCommon(ctx, command, nil, stdout, stderr)
  252. }
  253. func (s *Shell) execHandlers() []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  254. handlers := []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc{
  255. s.blockHandler(),
  256. }
  257. // Add custom exec handlers first (they get priority)
  258. handlers = append(handlers, s.customExecHandlers...)
  259. if useGoCoreUtils {
  260. handlers = append(handlers, coreutils.ExecHandler)
  261. }
  262. return handlers
  263. }
  264. // IsInterrupt checks if an error is due to interruption
  265. func IsInterrupt(err error) bool {
  266. return errors.Is(err, context.Canceled) ||
  267. errors.Is(err, context.DeadlineExceeded)
  268. }
  269. // ExitCode extracts the exit code from an error
  270. func ExitCode(err error) int {
  271. if err == nil {
  272. return 0
  273. }
  274. var exitErr interp.ExitStatus
  275. if errors.As(err, &exitErr) {
  276. return int(exitErr)
  277. }
  278. return 1
  279. }