shell.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. // Package shell provides cross-platform shell execution capabilities.
  2. //
  3. // This package offers two main types:
  4. // - Shell: A general-purpose shell executor for one-off or managed commands
  5. // - PersistentShell: A singleton shell that maintains state across the application
  6. //
  7. // WINDOWS COMPATIBILITY:
  8. // This implementation provides both POSIX shell emulation (mvdan.cc/sh/v3),
  9. // even on Windows. Some caution has to be taken: commands should have forward
  10. // slashes (/) as path separators to work, even on Windows.
  11. package shell
  12. import (
  13. "bytes"
  14. "context"
  15. "errors"
  16. "fmt"
  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.execPOSIX(ctx, command)
  87. }
  88. // GetWorkingDir returns the current working directory
  89. func (s *Shell) GetWorkingDir() string {
  90. s.mu.Lock()
  91. defer s.mu.Unlock()
  92. return s.cwd
  93. }
  94. // SetWorkingDir sets the working directory
  95. func (s *Shell) SetWorkingDir(dir string) error {
  96. s.mu.Lock()
  97. defer s.mu.Unlock()
  98. // Verify the directory exists
  99. if _, err := os.Stat(dir); err != nil {
  100. return fmt.Errorf("directory does not exist: %w", err)
  101. }
  102. s.cwd = dir
  103. return nil
  104. }
  105. // GetEnv returns a copy of the environment variables
  106. func (s *Shell) GetEnv() []string {
  107. s.mu.Lock()
  108. defer s.mu.Unlock()
  109. env := make([]string, len(s.env))
  110. copy(env, s.env)
  111. return env
  112. }
  113. // SetEnv sets an environment variable
  114. func (s *Shell) SetEnv(key, value string) {
  115. s.mu.Lock()
  116. defer s.mu.Unlock()
  117. // Update or add the environment variable
  118. keyPrefix := key + "="
  119. for i, env := range s.env {
  120. if strings.HasPrefix(env, keyPrefix) {
  121. s.env[i] = keyPrefix + value
  122. return
  123. }
  124. }
  125. s.env = append(s.env, keyPrefix+value)
  126. }
  127. // SetBlockFuncs sets the command block functions for the shell
  128. func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
  129. s.mu.Lock()
  130. defer s.mu.Unlock()
  131. s.blockFuncs = blockFuncs
  132. }
  133. // CommandsBlocker creates a BlockFunc that blocks exact command matches
  134. func CommandsBlocker(cmds []string) BlockFunc {
  135. bannedSet := make(map[string]struct{})
  136. for _, cmd := range cmds {
  137. bannedSet[cmd] = struct{}{}
  138. }
  139. return func(args []string) bool {
  140. if len(args) == 0 {
  141. return false
  142. }
  143. _, ok := bannedSet[args[0]]
  144. return ok
  145. }
  146. }
  147. // ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
  148. func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
  149. return func(parts []string) bool {
  150. if len(parts) == 0 || parts[0] != cmd {
  151. return false
  152. }
  153. argParts, flagParts := splitArgsFlags(parts[1:])
  154. if len(argParts) < len(args) || len(flagParts) < len(flags) {
  155. return false
  156. }
  157. argsMatch := slices.Equal(argParts[:len(args)], args)
  158. flagsMatch := slice.IsSubset(flags, flagParts)
  159. return argsMatch && flagsMatch
  160. }
  161. }
  162. func splitArgsFlags(parts []string) (args []string, flags []string) {
  163. args = make([]string, 0, len(parts))
  164. flags = make([]string, 0, len(parts))
  165. for _, part := range parts {
  166. if strings.HasPrefix(part, "-") {
  167. // Extract flag name before '=' if present
  168. flag := part
  169. if idx := strings.IndexByte(part, '='); idx != -1 {
  170. flag = part[:idx]
  171. }
  172. flags = append(flags, flag)
  173. } else {
  174. args = append(args, part)
  175. }
  176. }
  177. return args, flags
  178. }
  179. func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  180. return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
  181. return func(ctx context.Context, args []string) error {
  182. if len(args) == 0 {
  183. return next(ctx, args)
  184. }
  185. for _, blockFunc := range s.blockFuncs {
  186. if blockFunc(args) {
  187. return fmt.Errorf("command is not allowed for security reasons: %s", strings.Join(args, " "))
  188. }
  189. }
  190. return next(ctx, args)
  191. }
  192. }
  193. }
  194. // execPOSIX executes commands using POSIX shell emulation (cross-platform)
  195. func (s *Shell) execPOSIX(ctx context.Context, command string) (string, string, error) {
  196. line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
  197. if err != nil {
  198. return "", "", fmt.Errorf("could not parse command: %w", err)
  199. }
  200. var stdout, stderr bytes.Buffer
  201. runner, err := interp.New(
  202. interp.StdIO(nil, &stdout, &stderr),
  203. interp.Interactive(false),
  204. interp.Env(expand.ListEnviron(s.env...)),
  205. interp.Dir(s.cwd),
  206. interp.ExecHandlers(s.blockHandler(), coreutils.ExecHandler),
  207. )
  208. if err != nil {
  209. return "", "", fmt.Errorf("could not run command: %w", err)
  210. }
  211. err = runner.Run(ctx, line)
  212. s.cwd = runner.Dir
  213. s.env = []string{}
  214. for name, vr := range runner.Vars {
  215. s.env = append(s.env, fmt.Sprintf("%s=%s", name, vr.Str))
  216. }
  217. s.logger.InfoPersist("POSIX command finished", "command", command, "err", err)
  218. return stdout.String(), stderr.String(), err
  219. }
  220. // IsInterrupt checks if an error is due to interruption
  221. func IsInterrupt(err error) bool {
  222. return errors.Is(err, context.Canceled) ||
  223. errors.Is(err, context.DeadlineExceeded)
  224. }
  225. // ExitCode extracts the exit code from an error
  226. func ExitCode(err error) int {
  227. if err == nil {
  228. return 0
  229. }
  230. var exitErr interp.ExitStatus
  231. if errors.As(err, &exitErr) {
  232. return int(exitErr)
  233. }
  234. return 1
  235. }