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 state;
72pub mod stream;
73pub mod terminal;
74pub mod trace;
75
76// Core modules
77pub mod commands;
78pub mod shell_parser;
79pub mod utils;
80
81use std::collections::HashMap;
82use std::path::PathBuf;
83use std::process::Stdio;
84use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
85use tokio::process::{Child, Command};
86use tokio::sync::mpsc;
87
88pub use commands::{CommandContext, StreamChunk};
89pub use shell_parser::{needs_real_shell, parse_shell_command, ParsedCommand};
90pub use utils::{CommandResult, VirtualUtils};
91
92// Re-export modular utilities at crate root for convenient access
93pub use ansi::{AnsiConfig, AnsiUtils};
94pub use events::{EventData, EventType, StreamEmitter};
95pub use pipeline::{Pipeline, PipelineBuilder, PipelineExt};
96pub use quote::{
97    escape_for_double_quotes, escape_for_single_quotes, has_shell_escapes,
98    is_pre_quoted_passthrough_enabled, is_quote_context_enabled, quote, quote_for_context,
99    scan_quote_context, QuoteContext,
100};
101pub use state::{
102    get_shell_settings, global_state, reset_global_state, set_shell_option, unset_shell_option,
103    GlobalState, ShellSettings,
104};
105pub use stream::{AsyncIterator, IntoStream, OutputChunk, OutputStream, StreamingRunner};
106pub use trace::trace;
107
108#[derive(Clone, Copy)]
109enum ChildOutput {
110    Stdout,
111    Stderr,
112}
113
114/// Read child output as byte chunks so capture does not invent a trailing newline.
115///
116/// stdout and stderr use separate futures in `ProcessRunner::run`, preventing
117/// either pipe from filling while the other is being drained. Mirroring keeps
118/// the original bytes too, including output that does not end in a newline.
119async fn collect_child_output<R>(
120    reader: Option<R>,
121    mirror: bool,
122    target: ChildOutput,
123) -> std::io::Result<Vec<u8>>
124where
125    R: AsyncRead + Unpin,
126{
127    let Some(mut reader) = reader else {
128        return Ok(Vec::new());
129    };
130    let mut collected = Vec::new();
131    let mut buffer = [0_u8; 8192];
132
133    loop {
134        let count = reader.read(&mut buffer).await?;
135        if count == 0 {
136            break;
137        }
138
139        let chunk = &buffer[..count];
140        collected.extend_from_slice(chunk);
141        if mirror {
142            match target {
143                ChildOutput::Stdout => {
144                    let mut output = std::io::stdout().lock();
145                    let _ = std::io::Write::write_all(&mut output, chunk);
146                    let _ = std::io::Write::flush(&mut output);
147                }
148                ChildOutput::Stderr => {
149                    let mut output = std::io::stderr().lock();
150                    let _ = std::io::Write::write_all(&mut output, chunk);
151                    let _ = std::io::Write::flush(&mut output);
152                }
153            }
154        }
155    }
156
157    Ok(collected)
158}
159
160fn fallback_cwd() -> PathBuf {
161    std::env::var_os("HOME")
162        .or_else(|| std::env::var_os("USERPROFILE"))
163        .map(PathBuf::from)
164        .filter(|path| path.is_dir())
165        .unwrap_or_else(std::env::temp_dir)
166}
167
168/// Resolve a working directory that is safe to spawn a child process in.
169///
170/// When no explicit cwd is requested the child normally inherits the parent's
171/// working directory. But if that directory has been deleted or become
172/// inaccessible (the "getcwd() failed" scenario from issue #44), inheriting it
173/// makes the OS-level spawn fail. In that case fall back to a directory that is
174/// known to exist so the command still runs.
175///
176/// Normal behavior is preserved: when an explicit cwd is given, or when the
177/// inherited working directory is valid, this returns the requested value
178/// (`None` meaning "inherit").
179fn resolve_spawn_cwd(cwd: Option<&PathBuf>) -> Option<PathBuf> {
180    // An explicit directory is always honored as-is.
181    if let Some(c) = cwd {
182        return Some(c.clone());
183    }
184
185    // No explicit cwd: we would inherit the parent's working directory. Make
186    // sure that directory is actually usable before relying on inheritance.
187    match std::env::current_dir() {
188        Ok(_) => None,
189        Err(e) => {
190            let fallback = fallback_cwd();
191            trace(
192                "ProcessRunner",
193                &format!(
194                    "current_dir() failed ({}); spawning in fallback directory {}",
195                    e,
196                    fallback.display()
197                ),
198            );
199            Some(fallback)
200        }
201    }
202}
203
204/// Error type for command-stream operations
205#[derive(Debug, thiserror::Error)]
206pub enum Error {
207    #[error("IO error: {0}")]
208    Io(#[from] std::io::Error),
209
210    #[error("Command failed with exit code {code}: {message}")]
211    CommandFailed { code: i32, message: String },
212
213    #[error("Command not found: {0}")]
214    CommandNotFound(String),
215
216    #[error("Parse error: {0}")]
217    ParseError(String),
218
219    #[error("Cancelled")]
220    Cancelled,
221}
222
223/// Result type for command-stream operations
224pub type Result<T> = std::result::Result<T, Error>;
225
226/// Options for command execution
227#[derive(Debug, Clone)]
228pub struct RunOptions {
229    /// Mirror output to parent stdout/stderr
230    pub mirror: bool,
231    /// Capture output in result
232    pub capture: bool,
233    /// Standard input handling
234    pub stdin: StdinOption,
235    /// Working directory
236    pub cwd: Option<PathBuf>,
237    /// Environment variables
238    pub env: Option<HashMap<String, String>>,
239    /// Interactive mode (TTY forwarding)
240    pub interactive: bool,
241    /// Enable shell operator parsing
242    pub shell_operators: bool,
243    /// Enable tracing for this command
244    pub trace: bool,
245}
246
247impl Default for RunOptions {
248    fn default() -> Self {
249        RunOptions {
250            mirror: true,
251            capture: true,
252            stdin: StdinOption::Inherit,
253            cwd: None,
254            env: None,
255            interactive: false,
256            shell_operators: true,
257            trace: true,
258        }
259    }
260}
261
262/// Standard input options
263#[derive(Debug, Clone)]
264pub enum StdinOption {
265    /// Inherit from parent process
266    Inherit,
267    /// Pipe (allow writing to stdin)
268    Pipe,
269    /// Provide string content
270    Content(String),
271    /// Null device
272    Null,
273}
274
275/// A running or completed process
276pub struct ProcessRunner {
277    command: String,
278    options: RunOptions,
279    child: Option<Child>,
280    result: Option<CommandResult>,
281    started: bool,
282    finished: bool,
283    cancelled: bool,
284    output_tx: Option<mpsc::Sender<StreamChunk>>,
285    // Held, never read: dropping the receiver would close the channel, and
286    // streaming virtual commands treat a closed channel as "stop now" (see
287    // `commands::yes`, which loops until `output_tx.send` fails). Keeping it
288    // alive is what gives those commands their run-until-cancelled behaviour.
289    #[allow(dead_code)]
290    output_rx: Option<mpsc::Receiver<StreamChunk>>,
291}
292
293impl ProcessRunner {
294    /// Create a new process runner
295    pub fn new(command: impl Into<String>, options: RunOptions) -> Self {
296        let (tx, rx) = mpsc::channel(1024);
297        ProcessRunner {
298            command: command.into(),
299            options,
300            child: None,
301            result: None,
302            started: false,
303            finished: false,
304            cancelled: false,
305            output_tx: Some(tx),
306            output_rx: Some(rx),
307        }
308    }
309
310    /// Start the process
311    pub async fn start(&mut self) -> Result<()> {
312        if self.started {
313            return Ok(());
314        }
315        self.started = true;
316
317        utils::trace_lazy("ProcessRunner", || {
318            format!("Starting command: {}", self.command)
319        });
320
321        // Check if this is a virtual command. Backslash escapes are removed by a
322        // real shell but not by the whitespace splitting used for virtual
323        // command args, so such commands always go to the system shell (#49).
324        // The same applies to redirection and expansions: whitespace splitting
325        // would hand `>`, `out.txt` to the virtual command as two ordinary
326        // arguments, so `echo hello > out.txt` printed the redirection instead
327        // of writing the file, and `git push ... 2>&1` reported success while
328        // nothing was pushed (#46).
329        let first_word = if has_shell_escapes(&self.command) || needs_real_shell(&self.command) {
330            ""
331        } else {
332            self.command.split_whitespace().next().unwrap_or("")
333        };
334        if let Some(result) = self.try_virtual_command(first_word).await {
335            self.result = Some(result);
336            self.finished = true;
337            return Ok(());
338        }
339        // Parse command for shell operators (for future use with virtual command pipelines)
340        let _parsed = if self.options.shell_operators && !needs_real_shell(&self.command) {
341            parse_shell_command(&self.command)
342        } else {
343            None
344        };
345
346        // Execute via real shell if needed
347        let shell = find_available_shell();
348
349        let mut cmd = Command::new(&shell.cmd);
350        for arg in &shell.args {
351            cmd.arg(arg);
352        }
353        utils::append_shell_command(&mut cmd, &self.command, self.options.env.as_ref());
354
355        // Configure stdin
356        match &self.options.stdin {
357            StdinOption::Inherit => {
358                cmd.stdin(Stdio::inherit());
359            }
360            StdinOption::Pipe => {
361                cmd.stdin(Stdio::piped());
362            }
363            StdinOption::Content(_) => {
364                cmd.stdin(Stdio::piped());
365            }
366            StdinOption::Null => {
367                cmd.stdin(Stdio::null());
368            }
369        }
370
371        // Configure stdout/stderr
372        if self.options.capture || self.options.mirror {
373            cmd.stdout(Stdio::piped());
374            cmd.stderr(Stdio::piped());
375        } else {
376            cmd.stdout(Stdio::inherit());
377            cmd.stderr(Stdio::inherit());
378        }
379
380        // Set working directory. Fall back to a valid directory when the
381        // inherited working directory has been deleted (issue #44).
382        if let Some(cwd) = resolve_spawn_cwd(self.options.cwd.as_ref()) {
383            cmd.current_dir(cwd);
384        }
385
386        // Set environment
387        if let Some(ref env_vars) = self.options.env {
388            for (key, value) in env_vars {
389                cmd.env(key, value);
390            }
391        }
392
393        // Spawn the process
394        let child = cmd.spawn()?;
395        self.child = Some(child);
396
397        Ok(())
398    }
399
400    /// Run the process to completion
401    pub async fn run(&mut self) -> Result<CommandResult> {
402        self.start().await?;
403
404        if let Some(result) = &self.result {
405            return Ok(result.clone());
406        }
407
408        let mut child = self
409            .child
410            .take()
411            .ok_or_else(|| Error::Io(std::io::Error::other("Process not started")))?;
412
413        // Handle stdin content if provided
414        if let StdinOption::Content(ref content) = self.options.stdin {
415            if let Some(mut stdin) = child.stdin.take() {
416                let content = content.clone();
417                tokio::spawn(async move {
418                    let _ = stdin.write_all(content.as_bytes()).await;
419                    let _ = stdin.shutdown().await;
420                });
421            }
422        }
423
424        // Drain both pipes concurrently and preserve their newline framing. The
425        // previous line reader appended `\n` to every final line, changing
426        // output from commands such as `printf` that omit a newline (issue #37).
427        let stdout = child.stdout.take();
428        let stderr = child.stderr.take();
429        let collected = tokio::try_join!(
430            collect_child_output(stdout, self.options.mirror, ChildOutput::Stdout),
431            collect_child_output(stderr, self.options.mirror, ChildOutput::Stderr),
432        );
433        let (stdout, stderr) = match collected {
434            Ok(output) => output,
435            Err(error) => {
436                // `try_join!` drops the other pipe reader after an error. Stop
437                // and reap the child so it cannot remain blocked on that pipe.
438                let _ = child.start_kill();
439                let _ = child.wait().await;
440                return Err(error.into());
441            }
442        };
443
444        let status = child.wait().await?;
445        let code = status.code().unwrap_or(-1);
446
447        let result = CommandResult {
448            stdout: String::from_utf8_lossy(&stdout).into_owned(),
449            stderr: String::from_utf8_lossy(&stderr).into_owned(),
450            code,
451        };
452
453        self.result = Some(result.clone());
454        self.finished = true;
455
456        Ok(result)
457    }
458
459    /// Try to execute as a virtual command
460    async fn try_virtual_command(&self, cmd_name: &str) -> Option<CommandResult> {
461        if !commands::are_virtual_commands_enabled() {
462            return None;
463        }
464
465        // An empty command name means the caller already decided this command
466        // must go to a real shell (redirection, expansions, escapes). Bail out
467        // before tokenizing so we neither waste work nor parse shell syntax we
468        // deliberately delegate.
469        if cmd_name.is_empty() {
470            return None;
471        }
472
473        // Parse args from command string, respecting quotes and performing
474        // POSIX quote removal so `echo label:'help wanted'` reaches the built-in
475        // as the single argument `label:help wanted` (issue #48).
476        let words = shell_parser::split_command_words(&self.command);
477        let args: Vec<String> = words.into_iter().skip(1).collect();
478
479        let ctx = CommandContext {
480            args,
481            stdin: match &self.options.stdin {
482                StdinOption::Content(s) => Some(s.clone()),
483                _ => None,
484            },
485            cwd: self.options.cwd.clone(),
486            env: self.options.env.clone(),
487            output_tx: self.output_tx.clone(),
488            is_cancelled: None,
489        };
490
491        match cmd_name {
492            "echo" => Some(commands::echo(ctx).await),
493            "pwd" => Some(commands::pwd(ctx).await),
494            "cd" => Some(commands::cd::resolve_cd(ctx).await.0),
495            "true" => Some(commands::r#true(ctx).await),
496            "false" => Some(commands::r#false(ctx).await),
497            "sleep" => Some(commands::sleep(ctx).await),
498            "cat" => Some(commands::cat(ctx).await),
499            "ls" => Some(commands::ls(ctx).await),
500            "mkdir" => Some(commands::mkdir(ctx).await),
501            "rm" => Some(commands::rm(ctx).await),
502            "touch" => Some(commands::touch(ctx).await),
503            "cp" => Some(commands::cp(ctx).await),
504            "mv" => Some(commands::mv(ctx).await),
505            "basename" => Some(commands::basename(ctx).await),
506            "dirname" => Some(commands::dirname(ctx).await),
507            "env" => Some(commands::env(ctx).await),
508            "exit" => Some(commands::exit(ctx).await),
509            "which" => Some(commands::which(ctx).await),
510            "yes" => Some(commands::yes(ctx).await),
511            "seq" => Some(commands::seq(ctx).await),
512            "test" => Some(commands::test(ctx).await),
513            _ => None,
514        }
515    }
516
517    /// Kill the process
518    pub fn kill(&mut self) -> Result<()> {
519        self.cancelled = true;
520        if let Some(ref mut child) = self.child {
521            child.start_kill()?;
522        }
523        Ok(())
524    }
525
526    /// Check if the process is finished
527    pub fn is_finished(&self) -> bool {
528        self.finished
529    }
530
531    /// Get the result if available
532    pub fn result(&self) -> Option<&CommandResult> {
533        self.result.as_ref()
534    }
535
536    /// Get the command string
537    pub fn command(&self) -> &str {
538        &self.command
539    }
540
541    /// Get the options
542    pub fn options(&self) -> &RunOptions {
543        &self.options
544    }
545}
546
547/// Shell configuration
548#[derive(Debug, Clone)]
549struct ShellConfig {
550    cmd: String,
551    args: Vec<String>,
552}
553
554/// Find an available shell
555fn find_available_shell() -> ShellConfig {
556    let is_windows = cfg!(windows);
557
558    if is_windows {
559        // Windows shells
560        let shells = [
561            ("cmd.exe", vec!["/c"]),
562            ("powershell.exe", vec!["-Command"]),
563        ];
564
565        for (cmd, args) in shells {
566            if which::which(cmd).is_ok() {
567                return ShellConfig {
568                    cmd: cmd.to_string(),
569                    args: args.into_iter().map(String::from).collect(),
570                };
571            }
572        }
573
574        ShellConfig {
575            cmd: "cmd.exe".to_string(),
576            args: vec!["/c".to_string()],
577        }
578    } else {
579        // Unix shells
580        let shells = [
581            ("/bin/sh", vec!["-c"]),
582            ("/usr/bin/sh", vec!["-c"]),
583            ("/bin/bash", vec!["-c"]),
584            ("sh", vec!["-c"]),
585        ];
586
587        for (cmd, args) in shells {
588            if std::path::Path::new(cmd).exists() || which::which(cmd).is_ok() {
589                return ShellConfig {
590                    cmd: cmd.to_string(),
591                    args: args.into_iter().map(String::from).collect(),
592                };
593            }
594        }
595
596        ShellConfig {
597            cmd: "/bin/sh".to_string(),
598            args: vec!["-c".to_string()],
599        }
600    }
601}
602
603/// Execute a command and return the result
604///
605/// This is the main entry point for simple command execution.
606/// Named `run` instead of `$` since `$` is not a valid Rust identifier.
607pub async fn run(command: impl Into<String>) -> Result<CommandResult> {
608    let mut runner = ProcessRunner::new(command, RunOptions::default());
609    runner.run().await
610}
611
612/// Alias for `run` function - for JavaScript-like API feel
613/// Since `$` is not valid in Rust, this provides a similar short name
614pub use run as execute;
615
616/// Execute a command with custom options
617pub async fn exec(command: impl Into<String>, options: RunOptions) -> Result<CommandResult> {
618    let mut runner = ProcessRunner::new(command, options);
619    runner.run().await
620}
621
622/// Create a new process runner without starting it
623pub fn create(command: impl Into<String>, options: RunOptions) -> ProcessRunner {
624    ProcessRunner::new(command, options)
625}
626
627/// Execute a command synchronously (blocking)
628pub fn run_sync(command: impl Into<String>) -> Result<CommandResult> {
629    let rt = tokio::runtime::Runtime::new()?;
630    rt.block_on(run(command))
631}
632
633// Tests are located in tests/ directory for better organization