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 cmd.arg(utils::with_exported_process_context(
354 &self.command,
355 self.options.env.as_ref(),
356 ));
357
358 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 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 if let Some(cwd) = resolve_spawn_cwd(self.options.cwd.as_ref()) {
386 cmd.current_dir(cwd);
387 }
388
389 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 let child = cmd.spawn()?;
398 self.child = Some(child);
399
400 Ok(())
401 }
402
403 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 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 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 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 async fn try_virtual_command(&self, cmd_name: &str) -> Option<CommandResult> {
464 if !commands::are_virtual_commands_enabled() {
465 return None;
466 }
467
468 if cmd_name.is_empty() {
473 return None;
474 }
475
476 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 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 pub fn is_finished(&self) -> bool {
531 self.finished
532 }
533
534 pub fn result(&self) -> Option<&CommandResult> {
536 self.result.as_ref()
537 }
538
539 pub fn command(&self) -> &str {
541 &self.command
542 }
543
544 pub fn options(&self) -> &RunOptions {
546 &self.options
547 }
548}
549
550#[derive(Debug, Clone)]
552struct ShellConfig {
553 cmd: String,
554 args: Vec<String>,
555}
556
557fn find_available_shell() -> ShellConfig {
559 let is_windows = cfg!(windows);
560
561 if is_windows {
562 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 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
606pub async fn run(command: impl Into<String>) -> Result<CommandResult> {
611 let mut runner = ProcessRunner::new(command, RunOptions::default());
612 runner.run().await
613}
614
615pub use run as execute;
618
619pub 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
625pub fn create(command: impl Into<String>, options: RunOptions) -> ProcessRunner {
627 ProcessRunner::new(command, options)
628}
629
630pub 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