shell.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. }
  51. // Options for creating a new shell
  52. type Options struct {
  53. WorkingDir string
  54. Env []string
  55. Logger Logger
  56. BlockFuncs []BlockFunc
  57. }
  58. // NewShell creates a new shell instance with the given options
  59. func NewShell(opts *Options) *Shell {
  60. if opts == nil {
  61. opts = &Options{}
  62. }
  63. cwd := opts.WorkingDir
  64. if cwd == "" {
  65. cwd, _ = os.Getwd()
  66. }
  67. env := opts.Env
  68. if env == nil {
  69. env = os.Environ()
  70. }
  71. logger := opts.Logger
  72. if logger == nil {
  73. logger = noopLogger{}
  74. }
  75. return &Shell{
  76. cwd: cwd,
  77. env: env,
  78. logger: logger,
  79. blockFuncs: opts.BlockFuncs,
  80. }
  81. }
  82. // Exec executes a command in the shell
  83. func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
  84. s.mu.Lock()
  85. defer s.mu.Unlock()
  86. return s.exec(ctx, command)
  87. }
  88. // ExecStream executes a command in the shell with streaming output to provided writers
  89. func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
  90. s.mu.Lock()
  91. defer s.mu.Unlock()
  92. return s.execStream(ctx, command, stdout, stderr)
  93. }
  94. // GetWorkingDir returns the current working directory
  95. func (s *Shell) GetWorkingDir() string {
  96. s.mu.Lock()
  97. defer s.mu.Unlock()
  98. return s.cwd
  99. }
  100. // SetWorkingDir sets the working directory
  101. func (s *Shell) SetWorkingDir(dir string) error {
  102. s.mu.Lock()
  103. defer s.mu.Unlock()
  104. // Verify the directory exists
  105. if _, err := os.Stat(dir); err != nil {
  106. return fmt.Errorf("directory does not exist: %w", err)
  107. }
  108. s.cwd = dir
  109. return nil
  110. }
  111. // GetEnv returns a copy of the environment variables
  112. func (s *Shell) GetEnv() []string {
  113. s.mu.Lock()
  114. defer s.mu.Unlock()
  115. env := make([]string, len(s.env))
  116. copy(env, s.env)
  117. return env
  118. }
  119. // SetEnv sets an environment variable
  120. func (s *Shell) SetEnv(key, value string) {
  121. s.mu.Lock()
  122. defer s.mu.Unlock()
  123. // Update or add the environment variable
  124. keyPrefix := key + "="
  125. for i, env := range s.env {
  126. if strings.HasPrefix(env, keyPrefix) {
  127. s.env[i] = keyPrefix + value
  128. return
  129. }
  130. }
  131. s.env = append(s.env, keyPrefix+value)
  132. }
  133. // SetBlockFuncs sets the command block functions for the shell
  134. func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
  135. s.mu.Lock()
  136. defer s.mu.Unlock()
  137. s.blockFuncs = blockFuncs
  138. }
  139. // CommandsBlocker creates a BlockFunc that blocks exact command matches
  140. func CommandsBlocker(cmds []string) BlockFunc {
  141. bannedSet := make(map[string]struct{})
  142. for _, cmd := range cmds {
  143. bannedSet[cmd] = struct{}{}
  144. }
  145. return func(args []string) bool {
  146. if len(args) == 0 {
  147. return false
  148. }
  149. _, ok := bannedSet[args[0]]
  150. return ok
  151. }
  152. }
  153. // ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
  154. func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
  155. return func(parts []string) bool {
  156. if len(parts) == 0 || parts[0] != cmd {
  157. return false
  158. }
  159. argParts, flagParts := splitArgsFlags(parts[1:])
  160. if len(argParts) < len(args) || len(flagParts) < len(flags) {
  161. return false
  162. }
  163. argsMatch := slices.Equal(argParts[:len(args)], args)
  164. flagsMatch := slice.IsSubset(flags, flagParts)
  165. return argsMatch && flagsMatch
  166. }
  167. }
  168. func splitArgsFlags(parts []string) (args []string, flags []string) {
  169. args = make([]string, 0, len(parts))
  170. flags = make([]string, 0, len(parts))
  171. for _, part := range parts {
  172. if strings.HasPrefix(part, "-") {
  173. // Extract flag name before '=' if present
  174. flag := part
  175. if idx := strings.IndexByte(part, '='); idx != -1 {
  176. flag = part[:idx]
  177. }
  178. flags = append(flags, flag)
  179. } else {
  180. args = append(args, part)
  181. }
  182. }
  183. return args, flags
  184. }
  185. func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  186. return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  187. return func(ctx context.Context, args []string) error {
  188. if len(args) == 0 {
  189. return next(ctx, args)
  190. }
  191. for _, blockFunc := range s.blockFuncs {
  192. if blockFunc(args) {
  193. return fmt.Errorf("command is not allowed for security reasons: %s", strings.Join(args, " "))
  194. }
  195. }
  196. return next(ctx, args)
  197. }
  198. }
  199. }
  200. // newInterp creates a new interpreter with the current shell state
  201. func (s *Shell) newInterp(stdout, stderr io.Writer) (*interp.Runner, error) {
  202. return interp.New(
  203. interp.StdIO(nil, stdout, stderr),
  204. interp.Interactive(false),
  205. interp.Env(expand.ListEnviron(s.env...)),
  206. interp.Dir(s.cwd),
  207. interp.ExecHandlers(s.execHandlers()...),
  208. )
  209. }
  210. // updateShellFromRunner updates the shell from the interpreter after execution.
  211. func (s *Shell) updateShellFromRunner(runner *interp.Runner) {
  212. s.cwd = runner.Dir
  213. s.env = s.env[:0]
  214. for name, vr := range runner.Vars {
  215. if vr.Exported {
  216. s.env = append(s.env, name+"="+vr.Str)
  217. }
  218. }
  219. }
  220. // execCommon is the shared implementation for executing commands
  221. func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr io.Writer) error {
  222. line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
  223. if err != nil {
  224. return fmt.Errorf("could not parse command: %w", err)
  225. }
  226. runner, err := s.newInterp(stdout, stderr)
  227. if err != nil {
  228. return fmt.Errorf("could not run command: %w", err)
  229. }
  230. err = runner.Run(ctx, line)
  231. s.updateShellFromRunner(runner)
  232. s.logger.InfoPersist("command finished", "command", command, "err", err)
  233. return err
  234. }
  235. // exec executes commands using a cross-platform shell interpreter.
  236. func (s *Shell) exec(ctx context.Context, command string) (string, string, error) {
  237. var stdout, stderr bytes.Buffer
  238. err := s.execCommon(ctx, command, &stdout, &stderr)
  239. return stdout.String(), stderr.String(), err
  240. }
  241. // execStream executes commands using POSIX shell emulation with streaming output
  242. func (s *Shell) execStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
  243. return s.execCommon(ctx, command, stdout, stderr)
  244. }
  245. func (s *Shell) execHandlers() []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  246. handlers := []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc{
  247. s.blockHandler(),
  248. }
  249. if useGoCoreUtils {
  250. handlers = append(handlers, coreutils.ExecHandler)
  251. }
  252. return handlers
  253. }
  254. // IsInterrupt checks if an error is due to interruption
  255. func IsInterrupt(err error) bool {
  256. return errors.Is(err, context.Canceled) ||
  257. errors.Is(err, context.DeadlineExceeded)
  258. }
  259. // ExitCode extracts the exit code from an error
  260. func ExitCode(err error) int {
  261. if err == nil {
  262. return 0
  263. }
  264. var exitErr interp.ExitStatus
  265. if errors.As(err, &exitErr) {
  266. return int(exitErr)
  267. }
  268. return 1
  269. }