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        cmd.arg(utils::with_exported_process_context(
354            &self.command,
355            self.options.env.as_ref(),
356        ));
357
358        // Configure stdin
359        match &self.options.stdin {
360            StdinOption::Inherit => {
361                cmd.stdin(Stdio::inherit());
362            }
363            StdinOption::Pipe => {
364                cmd.stdin(Stdio::piped());
365            }
366            StdinOption::Content(_) => {
367                cmd.stdin(Stdio::piped());
368            }
369            StdinOption::Null => {
370                cmd.stdin(Stdio::null());
371            }
372        }
373
374        // Configure stdout/stderr
375        if self.options.capture || self.options.mirror {
376            cmd.stdout(Stdio::piped());
377            cmd.stderr(Stdio::piped());
378        } else {
379            cmd.stdout(Stdio::inherit());
380            cmd.stderr(Stdio::inherit());
381        }
382
383        // Set working directory. Fall back to a valid directory when the
384        // inherited working directory has been deleted (issue #44).
385        if let Some(cwd) = resolve_spawn_cwd(self.options.cwd.as_ref()) {
386            cmd.current_dir(cwd);
387        }
388
389        // Set environment
390        if let Some(ref env_vars) = self.options.env {
391            for (key, value) in env_vars {
392                cmd.env(key, value);
393            }
394        }
395
396        // Spawn the process
397        let child = cmd.spawn()?;
398        self.child = Some(child);
399
400        Ok(())
401    }
402
403    /// Run the process to completion
404    pub async fn run(&mut self) -> Result<CommandResult> {
405        self.start().await?;
406
407        if let Some(result) = &self.result {
408            return Ok(result.clone());
409        }
410
411        let mut child = self
412            .child
413            .take()
414            .ok_or_else(|| Error::Io(std::io::Error::other("Process not started")))?;
415
416        // Handle stdin content if provided
417        if let StdinOption::Content(ref content) = self.options.stdin {
418            if let Some(mut stdin) = child.stdin.take() {
419                let content = content.clone();
420                tokio::spawn(async move {
421                    let _ = stdin.write_all(content.as_bytes()).await;
422                    let _ = stdin.shutdown().await;
423                });
424            }
425        }
426
427        // Drain both pipes concurrently and preserve their newline framing. The
428        // previous line reader appended `\n` to every final line, changing
429        // output from commands such as `printf` that omit a newline (issue #37).
430        let stdout = child.stdout.take();
431        let stderr = child.stderr.take();
432        let collected = tokio::try_join!(
433            collect_child_output(stdout, self.options.mirror, ChildOutput::Stdout),
434            collect_child_output(stderr, self.options.mirror, ChildOutput::Stderr),
435        );
436        let (stdout, stderr) = match collected {
437            Ok(output) => output,
438            Err(error) => {
439                // `try_join!` drops the other pipe reader after an error. Stop
440                // and reap the child so it cannot remain blocked on that pipe.
441                let _ = child.start_kill();
442                let _ = child.wait().await;
443                return Err(error.into());
444            }
445        };
446
447        let status = child.wait().await?;
448        let code = status.code().unwrap_or(-1);
449
450        let result = CommandResult {
451            stdout: String::from_utf8_lossy(&stdout).into_owned(),
452            stderr: String::from_utf8_lossy(&stderr).into_owned(),
453            code,
454        };
455
456        self.result = Some(result.clone());
457        self.finished = true;
458
459        Ok(result)
460    }
461
462    /// Try to execute as a virtual command
463    async fn try_virtual_command(&self, cmd_name: &str) -> Option<CommandResult> {
464        if !commands::are_virtual_commands_enabled() {
465            return None;
466        }
467
468        // An empty command name means the caller already decided this command
469        // must go to a real shell (redirection, expansions, escapes). Bail out
470        // before tokenizing so we neither waste work nor parse shell syntax we
471        // deliberately delegate.
472        if cmd_name.is_empty() {
473            return None;
474        }
475
476        // Parse args from command string, respecting quotes and performing
477        // POSIX quote removal so `echo label:'help wanted'` reaches the built-in
478        // as the single argument `label:help wanted` (issue #48).
479        let words = shell_parser::split_command_words(&self.command);
480        let args: Vec<String> = words.into_iter().skip(1).collect();
481
482        let ctx = CommandContext {
483            args,
484            stdin: match &self.options.stdin {
485                StdinOption::Content(s) => Some(s.clone()),
486                _ => None,
487            },
488            cwd: self.options.cwd.clone(),
489            env: self.options.env.clone(),
490            output_tx: self.output_tx.clone(),
491            is_cancelled: None,
492        };
493
494        match cmd_name {
495            "echo" => Some(commands::echo(ctx).await),
496            "pwd" => Some(commands::pwd(ctx).await),
497            "cd" => Some(commands::cd::resolve_cd(ctx).await.0),
498            "true" => Some(commands::r#true(ctx).await),
499            "false" => Some(commands::r#false(ctx).await),
500            "sleep" => Some(commands::sleep(ctx).await),
501            "cat" => Some(commands::cat(ctx).await),
502            "ls" => Some(commands::ls(ctx).await),
503            "mkdir" => Some(commands::mkdir(ctx).await),
504            "rm" => Some(commands::rm(ctx).await),
505            "touch" => Some(commands::touch(ctx).await),
506            "cp" => Some(commands::cp(ctx).await),
507            "mv" => Some(commands::mv(ctx).await),
508            "basename" => Some(commands::basename(ctx).await),
509            "dirname" => Some(commands::dirname(ctx).await),
510            "env" => Some(commands::env(ctx).await),
511            "exit" => Some(commands::exit(ctx).await),
512            "which" => Some(commands::which(ctx).await),
513            "yes" => Some(commands::yes(ctx).await),
514            "seq" => Some(commands::seq(ctx).await),
515            "test" => Some(commands::test(ctx).await),
516            _ => None,
517        }
518    }
519
520    /// Kill the process
521    pub fn kill(&mut self) -> Result<()> {
522        self.cancelled = true;
523        if let Some(ref mut child) = self.child {
524            child.start_kill()?;
525        }
526        Ok(())
527    }
528
529    /// Check if the process is finished
530    pub fn is_finished(&self) -> bool {
531        self.finished
532    }
533
534    /// Get the result if available
535    pub fn result(&self) -> Option<&CommandResult> {
536        self.result.as_ref()
537    }
538
539    /// Get the command string
540    pub fn command(&self) -> &str {
541        &self.command
542    }
543
544    /// Get the options
545    pub fn options(&self) -> &RunOptions {
546        &self.options
547    }
548}
549
550/// Shell configuration
551#[derive(Debug, Clone)]
552struct ShellConfig {
553    cmd: String,
554    args: Vec<String>,
555}
556
557/// Find an available shell
558fn find_available_shell() -> ShellConfig {
559    let is_windows = cfg!(windows);
560
561    if is_windows {
562        // Windows shells
563        let shells = [
564            ("cmd.exe", vec!["/c"]),
565            ("powershell.exe", vec!["-Command"]),
566        ];
567
568        for (cmd, args) in shells {
569            if which::which(cmd).is_ok() {
570                return ShellConfig {
571                    cmd: cmd.to_string(),
572                    args: args.into_iter().map(String::from).collect(),
573                };
574            }
575        }
576
577        ShellConfig {
578            cmd: "cmd.exe".to_string(),
579            args: vec!["/c".to_string()],
580        }
581    } else {
582        // Unix shells
583        let shells = [
584            ("/bin/sh", vec!["-c"]),
585            ("/usr/bin/sh", vec!["-c"]),
586            ("/bin/bash", vec!["-c"]),
587            ("sh", vec!["-c"]),
588        ];
589
590        for (cmd, args) in shells {
591            if std::path::Path::new(cmd).exists() || which::which(cmd).is_ok() {
592                return ShellConfig {
593                    cmd: cmd.to_string(),
594                    args: args.into_iter().map(String::from).collect(),
595                };
596            }
597        }
598
599        ShellConfig {
600            cmd: "/bin/sh".to_string(),
601            args: vec!["-c".to_string()],
602        }
603    }
604}
605
606/// Execute a command and return the result
607///
608/// This is the main entry point for simple command execution.
609/// Named `run` instead of `$` since `$` is not a valid Rust identifier.
610pub async fn run(command: impl Into<String>) -> Result<CommandResult> {
611    let mut runner = ProcessRunner::new(command, RunOptions::default());
612    runner.run().await
613}
614
615/// Alias for `run` function - for JavaScript-like API feel
616/// Since `$` is not valid in Rust, this provides a similar short name
617pub use run as execute;
618
619/// Execute a command with custom options
620pub async fn exec(command: impl Into<String>, options: RunOptions) -> Result<CommandResult> {
621    let mut runner = ProcessRunner::new(command, options);
622    runner.run().await
623}
624
625/// Create a new process runner without starting it
626pub fn create(command: impl Into<String>, options: RunOptions) -> ProcessRunner {
627    ProcessRunner::new(command, options)
628}
629
630/// Execute a command synchronously (blocking)
631pub fn run_sync(command: impl Into<String>) -> Result<CommandResult> {
632    let rt = tokio::runtime::Runtime::new()?;
633    rt.block_on(run(command))
634}
635
636// Tests are located in tests/ directory for better organization