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// Logger interface for optional logging
38type Logger interface {
39 InfoPersist(msg string, keysAndValues ...any)
42// noopLogger is a logger that does nothing
43type noopLogger struct{}
45func (noopLogger) InfoPersist(msg string, keysAndValues ...any) {}
47// BlockFunc is a function that determines if a command should be blocked
48type BlockFunc func(args []string) bool
50// Shell provides cross-platform shell execution with optional state persistence
56 blockFuncs []BlockFunc
59// Options for creating a new shell
64 BlockFuncs []BlockFunc
67// NewShell creates a new shell instance with the given options
68func NewShell(opts *Options) *Shell {
73 cwd := opts.WorkingDir
83 // Allow tools to detect execution by Crush.
100 blockFuncs: opts.BlockFuncs,
104// Exec executes a command in the shell
105func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
109 return s.exec(ctx, command)
112// ExecStream executes a command in the shell with streaming output to provided writers
113func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
117 return s.execStream(ctx, command, stdout, stderr)
120// GetWorkingDir returns the current working directory
121func (s *Shell) GetWorkingDir() string {
127// SetWorkingDir sets the working directory
128func (s *Shell) SetWorkingDir(dir string) error {
132 // Verify the directory exists
133 if _, err := os.Stat(dir); err != nil {
134 return fmt.Errorf("directory does not exist: %w", err)
141// GetEnv returns a copy of the environment variables
142func (s *Shell) GetEnv() []string {
146 env := make([]string, len(s.env))
151// SetEnv sets an environment variable
152func (s *Shell) SetEnv(key, value string) {
156 // Update or add the environment variable
157 keyPrefix := key + "="
158 for i, env := range s.env {
159 if strings.HasPrefix(env, keyPrefix) {
160 s.env[i] = keyPrefix + value
164 s.env = append(s.env, keyPrefix+value)
167// SetBlockFuncs sets the command block functions for the shell
168func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
171 s.blockFuncs = blockFuncs
174// CommandsBlocker creates a BlockFunc that blocks exact command matches
175func CommandsBlocker(cmds []string) BlockFunc {
176 bannedSet := make(map[string]struct{})
177 for _, cmd := range cmds {
178 bannedSet[cmd] = struct{}{}
181 return func(args []string) bool {
185 _, ok := bannedSet[args[0]]
190// ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
191func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
192 return func(parts []string) bool {
193 if len(parts) == 0 || parts[0] != cmd {
197 argParts, flagParts := splitArgsFlags(parts[1:])
198 if len(argParts) < len(args) || len(flagParts) < len(flags) {
202 argsMatch := slices.Equal(argParts[:len(args)], args)
203 flagsMatch := slice.IsSubset(flags, flagParts)
205 return argsMatch && flagsMatch
209func splitArgsFlags(parts []string) (args []string, flags []string) {
210 args = make([]string, 0, len(parts))
211 flags = make([]string, 0, len(parts))
212 for _, part := range parts {
213 if strings.HasPrefix(part, "-") {
214 // Extract flag name before '=' if present
216 if before, _, ok := strings.Cut(part, "="); ok {
219 flags = append(flags, flag)
221 args = append(args, part)
227// newInterp creates a new interpreter with the current shell state. A nil
228// stdin is equivalent to an empty input stream.
229func (s *Shell) newInterp(stdin io.Reader, stdout, stderr io.Writer) (*interp.Runner, error) {
230 return newRunner(s.cwd, s.env, stdin, stdout, stderr, s.blockFuncs)
233// updateShellFromRunner updates the shell from the interpreter after execution.
234func (s *Shell) updateShellFromRunner(runner *interp.Runner) {
237 for name, vr := range runner.Vars {
239 s.env = append(s.env, name+"="+vr.Str)
244// execCommon is the shared implementation for executing commands
245func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr io.Writer) (err error) {
246 var runner *interp.Runner
248 if r := recover(); r != nil {
249 err = fmt.Errorf("command execution panic: %v", r)
252 s.updateShellFromRunner(runner)
254 s.logger.InfoPersist("command finished", "command", command, "err", err)
257 line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
259 return fmt.Errorf("could not parse command: %w", err)
262 runner, err = s.newInterp(nil, stdout, stderr)
264 return fmt.Errorf("could not run command: %w", err)
267 err = runner.Run(ctx, line)
271// exec executes commands using a cross-platform shell interpreter.
272func (s *Shell) exec(ctx context.Context, command string) (string, string, error) {
273 var stdout, stderr bytes.Buffer
274 err := s.execCommon(ctx, command, &stdout, &stderr)
275 return stdout.String(), stderr.String(), err
278// execStream executes commands using POSIX shell emulation with streaming output
279func (s *Shell) execStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
280 return s.execCommon(ctx, command, stdout, stderr)
283// IsInterrupt checks if an error is due to interruption
284func IsInterrupt(err error) bool {
285 return errors.Is(err, context.Canceled) ||
286 errors.Is(err, context.DeadlineExceeded)
289// ExitCode extracts the exit code from an error
290func ExitCode(err error) int {
294 var exitErr interp.ExitStatus
295 if errors.As(err, &exitErr) {
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