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