1// Package shell provides cross-platform shell execution capabilities.
3// This package provides Shell instances for executing commands with their own
4// working directory and environment. Each shell execution is independent.
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.
23 "github.com/charmbracelet/x/exp/slice"
24 "mvdan.cc/sh/v3/interp"
25 "mvdan.cc/sh/v3/syntax"
28// ShellType represents the type of shell to use
32 ShellTypePOSIX ShellType = iota
37// CrushEnvMarkers returns a fresh slice of the environment variables that
38// Crush unconditionally sets on every shell it spawns — both the interactive
39// bash tool's [Shell] and the hook runner's [Run] calls. Tools that want to
40// detect "am I being invoked by an AI agent?" can check any of these.
41// Keeping them in one place guarantees the two shell surfaces cannot drift.
42// A fresh slice is returned on every call so callers may append freely.
43func CrushEnvMarkers() []string {
51// Logger interface for optional logging
52type Logger interface {
53 InfoPersist(msg string, keysAndValues ...any)
56// noopLogger is a logger that does nothing
57type noopLogger struct{}
59func (noopLogger) InfoPersist(msg string, keysAndValues ...any) {}
61// BlockFunc is a function that determines if a command should be blocked
62type BlockFunc func(args []string) bool
64// Shell provides cross-platform shell execution with optional state persistence
70 blockFuncs []BlockFunc
73// Options for creating a new shell
78 BlockFuncs []BlockFunc
81// NewShell creates a new shell instance with the given options
82func NewShell(opts *Options) *Shell {
87 cwd := opts.WorkingDir
97 // Allow tools to detect execution by Crush.
98 env = append(env, CrushEnvMarkers()...)
100 logger := opts.Logger
102 logger = noopLogger{}
109 blockFuncs: opts.BlockFuncs,
113// Exec executes a command in the shell
114func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
118 return s.exec(ctx, command)
121// ExecStream executes a command in the shell with streaming output to provided writers
122func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
126 return s.execStream(ctx, command, stdout, stderr)
129// GetWorkingDir returns the current working directory
130func (s *Shell) GetWorkingDir() string {
136// SetWorkingDir sets the working directory
137func (s *Shell) SetWorkingDir(dir string) error {
141 // Verify the directory exists
142 if _, err := os.Stat(dir); err != nil {
143 return fmt.Errorf("directory does not exist: %w", err)
150// GetEnv returns a copy of the environment variables
151func (s *Shell) GetEnv() []string {
155 env := make([]string, len(s.env))
160// SetEnv sets an environment variable
161func (s *Shell) SetEnv(key, value string) {
165 // Update or add the environment variable
166 keyPrefix := key + "="
167 for i, env := range s.env {
168 if strings.HasPrefix(env, keyPrefix) {
169 s.env[i] = keyPrefix + value
173 s.env = append(s.env, keyPrefix+value)
176// SetBlockFuncs sets the command block functions for the shell
177func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
180 s.blockFuncs = blockFuncs
183// CommandsBlocker creates a BlockFunc that blocks exact command matches
184func CommandsBlocker(cmds []string) BlockFunc {
185 bannedSet := make(map[string]struct{})
186 for _, cmd := range cmds {
187 bannedSet[cmd] = struct{}{}
190 return func(args []string) bool {
194 _, ok := bannedSet[args[0]]
199// ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
200func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
201 return func(parts []string) bool {
202 if len(parts) == 0 || parts[0] != cmd {
206 argParts, flagParts := splitArgsFlags(parts[1:])
207 if len(argParts) < len(args) || len(flagParts) < len(flags) {
211 argsMatch := slices.Equal(argParts[:len(args)], args)
212 flagsMatch := slice.IsSubset(flags, flagParts)
214 return argsMatch && flagsMatch
218func splitArgsFlags(parts []string) (args []string, flags []string) {
219 args = make([]string, 0, len(parts))
220 flags = make([]string, 0, len(parts))
221 for _, part := range parts {
222 if strings.HasPrefix(part, "-") {
223 // Extract flag name before '=' if present
225 if before, _, ok := strings.Cut(part, "="); ok {
228 flags = append(flags, flag)
230 args = append(args, part)
236// newInterp creates a new interpreter with the current shell state. A nil
237// stdin is equivalent to an empty input stream.
238func (s *Shell) newInterp(stdin io.Reader, stdout, stderr io.Writer) (*interp.Runner, error) {
239 return newRunner(s.cwd, s.env, stdin, stdout, stderr, s.blockFuncs)
242// updateShellFromRunner updates the shell from the interpreter after execution.
243func (s *Shell) updateShellFromRunner(runner *interp.Runner) {
246 for name, vr := range runner.Vars {
248 s.env = append(s.env, name+"="+vr.Str)
253// execCommon is the shared implementation for executing commands
254func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr io.Writer) (err error) {
255 var runner *interp.Runner
257 if r := recover(); r != nil {
258 err = fmt.Errorf("command execution panic: %v", r)
261 s.updateShellFromRunner(runner)
263 s.logger.InfoPersist("command finished", "command", command, "err", err)
266 line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
268 return fmt.Errorf("could not parse command: %w", err)
271 runner, err = s.newInterp(nil, stdout, stderr)
273 return fmt.Errorf("could not run command: %w", err)
276 err = runner.Run(ctx, line)
280// exec executes commands using a cross-platform shell interpreter.
281func (s *Shell) exec(ctx context.Context, command string) (string, string, error) {
282 var stdout, stderr bytes.Buffer
283 err := s.execCommon(ctx, command, &stdout, &stderr)
284 return stdout.String(), stderr.String(), err
287// execStream executes commands using POSIX shell emulation with streaming output
288func (s *Shell) execStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
289 return s.execCommon(ctx, command, stdout, stderr)
292// IsInterrupt checks if an error is due to interruption
293func IsInterrupt(err error) bool {
294 return errors.Is(err, context.Canceled) ||
295 errors.Is(err, context.DeadlineExceeded)
298// ExitCode extracts the exit code from an error
299func ExitCode(err error) int {
303 if exitErr, ok := errors.AsType[interp.ExitStatus](err); ok {
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list