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::{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
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_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
115fn resolve_spawn_cwd(cwd: Option<&PathBuf>) -> Option<PathBuf> {
127 if let Some(c) = cwd {
129 return Some(c.clone());
130 }
131
132 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#[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
170pub type Result<T> = std::result::Result<T, Error>;
172
173#[derive(Debug, Clone)]
175pub struct RunOptions {
176 pub mirror: bool,
178 pub capture: bool,
180 pub stdin: StdinOption,
182 pub cwd: Option<PathBuf>,
184 pub env: Option<HashMap<String, String>>,
186 pub interactive: bool,
188 pub shell_operators: bool,
190 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#[derive(Debug, Clone)]
211pub enum StdinOption {
212 Inherit,
214 Pipe,
216 Content(String),
218 Null,
220}
221
222pub 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 output_rx: Option<mpsc::Receiver<StreamChunk>>,
233}
234
235impl ProcessRunner {
236 pub fn new(command: impl Into<String>, options: RunOptions) -> Self {
238 let (tx, rx) = mpsc::channel(1024);
239 ProcessRunner {
240 command: command.into(),
241 options,
242 child: None,
243 result: None,
244 started: false,
245 finished: false,
246 cancelled: false,
247 output_tx: Some(tx),
248 output_rx: Some(rx),
249 }
250 }
251
252 pub async fn start(&mut self) -> Result<()> {
254 if self.started {
255 return Ok(());
256 }
257 self.started = true;
258
259 utils::trace_lazy("ProcessRunner", || {
260 format!("Starting command: {}", self.command)
261 });
262
263 let first_word = if has_shell_escapes(&self.command) {
267 ""
268 } else {
269 self.command.split_whitespace().next().unwrap_or("")
270 };
271 if let Some(result) = self.try_virtual_command(first_word).await {
272 self.result = Some(result);
273 self.finished = true;
274 return Ok(());
275 }
276 let _parsed = if self.options.shell_operators && !needs_real_shell(&self.command) {
278 parse_shell_command(&self.command)
279 } else {
280 None
281 };
282
283 let shell = find_available_shell();
285
286 let mut cmd = Command::new(&shell.cmd);
287 for arg in &shell.args {
288 cmd.arg(arg);
289 }
290 cmd.arg(utils::with_exported_process_context(
291 &self.command,
292 self.options.env.as_ref(),
293 ));
294
295 match &self.options.stdin {
297 StdinOption::Inherit => {
298 cmd.stdin(Stdio::inherit());
299 }
300 StdinOption::Pipe => {
301 cmd.stdin(Stdio::piped());
302 }
303 StdinOption::Content(_) => {
304 cmd.stdin(Stdio::piped());
305 }
306 StdinOption::Null => {
307 cmd.stdin(Stdio::null());
308 }
309 }
310
311 if self.options.capture || self.options.mirror {
313 cmd.stdout(Stdio::piped());
314 cmd.stderr(Stdio::piped());
315 } else {
316 cmd.stdout(Stdio::inherit());
317 cmd.stderr(Stdio::inherit());
318 }
319
320 if let Some(cwd) = resolve_spawn_cwd(self.options.cwd.as_ref()) {
323 cmd.current_dir(cwd);
324 }
325
326 if let Some(ref env_vars) = self.options.env {
328 for (key, value) in env_vars {
329 cmd.env(key, value);
330 }
331 }
332
333 let child = cmd.spawn()?;
335 self.child = Some(child);
336
337 Ok(())
338 }
339
340 pub async fn run(&mut self) -> Result<CommandResult> {
342 self.start().await?;
343
344 if let Some(result) = &self.result {
345 return Ok(result.clone());
346 }
347
348 let mut child = self.child.take().ok_or_else(|| {
349 Error::Io(std::io::Error::new(
350 std::io::ErrorKind::Other,
351 "Process not started",
352 ))
353 })?;
354
355 if let StdinOption::Content(ref content) = self.options.stdin {
357 if let Some(mut stdin) = child.stdin.take() {
358 let content = content.clone();
359 tokio::spawn(async move {
360 let _ = stdin.write_all(content.as_bytes()).await;
361 let _ = stdin.shutdown().await;
362 });
363 }
364 }
365
366 let mut stdout_content = String::new();
368 let mut stderr_content = String::new();
369
370 if let Some(stdout) = child.stdout.take() {
371 let mut reader = BufReader::new(stdout).lines();
372 while let Ok(Some(line)) = reader.next_line().await {
373 if self.options.mirror {
374 println!("{}", line);
375 }
376 stdout_content.push_str(&line);
377 stdout_content.push('\n');
378 }
379 }
380
381 if let Some(stderr) = child.stderr.take() {
382 let mut reader = BufReader::new(stderr).lines();
383 while let Ok(Some(line)) = reader.next_line().await {
384 if self.options.mirror {
385 eprintln!("{}", line);
386 }
387 stderr_content.push_str(&line);
388 stderr_content.push('\n');
389 }
390 }
391
392 let status = child.wait().await?;
393 let code = status.code().unwrap_or(-1);
394
395 let result = CommandResult {
396 stdout: stdout_content,
397 stderr: stderr_content,
398 code,
399 };
400
401 self.result = Some(result.clone());
402 self.finished = true;
403
404 Ok(result)
405 }
406
407 async fn try_virtual_command(&self, cmd_name: &str) -> Option<CommandResult> {
409 if !commands::are_virtual_commands_enabled() {
410 return None;
411 }
412
413 let parts: Vec<&str> = self.command.split_whitespace().collect();
415 let args: Vec<String> = parts.iter().skip(1).map(|s| s.to_string()).collect();
416
417 let ctx = CommandContext {
418 args,
419 stdin: match &self.options.stdin {
420 StdinOption::Content(s) => Some(s.clone()),
421 _ => None,
422 },
423 cwd: self.options.cwd.clone(),
424 env: self.options.env.clone(),
425 output_tx: self.output_tx.clone(),
426 is_cancelled: None,
427 };
428
429 match cmd_name {
430 "echo" => Some(commands::echo(ctx).await),
431 "pwd" => Some(commands::pwd(ctx).await),
432 "cd" => Some(commands::cd::resolve_cd(ctx).await.0),
433 "true" => Some(commands::r#true(ctx).await),
434 "false" => Some(commands::r#false(ctx).await),
435 "sleep" => Some(commands::sleep(ctx).await),
436 "cat" => Some(commands::cat(ctx).await),
437 "ls" => Some(commands::ls(ctx).await),
438 "mkdir" => Some(commands::mkdir(ctx).await),
439 "rm" => Some(commands::rm(ctx).await),
440 "touch" => Some(commands::touch(ctx).await),
441 "cp" => Some(commands::cp(ctx).await),
442 "mv" => Some(commands::mv(ctx).await),
443 "basename" => Some(commands::basename(ctx).await),
444 "dirname" => Some(commands::dirname(ctx).await),
445 "env" => Some(commands::env(ctx).await),
446 "exit" => Some(commands::exit(ctx).await),
447 "which" => Some(commands::which(ctx).await),
448 "yes" => Some(commands::yes(ctx).await),
449 "seq" => Some(commands::seq(ctx).await),
450 "test" => Some(commands::test(ctx).await),
451 _ => None,
452 }
453 }
454
455 pub fn kill(&mut self) -> Result<()> {
457 self.cancelled = true;
458 if let Some(ref mut child) = self.child {
459 child.start_kill()?;
460 }
461 Ok(())
462 }
463
464 pub fn is_finished(&self) -> bool {
466 self.finished
467 }
468
469 pub fn result(&self) -> Option<&CommandResult> {
471 self.result.as_ref()
472 }
473
474 pub fn command(&self) -> &str {
476 &self.command
477 }
478
479 pub fn options(&self) -> &RunOptions {
481 &self.options
482 }
483}
484
485#[derive(Debug, Clone)]
487struct ShellConfig {
488 cmd: String,
489 args: Vec<String>,
490}
491
492fn find_available_shell() -> ShellConfig {
494 let is_windows = cfg!(windows);
495
496 if is_windows {
497 let shells = [
499 ("cmd.exe", vec!["/c"]),
500 ("powershell.exe", vec!["-Command"]),
501 ];
502
503 for (cmd, args) in shells {
504 if which::which(cmd).is_ok() {
505 return ShellConfig {
506 cmd: cmd.to_string(),
507 args: args.into_iter().map(String::from).collect(),
508 };
509 }
510 }
511
512 ShellConfig {
513 cmd: "cmd.exe".to_string(),
514 args: vec!["/c".to_string()],
515 }
516 } else {
517 let shells = [
519 ("/bin/sh", vec!["-c"]),
520 ("/usr/bin/sh", vec!["-c"]),
521 ("/bin/bash", vec!["-c"]),
522 ("sh", vec!["-c"]),
523 ];
524
525 for (cmd, args) in shells {
526 if std::path::Path::new(cmd).exists() || which::which(cmd).is_ok() {
527 return ShellConfig {
528 cmd: cmd.to_string(),
529 args: args.into_iter().map(String::from).collect(),
530 };
531 }
532 }
533
534 ShellConfig {
535 cmd: "/bin/sh".to_string(),
536 args: vec!["-c".to_string()],
537 }
538 }
539}
540
541pub async fn run(command: impl Into<String>) -> Result<CommandResult> {
546 let mut runner = ProcessRunner::new(command, RunOptions::default());
547 runner.run().await
548}
549
550pub use run as execute;
553
554pub async fn exec(command: impl Into<String>, options: RunOptions) -> Result<CommandResult> {
556 let mut runner = ProcessRunner::new(command, options);
557 runner.run().await
558}
559
560pub fn create(command: impl Into<String>, options: RunOptions) -> ProcessRunner {
562 ProcessRunner::new(command, options)
563}
564
565pub fn run_sync(command: impl Into<String>) -> Result<CommandResult> {
567 let rt = tokio::runtime::Runtime::new()?;
568 rt.block_on(run(command))
569}
570
571