1// Package shell provides cross-platform shell execution capabilities.
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
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.
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.execPOSIX(ctx, command)
106// GetWorkingDir returns the current working directory
107func (s *Shell) GetWorkingDir() string {
113// SetWorkingDir sets the working directory
114func (s *Shell) SetWorkingDir(dir string) error {
118 // Verify the directory exists
119 if _, err := os.Stat(dir); err != nil {
120 return fmt.Errorf("directory does not exist: %w", err)
127// GetEnv returns a copy of the environment variables
128func (s *Shell) GetEnv() []string {
132 env := make([]string, len(s.env))
137// SetEnv sets an environment variable
138func (s *Shell) SetEnv(key, value string) {
142 // Update or add the environment variable
143 keyPrefix := key + "="
144 for i, env := range s.env {
145 if strings.HasPrefix(env, keyPrefix) {
146 s.env[i] = keyPrefix + value
150 s.env = append(s.env, keyPrefix+value)
153// SetBlockFuncs sets the command block functions for the shell
154func (s *Shell) SetBlockFuncs(blockFuncs []BlockFunc) {
157 s.blockFuncs = blockFuncs
160// CommandsBlocker creates a BlockFunc that blocks exact command matches
161func CommandsBlocker(cmds []string) BlockFunc {
162 bannedSet := make(map[string]struct{})
163 for _, cmd := range cmds {
164 bannedSet[cmd] = struct{}{}
167 return func(args []string) bool {
171 _, ok := bannedSet[args[0]]
176// ArgumentsBlocker creates a BlockFunc that blocks specific subcommand
177func ArgumentsBlocker(cmd string, args []string, flags []string) BlockFunc {
178 return func(parts []string) bool {
179 if len(parts) == 0 || parts[0] != cmd {
183 argParts, flagParts := splitArgsFlags(parts[1:])
184 if len(argParts) < len(args) || len(flagParts) < len(flags) {
188 argsMatch := slices.Equal(argParts[:len(args)], args)
189 flagsMatch := slice.IsSubset(flags, flagParts)
191 return argsMatch && flagsMatch
195func splitArgsFlags(parts []string) (args []string, flags []string) {
196 args = make([]string, 0, len(parts))
197 flags = make([]string, 0, len(parts))
198 for _, part := range parts {
199 if strings.HasPrefix(part, "-") {
200 // Extract flag name before '=' if present
202 if idx := strings.IndexByte(part, '='); idx != -1 {
205 flags = append(flags, flag)
207 args = append(args, part)
213func (s *Shell) blockHandler() func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
214 return func(next interp.ExecHandlerFunc) interp.ExecHandlerFunc {
215 return func(ctx context.Context, args []string) error {
217 return next(ctx, args)
220 for _, blockFunc := range s.blockFuncs {
222 return fmt.Errorf("command is not allowed for security reasons: %s", strings.Join(args, " "))
226 return next(ctx, args)
231// execPOSIX executes commands using POSIX shell emulation (cross-platform)
232func (s *Shell) execPOSIX(ctx context.Context, command string) (string, string, error) {
233 line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
235 return "", "", fmt.Errorf("could not parse command: %w", err)
238 var stdout, stderr bytes.Buffer
239 runner, err := interp.New(
240 interp.StdIO(nil, &stdout, &stderr),
241 interp.Interactive(false),
242 interp.Env(expand.ListEnviron(s.env...)),
244 interp.ExecHandlers(s.blockHandler(), coreutils.ExecHandler),
247 return "", "", fmt.Errorf("could not run command: %w", err)
250 err = runner.Run(ctx, line)
253 for name, vr := range runner.Vars {
254 s.env = append(s.env, fmt.Sprintf("%s=%s", name, vr.Str))
256 s.logger.InfoPersist("POSIX command finished", "command", command, "err", err)
257 return stdout.String(), stderr.String(), err
260// IsInterrupt checks if an error is due to interruption
261func IsInterrupt(err error) bool {
262 return errors.Is(err, context.Canceled) ||
263 errors.Is(err, context.DeadlineExceeded)
266// ExitCode extracts the exit code from an error
267func ExitCode(err error) int {
271 var exitErr interp.ExitStatus
272 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