返回 DeepSeek-Reasonix
bash.go
根目录 / internal / tool / builtin / bash.go
1 package builtin
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "runtime"
12 "slices"
13 "strings"
14 "time"
15
16 "mvdan.cc/sh/v3/syntax"
17
18 "reasonix/internal/persistentshell"
19 "reasonix/internal/proc"
20 "reasonix/internal/sandbox"
21 "reasonix/internal/secrets"
22 "reasonix/internal/sessiontemp"
23 "reasonix/internal/shellparse"
24 "reasonix/internal/shellrun"
25 "reasonix/internal/tool"
26 )
27
28 const (
29 bashWaitDelay = 5 * time.Second
30 )
31
32 func init() { tool.RegisterBuiltin(bash{}) }
33
34 var bashSandboxCommand = sandbox.Command
35
36 // bash runs a shell command. sb, when it enforces, wraps the command in an OS
37 // sandbox; the zero value registered at init runs unconfined and is overridden
38 // per run by ConfineBash. shell is the resolved interpreter (real bash, or
39 // PowerShell on a Windows host without bash); the zero value resolves lazily.
40 // workDir, when non-empty, is the directory the command runs in (cmd.Dir);
41 // empty uses the process cwd. timeout optionally caps foreground commands;
42 // zero or negative means no tool-local cap, while parent context cancellation
43 // still kills the process tree. guard appends a warning to the output of
44 // commands that reference Reasonix's own session stores (see SessionDataGuard).
45 // sessionTemp, when non-nil, supplies the logical-session private temporary
46 // directory shared across shell calls (see package sessiontemp). A Manager on
47 // the execution context overrides this for sub-agent isolation.
48 type bash struct {
49 name string
50 sb sandbox.Spec
51 rootSet *sandbox.WritableRootSet
52 shell sandbox.Shell
53 guard SessionDataGuard
54 workDir string
55 timeout time.Duration
56 // terminal, when non-nil, runs foreground commands in a host-owned terminal
57 // (ACP terminal/*). Only consulted when the local OS sandbox is not
58 // enforcing — a host terminal cannot honor the confinement configuration —
59 // and never for background jobs, which need the local job manager.
60 terminal TerminalRunner
61 sessionTemp *sessiontemp.Manager
62 // persistent runs ordinary foreground commands in a session PTY. A
63 // context-attached manager isolates sub-agents. Nil keeps one-shot processes.
64 persistent *persistentshell.Manager
65 }
66
67 type bashParams struct {
68 Command string `json:"command"`
69 Description string `json:"description,omitempty"`
70 TimeoutMS int `json:"timeout_ms,omitempty"`
71 RunInBackground bool `json:"run_in_background"`
72 PreserveBackgroundProcesses bool `json:"preserve_background_processes"`
73 AdditionalWriteDirs []string `json:"additional_write_dirs,omitempty"`
74 Justification string `json:"justification,omitempty"`
75 SandboxPermissions string `json:"sandbox_permissions,omitempty"`
76 DenialID string `json:"denial_id,omitempty"`
77 }
78
79 func (b bash) Name() string {
80 if strings.TrimSpace(b.name) != "" {
81 return b.name
82 }
83 return "bash"
84 }
85
86 func (b bash) Description() string {
87 sh := b.resolved()
88 if sh.Kind == sandbox.ShellPowerShell {
89 return "Execute one PowerShell command in an isolated process and return combined stdout/stderr. " +
90 "The host prefers PowerShell 7 and can fall back to Windows PowerShell 5.1, so use syntax accepted by both:\n" +
91 " - chaining: ';' runs both commands; use 'if ($?) { ... }' for conditional execution.\n" +
92 " - redirect/vars: $null not /dev/null; $env:VAR not $VAR; '2>$null' drops stderr.\n" +
93 " - file ops: Get-ChildItem (ls), Remove-Item -Recurse -Force (rm -rf), Copy-Item (cp), Select-String (grep).\n" +
94 " - file text: read with read_file and change with edit_file/write_file, not Get-Content, Set-Content, Out-File or '>'. Windows PowerShell 5.1 reads BOM-less UTF-8 as the ANSI code page and writes ANSI or UTF-16; the built-in tools keep each file's encoding and BOM.\n" +
95 " - no head/tail/which/touch: use Select-Object -First/-Last N, (Get-Command x).Source, New-Item.\n" +
96 " - services/watchers: set run_in_background=true and manage the returned job id with job_output/job_kill.\n" +
97 " - multi-line text to a native exe (e.g. git commit -m): use a single-quoted here-string @'...'@ (closing '@ at column 0)." +
98 bashToolSteer
99 }
100 return "Execute a command in the shell and return combined stdout/stderr. " +
101 "To write outside the workspace, pass additional_write_dirs with the smallest concrete directories (no globs; absolute, workspace-relative, ~, or ${HOME}) and a justification. " +
102 "The host will not infer write paths from the command text." + bashToolSteer
103 }
104
105 // bashToolSteer points the model at the cross-platform built-in tools instead of
106 // shell utilities, so it doesn't reach for grep/cat/ls/find (absent or different
107 // on native Windows) when a native tool already does the job everywhere.
108 const bashToolSteer = " Use for builds, tests, git, package managers, etc. To search/read/list/edit/move files, prefer the dedicated tools (grep, read_file, ls, glob, edit_file, move_file) over shell grep/cat/ls/find/sed/mv/Move-Item — they behave identically on every OS. For symbol search or architecture questions, prefer LSP/read tools and targeted grep before shell commands."
109
110 // resolved returns the bound shell, resolving lazily for the zero-value instance
111 // (e.g. a registry that never went through ConfineBash).
112 func (b bash) resolved() sandbox.Shell {
113 if b.shell.Path != "" {
114 return b.shell
115 }
116 if b.sb.Shell.Path != "" {
117 return b.sb.Shell
118 }
119 return sandbox.ResolveShell("", "", nil)
120 }
121
122 // ReadOnly is false: bash's effect cannot be inferred from args (rm, curl,
123 // git commit, etc. are all reachable). Conservative even when a particular
124 // command happens to be read-only — the agent batch decision can't tell.
125 func (bash) ReadOnly() bool { return false }
126
127 // SnipHint keeps both ends of command output equally: a build/test run's
128 // failure usually sits at the tail while the command and early context sit at
129 // the head, so neither end can be favored.
130 func (bash) SnipHint() tool.SnipHint {
131 return tool.SnipHint{Head: 40, Tail: 40, HeadChars: 8000, TailChars: 8000}
132 }
133
134 // Execute is the compatibility wrapper: all structured metadata is produced by
135 // ExecuteDetailed and discarded here so plugin/hook callers keep the old shape.
136 func (b bash) Execute(ctx context.Context, args json.RawMessage) (string, error) {
137 res, err := b.ExecuteDetailed(ctx, args)
138 return res.Output, err
139 }
140
141 // ExecutionDescriptor returns shell identity for the bound interpreter without
142 // launching a process. Invalid args still yield a descriptor from the shell.
143 func (b bash) ExecutionDescriptor(args json.RawMessage) *tool.ShellExecution {
144 return shellrun.DescriptorFromShell(b.resolved())
145 }
146
147 // ExecuteDetailed runs the shell command and returns structured execution
148 // metadata for host UI / session persistence. Provider-visible output stays in
149 // DetailedResult.Output; metadata never enters tool schemas.
150 func (b bash) ExecuteDetailed(ctx context.Context, args json.RawMessage) (tool.DetailedResult, error) {
151 start := time.Now()
152 ex := shellrun.DescriptorFromShell(b.resolved())
153 ex.State = tool.ShellStateRunning
154 ex.MutationRisk = tool.ShellMutationUnknown
155 ex.Verification = tool.ShellVerificationNotVerification
156
157 var p bashParams
158 if err := json.Unmarshal(args, &p); err != nil {
159 return bashPreflightFailure(ex, start, fmt.Errorf("invalid args: %w", err))
160 }
161 if err := validateBashParams(p); err != nil {
162 return bashPreflightFailure(ex, start, err)
163 }
164
165 sh := b.resolved()
166 if err := sandbox.ValidateShellPolicy(b.specForCall(ctx), sh); err != nil {
167 return bashPreflightFailure(ex, start, err)
168 }
169 if res, err, reject := rejectPowerShellChaining(ex, start, sh, p.Command); reject {
170 return res, err
171 }
172
173 // Pin the session-private temporary generation before any launch path so
174 // foreground, background, and host-terminal runs share one directory, and
175 // so a failed start still releases the lease.
176 prepared, lease, err := b.prepareLaunch(ctx, sh, p.Command, args)
177 if err != nil {
178 return bashLaunchFailure(ex, start, err)
179 }
180 // Background jobs take ownership of the lease until the job goroutine ends.
181 // Foreground/terminal paths release after the process exits.
182 releaseLease := true
183 defer func() {
184 if releaseLease && lease != nil {
185 lease.Release()
186 }
187 }()
188
189 // A host-owned terminal runs the command where the user watches it live.
190 // Never when the OS sandbox is enforcing (the host cannot honor the local
191 // confinement config), never when [secrets].filter_subprocess_env is on
192 // (the host terminal spawns with its own unfiltered environment, which
193 // would leak the credentials the user asked to strip), and never for
194 // background jobs. ok=false falls back to local execution unchanged.
195 if b.terminal != nil && sh.Kind != sandbox.ShellPowerShell && !p.RunInBackground && !b.sb.Enforce() && !secrets.FilterSubprocessEnv() {
196 envMap := sandbox.SessionTempEnvMap(prepared.SessionTemp, prepared.LinuxSandboxed)
197 if out, ok, termErr := b.terminal.RunCommand(ctx, p.Command, b.workDir, b.timeout, envMap); ok {
198 out = appendSessionDataHint(out, b.guard.CommandHint(b.workDir, p.Command))
199 applyTerminalResult(ex, termErr)
200 ex.DurationMs = time.Since(start).Milliseconds()
201 return tool.DetailedResult{Output: out, Execution: ex}, termErr
202 }
203 }
204
205 argv, wrapped := prepared.Argv, prepared.Wrapped
206 cmdEnv := applyEnvOverrides(bashCommandEnv(ctx), prepared.EnvOverrides)
207 if res, err, used := b.tryPersistent(ctx, p, sh, prepared, persistEnv(cmdEnv), start, ex); used {
208 return res, err
209 }
210 if err := checkCommandLine(argv); err != nil {
211 return bashPreflightFailure(ex, start, err)
212 }
213
214 if p.RunInBackground {
215 return b.startBackground(ctx, p, sh, argv, wrapped, cmdEnv, lease, &releaseLease, start, ex)
216 }
217
218 out, runEx, err := b.runForegroundDetailed(ctx, p, sh, argv, wrapped, cmdEnv)
219 mergeRunInto(ex, runEx)
220 ex.DurationMs = time.Since(start).Milliseconds()
221 out = b.appendWriteHints(ctx, out, err, p, wrapped)
222 return tool.DetailedResult{
223 Output: out,
224 Execution: ex,
225 }, err
226 }
227
228 func applyTerminalResult(ex *tool.ShellExecution, err error) {
229 if ex == nil {
230 return
231 }
232 if err == nil {
233 ex.State = tool.ShellStateCompleted
234 ex.ExitCode = tool.IntPtr(0)
235 ex.MutationRisk = tool.ShellMutationMayHaveCompleted
236 return
237 }
238 if errors.Is(err, context.Canceled) {
239 ex.State = tool.ShellStateCancelled
240 ex.FailurePhase = tool.ShellPhaseCancellation
241 ex.MutationRisk = tool.ShellMutationMayBePartial
242 return
243 }
244 var timeoutErr TerminalTimeoutError
245 if errors.As(err, &timeoutErr) || errors.Is(err, context.DeadlineExceeded) {
246 ex.State = tool.ShellStateTimedOut
247 ex.FailurePhase = tool.ShellPhaseTimeout
248 ex.MutationRisk = tool.ShellMutationMayBePartial
249 return
250 }
251 var exitErr TerminalExitError
252 if errors.As(err, &exitErr) {
253 code := exitErr.Code
254 ex.ExitCode = &code
255 ex.State = tool.ShellStateFailed
256 ex.FailurePhase = tool.ShellPhaseExecution
257 ex.MutationRisk = tool.ShellMutationMayBePartial
258 return
259 }
260 // Legacy plain errors from older host runners.
261 ex.State = tool.ShellStateFailed
262 ex.FailurePhase = tool.ShellPhaseExecution
263 ex.MutationRisk = tool.ShellMutationMayBePartial
264 }
265
266 func mergeRunInto(dst *tool.ShellExecution, src *tool.ShellExecution) {
267 if dst == nil || src == nil {
268 return
269 }
270 dst.State = src.State
271 dst.FailurePhase = src.FailurePhase
272 dst.ExitCode = src.ExitCode
273 dst.OutputTail = src.OutputTail
274 if src.MutationRisk != "" {
275 dst.MutationRisk = src.MutationRisk
276 }
277 }
278
279 // prepareLaunch acquires a session-temp lease (when a Manager is available),
280 // builds the sandboxed argv, and applies sandbox-escape approval. The caller
281 // owns the returned lease and must Release it after the process exits.
282 func (b bash) prepareLaunch(ctx context.Context, sh sandbox.Shell, command string, rawArgs json.RawMessage) (sandbox.Prepared, *sessiontemp.Lease, error) {
283 var lease *sessiontemp.Lease
284 sessionDir := ""
285 if m := b.sessionTempManager(ctx); m != nil {
286 l, err := m.Acquire()
287 if err != nil {
288 return sandbox.Prepared{}, nil, fmt.Errorf("session temporary directory: %w", err)
289 }
290 lease = l
291 sessionDir = l.Dir()
292 }
293
294 // bashSandboxCommand is injectable for tests; production points at
295 // sandbox.Command. Attach SessionTemp so Linux bwrap binds the private dir.
296 spec := b.specForCall(ctx)
297 effectiveSessionDir := sessionDir
298 spec.SessionTemp = effectiveSessionDir
299 argv, wrapped := bashSandboxCommand(spec, sh, command)
300 linuxSB := wrapped && effectiveSessionDir != "" && runtime.GOOS == "linux"
301 prepared := sandbox.Prepared{
302 Argv: argv,
303 Wrapped: wrapped,
304 SessionTemp: effectiveSessionDir,
305 EnvOverrides: sandbox.SessionTempEnv(effectiveSessionDir, linuxSB),
306 LinuxSandboxed: linuxSB,
307 }
308
309 if spec.Enforce() && !prepared.Wrapped {
310 if lease != nil {
311 lease.Release()
312 }
313 return sandbox.Prepared{}, nil, fmt.Errorf("%s", sandbox.UnavailableMessage())
314 }
315 if prepared.Wrapped {
316 if err := sandbox.CheckGitMetadata(spec); err != nil {
317 if lease != nil {
318 lease.Release()
319 }
320 return sandbox.Prepared{}, nil, err
321 }
322 }
323 return prepared, lease, nil
324 }
325
326 func (b bash) sessionTempManager(ctx context.Context) *sessiontemp.Manager {
327 if m := sessiontemp.FromContext(ctx); m != nil {
328 return m
329 }
330 return b.sessionTemp
331 }
332
333 func applyEnvOverrides(env, overrides []string) []string {
334 for _, kv := range overrides {
335 key, value, ok := strings.Cut(kv, "=")
336 if !ok || key == "" {
337 continue
338 }
339 env = setEnvValue(env, key, value)
340 }
341 return env
342 }
343
344 // appendSessionDataHint appends the session-data guard warning to command
345 // output; with no output the hint stands alone. An empty hint is a no-op.
346 func appendSessionDataHint(out, hint string) string {
347 if hint == "" {
348 return out
349 }
350 if strings.TrimSpace(out) == "" {
351 return hint
352 }
353 return out + "\n\n" + hint
354 }
355
356 func unconfinedShellArgv(sh sandbox.Shell, command string) []string {
357 argv, _ := sandbox.Command(sandbox.Spec{}, sh, command)
358 return argv
359 }
360
361 // runForegroundDetailed uses the shared shellrun collector so model bash and
362 // user !command share exit-code / phase / output-tail classification.
363 func (b bash) runForegroundDetailed(ctx context.Context, p bashParams, sh sandbox.Shell, argv []string, wrapped bool, cmdEnv []string) (string, *tool.ShellExecution, error) {
364 ex := shellrun.DescriptorFromShell(sh)
365 var progress func(string)
366 if emit, ok := tool.ProgressFrom(ctx); ok {
367 progress = emit
368 }
369 track := shouldTrackShellProcess(wrapped, sh, p.Command, p.PreserveBackgroundProcesses)
370 res := shellrun.RunForeground(ctx, shellrun.Request{
371 Argv: argv,
372 Dir: b.workDir,
373 Env: cmdEnv,
374 Timeout: b.foregroundTimeoutFor(p),
375 WaitDelay: bashWaitDelay,
376 CommandPreview: commandPreview(p.Command),
377 ShellKind: sh.Kind.String(),
378 ShellPath: sh.Path,
379 Source: b.Name() + "_tool",
380 Track: track,
381 PreserveWaitDelay: p.PreserveBackgroundProcesses,
382 Progress: progress,
383 })
384 // A foreground command that spawned a lingering child (e.g. `bazel run`'s
385 // server) leaves it in the process group; Wait only reaped the shell leader.
386 // Kill the group so those don't accumulate into an OOM (#3702). On cancel/
387 // timeout the command's Cancel path already did this; this covers normal exit.
388 // shellrun owns the tool-local timeout context, so treat timed_out/cancelled
389 // as ctx.Err()!=nil for the reap decision.
390 reapCtx := ctx
391 if res.State == tool.ShellStateTimedOut || res.State == tool.ShellStateCancelled || ctx.Err() != nil {
392 // Force reap on forced stops even when preserve_background_processes is set.
393 reapShellProcess(res.Cmd, res.Tracked)
394 } else if shouldReapAfterRun(reapCtx, sh, p.Command, p.PreserveBackgroundProcesses) {
395 reapShellProcess(res.Cmd, res.Tracked)
396 }
397
398 ex.State = res.State
399 ex.FailurePhase = res.FailurePhase
400 ex.ExitCode = res.ExitCode
401 ex.OutputTail = res.OutputTail
402 switch res.State {
403 case tool.ShellStateCompleted:
404 ex.MutationRisk = tool.ShellMutationMayHaveCompleted
405 case tool.ShellStateNotRun:
406 ex.MutationRisk = tool.ShellMutationNotStarted
407 case tool.ShellStateFailed:
408 if res.FailurePhase == tool.ShellPhaseLaunch || res.FailurePhase == tool.ShellPhasePreflight {
409 ex.MutationRisk = tool.ShellMutationNotStarted
410 } else {
411 ex.MutationRisk = tool.ShellMutationMayBePartial
412 }
413 case tool.ShellStateTimedOut, tool.ShellStateCancelled:
414 ex.MutationRisk = tool.ShellMutationMayBePartial
415 default:
416 ex.MutationRisk = tool.ShellMutationUnknown
417 }
418 return res.Combined, ex, res.Err
419 }
420
421 func normalizeBashRunError(ctx context.Context, err error, preserveBackgroundProcesses bool) error {
422 if preserveBackgroundProcesses && ctx.Err() == nil && errors.Is(err, exec.ErrWaitDelay) {
423 return nil
424 }
425 return err
426 }
427
428 func shouldReapAfterRun(ctx context.Context, sh sandbox.Shell, command string, preserveBackgroundProcesses bool) bool {
429 if ctx.Err() != nil {
430 return true
431 }
432 if preserveBackgroundProcesses {
433 return false
434 }
435 return !sh.Kind.IsPOSIX() || !hasExplicitBackgroundKeepalive(command)
436 }
437
438 // hasExplicitBackgroundKeepalive detects common shell-level daemonization intent
439 // without letting a plain "cmd &" bypass #3702's stray process cleanup.
440 func hasExplicitBackgroundKeepalive(command string) bool {
441 file, err := shellparse.ParseBash(command)
442 if err != nil {
443 return false
444 }
445
446 hasBackground := false
447 hasKeepaliveCommand := false
448 syntax.Walk(file, func(node syntax.Node) bool {
449 switch n := node.(type) {
450 case *syntax.Stmt:
451 if n.Background {
452 hasBackground = true
453 }
454 case *syntax.CallExpr:
455 name, ok := staticShellCallName(n)
456 if !ok {
457 break
458 }
459 switch name {
460 case "disown", "nohup", "setsid":
461 hasKeepaliveCommand = true
462 }
463 }
464 return !(hasBackground && hasKeepaliveCommand)
465 })
466 return hasBackground && hasKeepaliveCommand
467 }
468
469 func (b bash) foregroundTimeout() time.Duration {
470 if b.timeout <= 0 {
471 return 0
472 }
473 return b.timeout
474 }
475
476 func (b bash) foregroundTimeoutFor(p bashParams) time.Duration {
477 configured := b.foregroundTimeout()
478 if p.TimeoutMS <= 0 {
479 return configured
480 }
481 return cappedMilliseconds(p.TimeoutMS, configured)
482 }
483
484 // Clamp in milliseconds before multiplication so integer overflow can never
485 // turn a positive timeout into an unlimited (negative) duration.
486 func cappedMilliseconds(ms int, cap time.Duration) time.Duration {
487 const maxDuration = time.Duration(1<<63 - 1)
488 if cap <= 0 {
489 cap = maxDuration
490 }
491 if int64(ms) > int64(cap/time.Millisecond) {
492 return cap
493 }
494 return time.Duration(ms) * time.Millisecond
495 }
496
497 func shouldTrackShellProcess(wrapped bool, sh sandbox.Shell, command string, preserveBackgroundProcesses bool) bool {
498 if preserveBackgroundProcesses {
499 return false
500 }
501 return !sh.Kind.IsPOSIX() || !hasExplicitBackgroundKeepalive(command)
502 }
503
504 func runShellProcess(ctx context.Context, cmd *exec.Cmd, sh sandbox.Shell, command string, track bool) (*proc.TrackedCommand, error) {
505 source := "bash_tool"
506 if sh.Kind == sandbox.ShellPowerShell {
507 source = "pwsh_tool"
508 }
509 tracked, err := proc.RunCommand(ctx, cmd, proc.RunOptions{
510 Track: track,
511 CancelWaitGrace: bashWaitDelay + time.Second,
512 Source: source,
513 ShellKind: sh.Kind.String(),
514 ShellPath: sh.Path,
515 CommandPreview: commandPreview(command),
516 })
517 return tracked, err
518 }
519
520 func reapShellProcess(cmd *exec.Cmd, tracked *proc.TrackedCommand) {
521 if tracked != nil {
522 tracked.Kill()
523 return
524 }
525 proc.KillTree(cmd)
526 }
527
528 // hasUnquotedSeq reports whether seq appears in s outside any single- or
529 // double-quoted span, so a literal "a && b" string argument doesn't trip the
530 // PowerShell chaining guard.
531 func hasUnquotedSeq(s, seq string) bool {
532 var quote byte
533 for i := range len(s) {
534 c := s[i]
535 if quote != 0 {
536 if c == quote {
537 quote = 0
538 }
539 continue
540 }
541 if c == '\'' || c == '"' {
542 quote = c
543 continue
544 }
545 if strings.HasPrefix(s[i:], seq) {
546 return true
547 }
548 }
549 return false
550 }
551
552 func staticShellCallName(call *syntax.CallExpr) (string, bool) {
553 for _, arg := range call.Args {
554 word, ok := shellparse.StaticWord(arg)
555 if !ok {
556 return "", false
557 }
558 if shellparse.IsAssignment(word) {
559 continue
560 }
561 base := shellparse.WordBase(word)
562 if base == "command" || base == "env" {
563 continue
564 }
565 return base, true
566 }
567 return "", false
568 }
569
570 // commandPreview is a short single-line label for a background bash job, surfaced
571 // in the status bar and completion notices.
572 func commandPreview(cmd string) string {
573 cmd = strings.TrimSpace(strings.ReplaceAll(cmd, "\n", " "))
574 const max = 48
575 r := []rune(cmd)
576 if len(r) > max {
577 return string(r[:max]) + "…"
578 }
579 return cmd
580 }
581
582 func bashCommandEnv(ctx context.Context) []string {
583 env := secrets.ProcessEnv()
584 if runtime.GOOS == "windows" {
585 return env
586 }
587 currentPath, _ := envValue(env, "PATH")
588 if shellPath := strings.TrimSpace(shellrun.LoginShellPATH(ctx, env, loginShell())); shellPath != "" {
589 if merged := mergePathLists(shellPath, currentPath); merged != currentPath {
590 env = setEnvValue(env, "PATH", merged)
591 }
592 }
593 return env
594 }
595
596 func loginShell() string {
597 if shell := strings.TrimSpace(os.Getenv("SHELL")); shell != "" {
598 if hasPathSeparator(shell) {
599 if isExecutableFile(shell) {
600 return shell
601 }
602 } else if p, err := exec.LookPath(shell); err == nil {
603 return p
604 }
605 }
606 for _, shell := range []string{"/bin/zsh", "/bin/bash", "/bin/sh"} {
607 if isExecutableFile(shell) {
608 return shell
609 }
610 }
611 return ""
612 }
613
614 func hasPathSeparator(s string) bool {
615 return strings.ContainsAny(s, `/\`)
616 }
617
618 func isExecutableFile(path string) bool {
619 info, err := os.Stat(path)
620 if err != nil || info.IsDir() {
621 return false
622 }
623 return info.Mode().Perm()&0o111 != 0
624 }
625
626 func setEnvValue(env []string, key, value string) []string {
627 out := make([]string, 0, len(env)+1)
628 replaced := false
629 for _, kv := range env {
630 k, _, ok := strings.Cut(kv, "=")
631 if ok && envKeyEqual(k, key) {
632 if !replaced {
633 out = append(out, key+"="+value)
634 replaced = true
635 }
636 continue
637 }
638 out = append(out, kv)
639 }
640 if !replaced {
641 out = append(out, key+"="+value)
642 }
643 return out
644 }
645
646 func envValue(env []string, key string) (string, bool) {
647 for _, entry := range slices.Backward(env) {
648 k, v, ok := strings.Cut(entry, "=")
649 if ok && envKeyEqual(k, key) {
650 return v, true
651 }
652 }
653 return "", false
654 }
655
656 func envKeyEqual(a, b string) bool {
657 if runtime.GOOS == "windows" {
658 return strings.EqualFold(a, b)
659 }
660 return a == b
661 }
662
663 func mergePathLists(primary, secondary string) string {
664 var out []string
665 seen := map[string]bool{}
666 add := func(path string) {
667 for _, part := range filepath.SplitList(path) {
668 part = strings.TrimSpace(part)
669 if part == "" || seen[part] {
670 continue
671 }
672 seen[part] = true
673 out = append(out, part)
674 }
675 }
676 add(primary)
677 add(secondary)
678 return strings.Join(out, string(os.PathListSeparator))
679 }
680
680 lines GO