Skip to main content

command_stream/
lib.rs

1//! # command-stream
2//!
3//! Modern shell command execution library with streaming, async iteration, and event support.
4//!
5//! This library provides a Rust equivalent to the JavaScript command-stream library,
6//! offering powerful shell command execution with streaming capabilities.
7//!
8//! ## Features
9//!
10//! - Async command execution with tokio
11//! - Streaming output via async iterators
12//! - Event-based output handling (on, once, emit)
13//! - Virtual commands for common operations (cat, ls, mkdir, etc.)
14//! - Shell operator support (&&, ||, ;, |)
15//! - Pipeline support with `.pipe()` method and `Pipeline` builder
16//! - Global state management for shell settings
17//! - `cmd!` macro for ergonomic command creation (similar to JS `$` tagged template literals)
18//! - Cross-platform support
19//!
20//! ## Module Organization
21//!
22//! The codebase follows a modular architecture similar to the JavaScript implementation:
23//!
24//! - `ansi` - ANSI escape code handling utilities
25//! - `commands` - Virtual command implementations
26//! - `events` - Event emitter for stream events
27//! - `macros` - The `cmd!` macro for ergonomic command creation
28//! - `pipeline` - Pipeline execution support
29//! - `quote` - Shell quoting utilities
30//! - `shell_parser` - Shell command parsing
31//! - `state` - Global state management
32//! - `stream` - Async streaming and iteration support
33//! - `trace` - Logging and tracing utilities
34//! - `utils` - Command results and virtual command helpers
35//!
36//! ## Quick Start
37//!
38//! ```rust,no_run
39//! use command_stream::{run, cmd};
40//!
41//! #[tokio::main]
42//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
43//!     // Execute a simple command
44//!     let result = run("echo hello world").await?;
45//!     println!("{}", result.stdout);
46//!
47//!     // Using the cmd! macro (similar to JS $ tagged template)
48//!     let name = "world";
49//!     let result = cmd!("echo hello {}", name).await?;
50//!     println!("{}", result.stdout);
51//!
52//!     // Using pipelines
53//!     use command_stream::Pipeline;
54//!     let result = Pipeline::new()
55//!         .add("echo hello world")
56//!         .add("grep world")
57//!         .run()
58//!         .await?;
59//!
60//!     Ok(())
61//! }
62//! ```
63
64// Modular utility modules (following JavaScript modular pattern)
65pub mod ansi;
66pub mod events;
67#[doc(hidden)]
68pub mod macros;
69pub mod pipeline;
70pub mod quote;
71pub mod signal;
72pub mod state;
73pub mod stream;
74pub mod terminal;
75pub mod trace;
76
77// Core modules
78pub mod commands;
79pub mod shell_parser;
80pub mod utils;
81
82use std::collections::HashMap;
83use std::path::PathBuf;
84use std::process::Stdio;
85use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
86use tokio::process::{Child, Command};
87use tokio::sync::mpsc;
88
89pub use commands::{CommandContext, StreamChunk};
90pub use shell_parser::{needs_real_shell, parse_shell_command, ParsedCommand};
91pub use utils::{CommandResult, VirtualUtils};
92
93// Re-export modular utilities at crate root for convenient access
94pub use ansi::{AnsiConfig, AnsiUtils};
95pub use events::{EventData, EventType, StreamEmitter};
96pub use pipeline::{Pipeline, PipelineBuilder, PipelineExt};
97pub use quote::{
98    escape_for_double_quotes, escape_for_single_quotes, has_shell_escapes,
99    is_pre_quoted_passthrough_enabled, is_quote_context_enabled, quote, quote_for_context,
100    scan_quote_context, QuoteContext,
101};
102pub use signal::{signal_exit_code, signal_number, DEFAULT_KILL_GRACE_MS, DEFAULT_KILL_SIGNAL};
103pub use state::{
104    get_shell_settings, global_state, reset_global_state, set_shell_option, unset_shell_option,
105    GlobalState, ShellSettings,
106};
107pub use stream::{AsyncIterator, IntoStream, OutputChunk, OutputStream, StreamingRunner};
108pub use trace::trace;
109
110#[derive(Clone, Copy)]
111enum ChildOutput {
112    Stdout,
113    Stderr,
114}
115
116/// Read child output as byte chunks so capture does not invent a trailing newline.
117///
118/// stdout and stderr use separate futures in `ProcessRunner::run`, preventing
119/// either pipe from filling while the other is being drained. Mirroring keeps
120/// the original bytes too, including output that does not end in a newline.
121async fn collect_child_output<R>(
122    reader: Option<R>,
123    mirror: bool,
124    target: ChildOutput,
125) -> std::io::Result<Vec<u8>>
126where
127    R: AsyncRead + Unpin,
128{
129    let Some(mut reader) = reader else {
130        return Ok(Vec::new());
131    };
132    let mut collected = Vec::new();
133    let mut buffer = [0_u8; 8192];
134
135    loop {
136        let count = reader.read(&mut buffer).await?;
137        if count == 0 {
138            break;
139        }
140
141        let chunk = &buffer[..count];
142        collected.extend_from_slice(chunk);
143        if mirror {
144            match target {
145                ChildOutput::Stdout => {
146                    let mut output = std::io::stdout().lock();
147                    let _ = std::io::Write::write_all(&mut output, chunk);
148                    let _ = std::io::Write::flush(&mut output);
149                }
150                ChildOutput::Stderr => {
151                    let mut output = std::io::stderr().lock();
152                    let _ = std::io::Write::write_all(&mut output, chunk);
153                    let _ = std::io::Write::flush(&mut output);
154                }
155            }
156        }
157    }
158
159    Ok(collected)
160}
161
162fn fallback_cwd() -> PathBuf {
163    std::env::var_os("HOME")
164        .or_else(|| std::env::var_os("USERPROFILE"))
165        .map(PathBuf::from)
166        .filter(|path| path.is_dir())
167        .unwrap_or_else(std::env::temp_dir)
168}
169
170/// Resolve a working directory that is safe to spawn a child process in.
171///
172/// When no explicit cwd is requested the child normally inherits the parent's
173/// working directory. But if that directory has been deleted or become
174/// inaccessible (the "getcwd() failed" scenario from issue #44), inheriting it
175/// makes the OS-level spawn fail. In that case fall back to a directory that is
176/// known to exist so the command still runs.
177///
178/// Normal behavior is preserved: when an explicit cwd is given, or when the
179/// inherited working directory is valid, this returns the requested value
180/// (`None` meaning "inherit").
181fn resolve_spawn_cwd(cwd: Option<&PathBuf>) -> Option<PathBuf> {
182    // An explicit directory is always honored as-is.
183    if let Some(c) = cwd {
184        return Some(c.clone());
185    }
186
187    // No explicit cwd: we would inherit the parent's working directory. Make
188    // sure that directory is actually usable before relying on inheritance.
189    match std::env::current_dir() {
190        Ok(_) => None,
191        Err(e) => {
192            let fallback = fallback_cwd();
193            trace(
194                "ProcessRunner",
195                &format!(
196                    "current_dir() failed ({}); spawning in fallback directory {}",
197                    e,
198                    fallback.display()
199                ),
200            );
201            Some(fallback)
202        }
203    }
204}
205
206/// Error type for command-stream operations
207#[derive(Debug, thiserror::Error)]
208pub enum Error {
209    #[error("IO error: {0}")]
210    Io(#[from] std::io::Error),
211
212    #[error("Command failed with exit code {code}: {message}")]
213    CommandFailed { code: i32, message: String },
214
215    #[error("Command not found: {0}")]
216    CommandNotFound(String),
217
218    #[error("Parse error: {0}")]
219    ParseError(String),
220
221    #[error("Cancelled")]
222    Cancelled,
223}
224
225impl Error {
226    /// Build a [`Error::CommandFailed`] for a command that exited with `code`.
227    pub fn command_failed(code: i32, message: impl Into<String>) -> Self {
228        Error::CommandFailed {
229            code,
230            message: message.into(),
231        }
232    }
233
234    /// Exit status carried by the error, when the failure has one.
235    ///
236    /// Mirrors the `error.code` property of the JavaScript implementation
237    /// (issue #38). Failures that never reached a child process, such as parse
238    /// errors, report `None`.
239    pub fn code(&self) -> Option<i32> {
240        match self {
241            Error::CommandFailed { code, .. } => Some(*code),
242            // `command not found` is 127 in POSIX shells, which is also what
243            // the JavaScript implementation reports for a missing executable.
244            Error::CommandNotFound(_) => Some(127),
245            Error::Io(error) => match error.kind() {
246                std::io::ErrorKind::NotFound => Some(127),
247                std::io::ErrorKind::PermissionDenied => Some(126),
248                _ => None,
249            },
250            // A cancelled command is terminated with SIGINT (128 + 2).
251            Error::Cancelled => Some(130),
252            Error::ParseError(_) => None,
253        }
254    }
255
256    /// Alias for [`code`](Self::code).
257    ///
258    /// Node.js `child_process` names this property `code`, while execa, zx,
259    /// nano-spawn, and Bun Shell name it `exitCode`. command-stream exposes
260    /// both spellings in every language (issue #38).
261    pub fn exit_code(&self) -> Option<i32> {
262        self.code()
263    }
264}
265
266/// Result type for command-stream operations
267pub type Result<T> = std::result::Result<T, Error>;
268
269/// Options for command execution
270#[derive(Debug, Clone)]
271pub struct RunOptions {
272    /// Mirror output to parent stdout/stderr
273    pub mirror: bool,
274    /// Capture output in result
275    pub capture: bool,
276    /// Standard input handling
277    pub stdin: StdinOption,
278    /// Working directory
279    pub cwd: Option<PathBuf>,
280    /// Environment variables
281    pub env: Option<HashMap<String, String>>,
282    /// Interactive mode (TTY forwarding)
283    pub interactive: bool,
284    /// Enable shell operator parsing
285    pub shell_operators: bool,
286    /// Enable tracing for this command
287    pub trace: bool,
288    /// Signal used to stop the process when it is killed without an explicit
289    /// signal, i.e. [`ProcessRunner::kill`] (default `SIGTERM`).
290    ///
291    /// Mirrors the JavaScript `killSignal` option. An explicit
292    /// [`ProcessRunner::kill_with`] argument always overrides it.
293    pub kill_signal: String,
294    /// Milliseconds the child is given to handle the kill signal before
295    /// `SIGKILL` is sent (default 100).
296    ///
297    /// Mirrors the JavaScript `killGrace` option. This is the window in which a
298    /// child running its own signal handler can shut down on its own terms.
299    pub kill_grace_ms: u64,
300}
301
302impl Default for RunOptions {
303    fn default() -> Self {
304        RunOptions {
305            mirror: true,
306            capture: true,
307            stdin: StdinOption::Inherit,
308            cwd: None,
309            env: None,
310            interactive: false,
311            shell_operators: true,
312            trace: true,
313            kill_signal: signal::DEFAULT_KILL_SIGNAL.to_string(),
314            kill_grace_ms: signal::DEFAULT_KILL_GRACE_MS,
315        }
316    }
317}
318
319/// Standard input options
320#[derive(Debug, Clone)]
321pub enum StdinOption {
322    /// Inherit from parent process
323    Inherit,
324    /// Pipe (allow writing to stdin)
325    Pipe,
326    /// Provide string content
327    Content(String),
328    /// Null device
329    Null,
330}
331
332/// A running or completed process
333pub struct ProcessRunner {
334    command: String,
335    options: RunOptions,
336    child: Option<Child>,
337    result: Option<CommandResult>,
338    started: bool,
339    finished: bool,
340    cancelled: bool,
341    /// Whether the child was spawned into a process group of its own, and so
342    /// can be signalled as a group. Recorded at spawn time because it cannot be
343    /// discovered later: by the time the group is signalled the leader is
344    /// usually a zombie, which macOS refuses to answer `getpgid` for.
345    #[cfg(unix)]
346    own_process_group: bool,
347    output_tx: Option<mpsc::Sender<StreamChunk>>,
348    // Held, never read: dropping the receiver would close the channel, and
349    // streaming virtual commands treat a closed channel as "stop now" (see
350    // `commands::yes`, which loops until `output_tx.send` fails). Keeping it
351    // alive is what gives those commands their run-until-cancelled behaviour.
352    #[allow(dead_code)]
353    output_rx: Option<mpsc::Receiver<StreamChunk>>,
354}
355
356impl ProcessRunner {
357    /// Create a new process runner
358    pub fn new(command: impl Into<String>, options: RunOptions) -> Self {
359        let (tx, rx) = mpsc::channel(1024);
360        ProcessRunner {
361            command: command.into(),
362            options,
363            child: None,
364            result: None,
365            started: false,
366            finished: false,
367            cancelled: false,
368            #[cfg(unix)]
369            own_process_group: false,
370            output_tx: Some(tx),
371            output_rx: Some(rx),
372        }
373    }
374
375    /// Whether the child will read from the caller's terminal.
376    ///
377    /// Only an *inherited* stdin that is actually a tty counts: a pipe, a null
378    /// stdin, or inherited stdin that has been redirected to a file carries no
379    /// terminal, and neither does output-only inheritance. This is the one case
380    /// where the child must stay in the caller's process group.
381    #[cfg(unix)]
382    fn shares_the_terminal(&self) -> bool {
383        use std::io::IsTerminal;
384
385        self.options.interactive
386            || (matches!(self.options.stdin, StdinOption::Inherit)
387                && std::io::stdin().is_terminal())
388    }
389
390    /// Start the process
391    pub async fn start(&mut self) -> Result<()> {
392        if self.started {
393            return Ok(());
394        }
395        self.started = true;
396
397        utils::trace_lazy("ProcessRunner", || {
398            format!("Starting command: {}", self.command)
399        });
400
401        // Check if this is a virtual command. Backslash escapes are removed by a
402        // real shell but not by the whitespace splitting used for virtual
403        // command args, so such commands always go to the system shell (#49).
404        // The same applies to redirection and expansions: whitespace splitting
405        // would hand `>`, `out.txt` to the virtual command as two ordinary
406        // arguments, so `echo hello > out.txt` printed the redirection instead
407        // of writing the file, and `git push ... 2>&1` reported success while
408        // nothing was pushed (#46).
409        let first_word = if has_shell_escapes(&self.command) || needs_real_shell(&self.command) {
410            ""
411        } else {
412            self.command.split_whitespace().next().unwrap_or("")
413        };
414        if let Some(result) = self.try_virtual_command(first_word).await {
415            self.result = Some(result);
416            self.finished = true;
417            return Ok(());
418        }
419        // Parse command for shell operators (for future use with virtual command pipelines)
420        let _parsed = if self.options.shell_operators && !needs_real_shell(&self.command) {
421            parse_shell_command(&self.command)
422        } else {
423            None
424        };
425
426        // Execute via real shell if needed
427        let shell = find_available_shell();
428
429        let mut cmd = Command::new(&shell.cmd);
430        for arg in &shell.args {
431            cmd.arg(arg);
432        }
433        utils::append_shell_command(&mut cmd, &self.command, self.options.env.as_ref());
434
435        // Configure stdin
436        match &self.options.stdin {
437            StdinOption::Inherit => {
438                cmd.stdin(Stdio::inherit());
439            }
440            StdinOption::Pipe => {
441                cmd.stdin(Stdio::piped());
442            }
443            StdinOption::Content(_) => {
444                cmd.stdin(Stdio::piped());
445            }
446            StdinOption::Null => {
447                cmd.stdin(Stdio::null());
448            }
449        }
450
451        // Configure stdout/stderr
452        if self.options.capture || self.options.mirror {
453            cmd.stdout(Stdio::piped());
454            cmd.stderr(Stdio::piped());
455        } else {
456            cmd.stdout(Stdio::inherit());
457            cmd.stderr(Stdio::inherit());
458        }
459
460        // Set working directory. Fall back to a valid directory when the
461        // inherited working directory has been deleted (issue #44).
462        if let Some(cwd) = resolve_spawn_cwd(self.options.cwd.as_ref()) {
463            cmd.current_dir(cwd);
464        }
465
466        // Set environment
467        if let Some(ref env_vars) = self.options.env {
468            for (key, value) in env_vars {
469                cmd.env(key, value);
470            }
471        }
472
473        // Run the child in its own process group so that killing it can signal
474        // the whole group (parent + grandchildren), matching `StreamingRunner`
475        // and the JavaScript implementation's `detached` spawn.
476        //
477        // A child that shares the terminal is deliberately left in the caller's
478        // group. The tty delivers CTRL+C to its foreground group only, so
479        // moving such a child out would both hide CTRL+C from it and stop it
480        // with SIGTTIN the moment it read from the terminal. JavaScript draws
481        // the same line, spawning interactive commands without `detached`.
482        #[cfg(unix)]
483        {
484            self.own_process_group = !self.shares_the_terminal();
485            if self.own_process_group {
486                cmd.process_group(0);
487            }
488        }
489
490        // Spawn the process
491        let child = cmd.spawn()?;
492        self.child = Some(child);
493
494        Ok(())
495    }
496
497    /// Run the process to completion
498    pub async fn run(&mut self) -> Result<CommandResult> {
499        self.start().await?;
500
501        if let Some(result) = &self.result {
502            return Ok(result.clone());
503        }
504
505        let mut child = self
506            .child
507            .take()
508            .ok_or_else(|| Error::Io(std::io::Error::other("Process not started")))?;
509
510        // Handle stdin content if provided
511        if let StdinOption::Content(ref content) = self.options.stdin {
512            if let Some(mut stdin) = child.stdin.take() {
513                let content = content.clone();
514                tokio::spawn(async move {
515                    let _ = stdin.write_all(content.as_bytes()).await;
516                    let _ = stdin.shutdown().await;
517                });
518            }
519        }
520
521        // Drain both pipes concurrently and preserve their newline framing. The
522        // previous line reader appended `\n` to every final line, changing
523        // output from commands such as `printf` that omit a newline (issue #37).
524        let stdout = child.stdout.take();
525        let stderr = child.stderr.take();
526        let collected = tokio::try_join!(
527            collect_child_output(stdout, self.options.mirror, ChildOutput::Stdout),
528            collect_child_output(stderr, self.options.mirror, ChildOutput::Stderr),
529        );
530        let (stdout, stderr) = match collected {
531            Ok(output) => output,
532            Err(error) => {
533                // `try_join!` drops the other pipe reader after an error. Stop
534                // and reap the child so it cannot remain blocked on that pipe.
535                let _ = child.start_kill();
536                let _ = child.wait().await;
537                return Err(error.into());
538            }
539        };
540
541        let status = child.wait().await?;
542        let code = status.code().unwrap_or(-1);
543
544        let result = CommandResult {
545            stdout: String::from_utf8_lossy(&stdout).into_owned(),
546            stderr: String::from_utf8_lossy(&stderr).into_owned(),
547            code,
548        };
549
550        self.result = Some(result.clone());
551        self.finished = true;
552
553        Ok(result)
554    }
555
556    /// Try to execute as a virtual command
557    async fn try_virtual_command(&self, cmd_name: &str) -> Option<CommandResult> {
558        if !commands::are_virtual_commands_enabled() {
559            return None;
560        }
561
562        // An empty command name means the caller already decided this command
563        // must go to a real shell (redirection, expansions, escapes). Bail out
564        // before tokenizing so we neither waste work nor parse shell syntax we
565        // deliberately delegate.
566        if cmd_name.is_empty() {
567            return None;
568        }
569
570        // Parse args from command string, respecting quotes and performing
571        // POSIX quote removal so `echo label:'help wanted'` reaches the built-in
572        // as the single argument `label:help wanted` (issue #48).
573        let words = shell_parser::split_command_words(&self.command);
574        let args: Vec<String> = words.into_iter().skip(1).collect();
575
576        let ctx = CommandContext {
577            args,
578            stdin: match &self.options.stdin {
579                StdinOption::Content(s) => Some(s.clone()),
580                _ => None,
581            },
582            cwd: self.options.cwd.clone(),
583            env: self.options.env.clone(),
584            output_tx: self.output_tx.clone(),
585            is_cancelled: None,
586        };
587
588        match cmd_name {
589            "echo" => Some(commands::echo(ctx).await),
590            "pwd" => Some(commands::pwd(ctx).await),
591            "cd" => Some(commands::cd::resolve_cd(ctx).await.0),
592            "true" => Some(commands::r#true(ctx).await),
593            "false" => Some(commands::r#false(ctx).await),
594            "sleep" => Some(commands::sleep(ctx).await),
595            "cat" => Some(commands::cat(ctx).await),
596            "ls" => Some(commands::ls(ctx).await),
597            "mkdir" => Some(commands::mkdir(ctx).await),
598            "rm" => Some(commands::rm(ctx).await),
599            "touch" => Some(commands::touch(ctx).await),
600            "cp" => Some(commands::cp(ctx).await),
601            "mv" => Some(commands::mv(ctx).await),
602            "basename" => Some(commands::basename(ctx).await),
603            "dirname" => Some(commands::dirname(ctx).await),
604            "env" => Some(commands::env(ctx).await),
605            "exit" => Some(commands::exit(ctx).await),
606            "which" => Some(commands::which(ctx).await),
607            "yes" => Some(commands::yes(ctx).await),
608            "seq" => Some(commands::seq(ctx).await),
609            "tee" => Some(commands::tee(ctx).await),
610            "test" => Some(commands::test(ctx).await),
611            _ => None,
612        }
613    }
614
615    /// Stop the process using the configured kill signal
616    /// ([`RunOptions::kill_signal`], default `SIGTERM`).
617    ///
618    /// Mirrors the JavaScript `kill()` with no argument.
619    pub fn kill(&mut self) -> Result<()> {
620        let signal = self.options.kill_signal.clone();
621        self.kill_with(&signal)
622    }
623
624    /// Stop the process using an explicit signal, overriding
625    /// [`RunOptions::kill_signal`] for this call.
626    ///
627    /// Mirrors the JavaScript `kill(signal)`. The signal is delivered to the
628    /// child and its process group, so grandchildren behind a `sh -c` wrapper
629    /// are stopped too - except for a child sharing the caller's terminal,
630    /// which stays in the caller's group so CTRL+C keeps reaching it. The child
631    /// then has [`RunOptions::kill_grace_ms`] to run its own handler before
632    /// `SIGKILL` follows, so a process that ignores the signal still
633    /// terminates.
634    ///
635    /// ```no_run
636    /// use command_stream::{ProcessRunner, RunOptions};
637    ///
638    /// # #[tokio::main]
639    /// # async fn main() -> command_stream::Result<()> {
640    /// let mut runner = ProcessRunner::new("sleep 30", RunOptions::default());
641    /// runner.start().await?;
642    /// runner.kill_with("SIGINT")?; // the CTRL+C signal
643    /// # Ok(())
644    /// # }
645    /// ```
646    pub fn kill_with(&mut self, signal: &str) -> Result<()> {
647        self.cancelled = true;
648        utils::trace_lazy("ProcessRunner", || format!("kill | signal={signal}"));
649
650        let Some(child) = self.child.as_mut() else {
651            return Ok(());
652        };
653
654        // Windows has no signals to deliver and no handler for the child to
655        // run, so there is nothing to grant a grace period to: the forceful
656        // stop is the only way to end the process.
657        // The `#[cfg(unix)]` block below is stripped on Windows, which leaves
658        // this one as the function's tail expression - hence no `return`.
659        #[cfg(not(unix))]
660        {
661            let _ = signal;
662            child.start_kill()?;
663            Ok(())
664        }
665
666        // Without a pid the process never spawned (or was already reaped);
667        // fall back to the forceful stop so `kill()` still terminates it.
668        #[cfg(unix)]
669        {
670            let Some(pid) = child.id() else {
671                child.start_kill()?;
672                return Ok(());
673            };
674
675            // `SIGKILL` cannot be handled, so there is nothing to wait for.
676            //
677            // A zero grace period means the child is given no opportunity to
678            // handle the signal either, so the requested signal is not
679            // delivered at all. Anything done between it and `SIGKILL` - even a
680            // single syscall - is a window the child can be scheduled in, which
681            // made "no grace" a race the child occasionally won rather than a
682            // guarantee. The reported exit code still comes from the signal
683            // that was requested.
684            let grace = self.options.kill_grace_ms;
685            let delivery = if self.own_process_group {
686                signal::Delivery::ProcessAndGroup
687            } else {
688                signal::Delivery::ProcessOnly
689            };
690            if grace == 0 || signal == "SIGKILL" {
691                signal::send_signal_to_process(pid, "SIGKILL", delivery);
692                let _ = child.start_kill();
693                return Ok(());
694            }
695
696            signal::send_signal_to_process(pid, signal, delivery);
697
698            // Otherwise escalate in the background so the child keeps its grace
699            // period without blocking the caller, which may not be inside an
700            // await point.
701            tokio::spawn(async move {
702                tokio::time::sleep(std::time::Duration::from_millis(grace)).await;
703                // Best effort: if the child already exited on the first signal
704                // this delivery simply fails, and the pid has not been reused
705                // because the `Child` handle above has not reaped it yet. That
706                // unreaped leader is also what keeps the group id alive, so the
707                // group delivery still reaches a grandchild that outlived it.
708                signal::send_signal_to_process(pid, "SIGKILL", delivery);
709            });
710
711            Ok(())
712        }
713    }
714
715    /// Check if the process is finished
716    pub fn is_finished(&self) -> bool {
717        self.finished
718    }
719
720    /// Get the result if available
721    pub fn result(&self) -> Option<&CommandResult> {
722        self.result.as_ref()
723    }
724
725    /// Get the command string
726    pub fn command(&self) -> &str {
727        &self.command
728    }
729
730    /// Get the options
731    pub fn options(&self) -> &RunOptions {
732        &self.options
733    }
734}
735
736/// Shell configuration
737#[derive(Debug, Clone)]
738struct ShellConfig {
739    cmd: String,
740    args: Vec<String>,
741}
742
743/// Find an available shell
744fn find_available_shell() -> ShellConfig {
745    let is_windows = cfg!(windows);
746
747    if is_windows {
748        // Windows shells
749        let shells = [
750            ("cmd.exe", vec!["/c"]),
751            ("powershell.exe", vec!["-Command"]),
752        ];
753
754        for (cmd, args) in shells {
755            if which::which(cmd).is_ok() {
756                return ShellConfig {
757                    cmd: cmd.to_string(),
758                    args: args.into_iter().map(String::from).collect(),
759                };
760            }
761        }
762
763        ShellConfig {
764            cmd: "cmd.exe".to_string(),
765            args: vec!["/c".to_string()],
766        }
767    } else {
768        // Unix shells
769        let shells = [
770            ("/bin/sh", vec!["-c"]),
771            ("/usr/bin/sh", vec!["-c"]),
772            ("/bin/bash", vec!["-c"]),
773            ("sh", vec!["-c"]),
774        ];
775
776        for (cmd, args) in shells {
777            if std::path::Path::new(cmd).exists() || which::which(cmd).is_ok() {
778                return ShellConfig {
779                    cmd: cmd.to_string(),
780                    args: args.into_iter().map(String::from).collect(),
781                };
782            }
783        }
784
785        ShellConfig {
786            cmd: "/bin/sh".to_string(),
787            args: vec!["-c".to_string()],
788        }
789    }
790}
791
792/// Execute a command and return the result
793///
794/// This is the main entry point for simple command execution.
795/// Named `run` instead of `$` since `$` is not a valid Rust identifier.
796pub async fn run(command: impl Into<String>) -> Result<CommandResult> {
797    let mut runner = ProcessRunner::new(command, RunOptions::default());
798    runner.run().await
799}
800
801/// Alias for `run` function - for JavaScript-like API feel
802/// Since `$` is not valid in Rust, this provides a similar short name
803pub use run as execute;
804
805/// Execute a command with custom options
806pub async fn exec(command: impl Into<String>, options: RunOptions) -> Result<CommandResult> {
807    let mut runner = ProcessRunner::new(command, options);
808    runner.run().await
809}
810
811/// Create a new process runner without starting it
812pub fn create(command: impl Into<String>, options: RunOptions) -> ProcessRunner {
813    ProcessRunner::new(command, options)
814}
815
816/// Execute a command synchronously (blocking)
817pub fn run_sync(command: impl Into<String>) -> Result<CommandResult> {
818    let rt = tokio::runtime::Runtime::new()?;
819    rt.block_on(run(command))
820}
821
822// Tests are located in tests/ directory for better organization