1pub 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
76pub 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
92pub 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
114async 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
168fn resolve_spawn_cwd(cwd: Option<&PathBuf>) -> Option<PathBuf> {
180 if let Some(c) = cwd {
182 return Some(c.clone());
183 }
184
185 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#[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
223pub type Result<T> = std::result::Result<T, Error>;
225
226#[derive(Debug, Clone)]
228pub struct RunOptions {
229 pub mirror: bool,
231 pub capture: bool,
233 pub stdin: StdinOption,
235 pub cwd: Option<PathBuf>,
237 pub env: Option<HashMap<String, String>>,
239 pub interactive: bool,
241 pub shell_operators: bool,
243 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#[derive(Debug, Clone)]
264pub enum StdinOption {
265 Inherit,
267 Pipe,
269 Content(String),
271 Null,
273}
274
275pub 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 #[allow(dead_code)]
290 output_rx: Option<mpsc::Receiver<StreamChunk>>,
291}
292
293impl ProcessRunner {
294 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 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 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 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 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 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 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 if let Some(cwd) = resolve_spawn_cwd(self.options.cwd.as_ref()) {
383 cmd.current_dir(cwd);
384 }
385
386 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 let child = cmd.spawn()?;
395 self.child = Some(child);
396
397 Ok(())
398 }
399
400 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 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 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 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 async fn try_virtual_command(&self, cmd_name: &str) -> Option<CommandResult> {
461 if !commands::are_virtual_commands_enabled() {
462 return None;
463 }
464
465 if cmd_name.is_empty() {
470 return None;
471 }
472
473 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 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 pub fn is_finished(&self) -> bool {
528 self.finished
529 }
530
531 pub fn result(&self) -> Option<&CommandResult> {
533 self.result.as_ref()
534 }
535
536 pub fn command(&self) -> &str {
538 &self.command
539 }
540
541 pub fn options(&self) -> &RunOptions {
543 &self.options
544 }
545}
546
547#[derive(Debug, Clone)]
549struct ShellConfig {
550 cmd: String,
551 args: Vec<String>,
552}
553
554fn find_available_shell() -> ShellConfig {
556 let is_windows = cfg!(windows);
557
558 if is_windows {
559 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 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
603pub async fn run(command: impl Into<String>) -> Result<CommandResult> {
608 let mut runner = ProcessRunner::new(command, RunOptions::default());
609 runner.run().await
610}
611
612pub use run as execute;
615
616pub 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
622pub fn create(command: impl Into<String>, options: RunOptions) -> ProcessRunner {
624 ProcessRunner::new(command, options)
625}
626
627pub 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