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) and
9// native Windows shell support (cmd.exe/PowerShell) for optimal compatibility.
23 "mvdan.cc/sh/v3/expand"
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 ...interface{})
42// noopLogger is a logger that does nothing
43type noopLogger struct{}
45func (noopLogger) InfoPersist(msg string, keysAndValues ...interface{}) {}
47// Shell provides cross-platform shell execution with optional state persistence
55// Options for creating a new shell
62// NewShell creates a new shell instance with the given options
63func NewShell(opts *Options) *Shell {
68 cwd := opts.WorkingDir
90// Exec executes a command in the shell
91func (s *Shell) Exec(ctx context.Context, command string) (string, string, error) {
95 // Determine which shell to use based on platform and command
96 shellType := s.determineShellType(command)
100 return s.execWindows(ctx, command, "cmd")
101 case ShellTypePowerShell:
102 return s.execWindows(ctx, command, "powershell")
104 return s.execPOSIX(ctx, command)
108// GetWorkingDir returns the current working directory
109func (s *Shell) GetWorkingDir() string {
115// SetWorkingDir sets the working directory
116func (s *Shell) SetWorkingDir(dir string) error {
120 // Verify the directory exists
121 if _, err := os.Stat(dir); err != nil {
122 return fmt.Errorf("directory does not exist: %w", err)
129// GetEnv returns a copy of the environment variables
130func (s *Shell) GetEnv() []string {
134 env := make([]string, len(s.env))
139// SetEnv sets an environment variable
140func (s *Shell) SetEnv(key, value string) {
144 // Update or add the environment variable
145 keyPrefix := key + "="
146 for i, env := range s.env {
147 if strings.HasPrefix(env, keyPrefix) {
148 s.env[i] = keyPrefix + value
152 s.env = append(s.env, keyPrefix+value)
155// Windows-specific commands that should use native shell
156var windowsNativeCommands = map[string]bool{
176// determineShellType decides which shell to use based on platform and command
177func (s *Shell) determineShellType(command string) ShellType {
178 if runtime.GOOS != "windows" {
179 return ShellTypePOSIX
182 // Extract the first command from the command line
183 parts := strings.Fields(command)
185 return ShellTypePOSIX
188 firstCmd := strings.ToLower(parts[0])
190 // Check if it's a Windows-specific command
191 if windowsNativeCommands[firstCmd] {
195 // Check for PowerShell-specific syntax
196 if strings.Contains(command, "Get-") || strings.Contains(command, "Set-") ||
197 strings.Contains(command, "New-") || strings.Contains(command, "$_") ||
198 strings.Contains(command, "| Where-Object") || strings.Contains(command, "| ForEach-Object") {
199 return ShellTypePowerShell
202 // Default to POSIX emulation for cross-platform compatibility
203 return ShellTypePOSIX
206// execWindows executes commands using native Windows shells (cmd.exe or PowerShell)
207func (s *Shell) execWindows(ctx context.Context, command string, shell string) (string, string, error) {
210 // Handle directory changes specially to maintain persistent shell behavior
211 if strings.HasPrefix(strings.TrimSpace(command), "cd ") {
212 return s.handleWindowsCD(command)
217 // Use cmd.exe for Windows commands
218 // Add current directory context to maintain state
219 fullCommand := fmt.Sprintf("cd /d \"%s\" && %s", s.cwd, command)
220 cmd = exec.CommandContext(ctx, "cmd", "/C", fullCommand)
222 // Use PowerShell for PowerShell commands
223 // Add current directory context to maintain state
224 fullCommand := fmt.Sprintf("Set-Location '%s'; %s", s.cwd, command)
225 cmd = exec.CommandContext(ctx, "powershell", "-Command", fullCommand)
227 return "", "", fmt.Errorf("unsupported Windows shell: %s", shell)
230 // Set environment variables
233 var stdout, stderr bytes.Buffer
239 s.logger.InfoPersist("Windows command finished", "shell", shell, "command", command, "err", err)
240 return stdout.String(), stderr.String(), err
243// handleWindowsCD handles directory changes for Windows shells
244func (s *Shell) handleWindowsCD(command string) (string, string, error) {
245 // Extract the target directory from the cd command
246 parts := strings.Fields(command)
248 return "", "cd: missing directory argument", fmt.Errorf("missing directory argument")
251 targetDir := parts[1]
253 // Handle relative paths
254 if !strings.Contains(targetDir, ":") && !strings.HasPrefix(targetDir, "\\") {
255 // Relative path - resolve against current directory
256 if targetDir == ".." {
257 // Go up one directory
258 if len(s.cwd) > 3 { // Don't go above drive root (C:\)
259 lastSlash := strings.LastIndex(s.cwd, "\\")
260 if lastSlash > 2 { // Keep drive letter
261 s.cwd = s.cwd[:lastSlash]
264 } else if targetDir != "." {
265 // Go to subdirectory
266 s.cwd = s.cwd + "\\" + targetDir
273 // Verify the directory exists
274 if _, err := os.Stat(s.cwd); err != nil {
275 return "", fmt.Sprintf("cd: %s: No such file or directory", targetDir), err
281// execPOSIX executes commands using POSIX shell emulation (cross-platform)
282func (s *Shell) execPOSIX(ctx context.Context, command string) (string, string, error) {
283 line, err := syntax.NewParser().Parse(strings.NewReader(command), "")
285 return "", "", fmt.Errorf("could not parse command: %w", err)
288 var stdout, stderr bytes.Buffer
289 runner, err := interp.New(
290 interp.StdIO(nil, &stdout, &stderr),
291 interp.Interactive(false),
292 interp.Env(expand.ListEnviron(s.env...)),
296 return "", "", fmt.Errorf("could not run command: %w", err)
299 err = runner.Run(ctx, line)
302 for name, vr := range runner.Vars {
303 s.env = append(s.env, fmt.Sprintf("%s=%s", name, vr.Str))
305 s.logger.InfoPersist("POSIX command finished", "command", command, "err", err)
306 return stdout.String(), stderr.String(), err
309// IsInterrupt checks if an error is due to interruption
310func IsInterrupt(err error) bool {
311 return errors.Is(err, context.Canceled) ||
312 errors.Is(err, context.DeadlineExceeded)
315// ExitCode extracts the exit code from an error
316func ExitCode(err error) int {
320 status, ok := interp.IsExitStatus(err)
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