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/moreinterp/coreutils"
25 "mvdan.cc/sh/v3/expand"
26 "mvdan.cc/sh/v3/interp"
27 "mvdan.cc/sh/v3/syntax"
30// ShellType represents the type of shell to use
34 ShellTypePOSIX ShellType = iota
39// Logger interface for optional logging
40type Logger interface {
41 InfoPersist(msg string, keysAndValues ...any)
44// noopLogger is a logger that does nothing
45type noopLogger struct{}
47func (noopLogger) InfoPersist(msg string, keysAndValues ...any) {}
49// BlockFunc is a function that determines if a command should be blocked
50type BlockFunc func(args []string) bool
52// Shell provides cross-platform shell execution with optional state persistence
58 blockFuncs []BlockFunc
61// Options for creating a new shell
66 BlockFuncs []BlockFunc
69// NewShell creates a new shell instance with the given options
70func NewShell(opts *Options) *Shell {
75 cwd := opts.WorkingDir
94 blockFuncs: opts.BlockFuncs,
98// Exec executes a command in the shell
99func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
103 return s.exec(ctx, command)
106// ExecStream executes a command in the shell with streaming output to provided writers
107func (s *Shell) ExecStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
111 return s.execStream(ctx, command, stdout, stderr)
114// GetWorkingDir returns the current working directory
115func (s *Shell) GetWorkingDir() string {
121// SetWorkingDir sets the working directory
122func (s *Shell) SetWorkingDir(dir string) error {
126 // Verify the directory exists
127 if _, err := os.Stat(dir); err != nil {
128 return fmt.Errorf("directory does not exist: %w", err)
135// GetEnv returns a copy of the environment variables
136func (s *Shell) GetEnv() []string {
140 env := make([]string, len(s.env))
145// SetEnv sets an environment variable
146func (s *Shell) SetEnv(key, value string) {
150 // Update or add the environment variable
151 keyPrefix := key + "="
152 for i, env := range s.env {
153 if strings.HasPrefix(env, keyPrefix) {
154 s.env[i] = keyPrefix + value
158 s.env = append(s.env, keyPrefix+value)
161// SetBlockFuncs sets the command block functions for the shell
162func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
165 s.blockFuncs = blockFuncs
168// CommandsBlocker creates a BlockFunc that blocks exact command matches
169func CommandsBlocker(cmds []string) BlockFunc {
170 bannedSet := make(map[string]struct{})
171 for _, cmd := range cmds {
172 bannedSet[cmd] = struct{}{}
175 return func(args []string) bool {
179 _, ok := bannedSet[args[0]]
184// ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
185func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
186 return func(parts []string) bool {
187 if len(parts) == 0 || parts[0] != cmd {
191 argParts, flagParts := splitArgsFlags(parts[1:])
192 if len(argParts) < len(args) || len(flagParts) < len(flags) {
196 argsMatch := slices.Equal(argParts[:len(args)], args)
197 flagsMatch := slice.IsSubset(flags, flagParts)
199 return argsMatch && flagsMatch
203func splitArgsFlags(parts []string) (args []string, flags []string) {
204 args = make([]string, 0, len(parts))
205 flags = make([]string, 0, len(parts))
206 for _, part := range parts {
207 if strings.HasPrefix(part, "-") {
208 // Extract flag name before '=' if present
210 if before, _, ok := strings.Cut(part, "="); ok {
213 flags = append(flags, flag)
215 args = append(args, part)
221func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
222 return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
223 return func(ctx context.Context, args []string) error {
225 return next(ctx, args)
228 for _, blockFunc := range s.blockFuncs {
230 return fmt.Errorf("command is not allowed for security reasons: %q", args[0])
234 return next(ctx, args)
239// newInterp creates a new interpreter with the current shell state
240func (s *Shell) newInterp(stdout, stderr io.Writer) (*interp.Runner, error) {
242 interp.StdIO(nil, stdout, stderr),
243 interp.Interactive(false),
244 interp.Env(expand.ListEnviron(s.env...)),
246 interp.ExecHandlers(s.execHandlers()...),
250// updateShellFromRunner updates the shell from the interpreter after execution.
251func (s *Shell) updateShellFromRunner(runner *interp.Runner) {
254 for name, vr := range runner.Vars {
256 s.env = append(s.env, name+"="+vr.Str)
261// execCommon is the shared implementation for executing commands
262func (s *Shell) execCommon(ctx context.Context, command string, stdout, stderr io.Writer) (err error) {
263 var runner *interp.Runner
265 if r := recover(); r != nil {
266 err = fmt.Errorf("command execution panic: %v", r)
269 s.updateShellFromRunner(runner)
271 s.logger.InfoPersist("command finished", "command", command, "err", err)
274 line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
276 return fmt.Errorf("could not parse command: %w", err)
279 runner, err = s.newInterp(stdout, stderr)
281 return fmt.Errorf("could not run command: %w", err)
284 err = runner.Run(ctx, line)
288// exec executes commands using a cross-platform shell interpreter.
289func (s *Shell) exec(ctx context.Context, command string) (string, string, error) {
290 var stdout, stderr bytes.Buffer
291 err := s.execCommon(ctx, command, &stdout, &stderr)
292 return stdout.String(), stderr.String(), err
295// execStream executes commands using POSIX shell emulation with streaming output
296func (s *Shell) execStream(ctx context.Context, command string, stdout, stderr io.Writer) error {
297 return s.execCommon(ctx, command, stdout, stderr)
300func (s *Shell) execHandlers() []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
301 handlers := []func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc{
305 handlers = append(handlers, coreutils.ExecHandler)
310// IsInterrupt checks if an error is due to interruption
311func IsInterrupt(err error) bool {
312 return errors.Is(err, context.Canceled) ||
313 errors.Is(err, context.DeadlineExceeded)
316// ExitCode extracts the exit code from an error
317func ExitCode(err error) int {
321 var exitErr interp.ExitStatus
322 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