Skip to main content

cargo_run/commands/
script.rs

1//! This module provides the functionality to run scripts defined in `Scripts.toml`.
2//!
3//! In addition to the original execution engine, this module now supports:
4//!
5//! * Workspace-aware execution (run a script in every workspace member, in
6//!   parallel or sequentially).
7//! * Cargo script (single-file Rust packages, RFC 3502) integration: any
8//!   command pointing at a `.rs` file is executed via `cargo +nightly -Zscript`
9//!   (or stable `cargo` when available).
10//! * Pre/post/on_success/on_failure hooks.
11//! * Parameterized commands using `{{arg}}` template substitution and
12//!   key=value CLI arguments.
13//! * Optional structured JSON output.
14
15use std::{
16    collections::HashMap,
17    env,
18    process::{Command, Stdio},
19    sync::{Arc, Mutex},
20    time::{Duration, Instant},
21};
22use serde::Deserialize;
23use emoji::symbols;
24use colored::*;
25use dialoguer::FuzzySelect;
26
27/// Workspace execution mode for a single script.
28#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
29#[serde(rename_all = "lowercase")]
30pub enum WorkspaceMode {
31    /// Execute the script once in every workspace member sequentially.
32    All,
33    /// Execute the script in every workspace member in parallel.
34    Parallel,
35    /// Execute the script only at the workspace root (default behaviour).
36    Root,
37}
38
39/// Top-level workspace configuration declared inside `Scripts.toml`.
40#[derive(Deserialize, Debug, Clone, Default)]
41pub struct WorkspaceConfig {
42    /// Optional explicit list of members. When omitted, members are discovered
43    /// from `Cargo.toml`.
44    pub members: Option<Vec<String>>,
45    /// Members to exclude from workspace runs.
46    pub exclude: Option<Vec<String>>,
47}
48
49/// Enum representing a script. Backward compatible with all v0.5 layouts.
50#[derive(Deserialize, Debug, Clone)]
51#[serde(untagged)]
52pub enum Script {
53    /// Simple form: `name = "command"`.
54    Default(String),
55    /// Inline / table form. All fields are optional to remain backward
56    /// compatible. Scripts that previously parsed as `Inline` keep parsing
57    /// the same way; new fields are additive.
58    Inline {
59        command: Option<String>,
60        requires: Option<Vec<String>>,
61        toolchain: Option<String>,
62        info: Option<String>,
63        env: Option<HashMap<String, String>>,
64        include: Option<Vec<String>>,
65        interpreter: Option<String>,
66        // ---- NEW FIELDS (all opt-in / backward compatible) -----------------
67        /// Explicit cargo-script (single-file `.rs`) path.
68        script_file: Option<String>,
69        /// Names of CLI arguments accepted by this script (used with
70        /// `{{name}}` substitution in `command`).
71        args: Option<Vec<String>>,
72        /// Default values for `args`.
73        defaults: Option<HashMap<String, String>>,
74        /// Workspace execution mode.
75        workspace: Option<WorkspaceMode>,
76        /// Hooks: scripts run before the main command.
77        pre: Option<Vec<String>>,
78        /// Hooks: scripts run after the main command (always).
79        post: Option<Vec<String>>,
80        /// Hooks: scripts run only when the main command succeeds.
81        on_success: Option<Vec<String>>,
82        /// Hooks: scripts run only when the main command fails.
83        on_failure: Option<Vec<String>>,
84    },
85    /// CI-like layout, retained for backward compatibility.
86    CILike {
87        script: String,
88        command: Option<String>,
89        requires: Option<Vec<String>>,
90        toolchain: Option<String>,
91        info: Option<String>,
92        env: Option<HashMap<String, String>>,
93        include: Option<Vec<String>>,
94        interpreter: Option<String>,
95        // NEW FIELDS - mirror Inline
96        script_file: Option<String>,
97        args: Option<Vec<String>>,
98        defaults: Option<HashMap<String, String>>,
99        workspace: Option<WorkspaceMode>,
100        pre: Option<Vec<String>>,
101        post: Option<Vec<String>>,
102        on_success: Option<Vec<String>>,
103        on_failure: Option<Vec<String>>,
104    }
105}
106
107/// Struct representing the collection of scripts defined in `Scripts.toml`.
108#[derive(Deserialize, Debug, Clone, Default)]
109pub struct Scripts {
110    pub global_env: Option<HashMap<String, String>>,
111    #[serde(default)]
112    pub scripts: HashMap<String, Script>,
113    /// Optional workspace configuration.
114    pub workspace: Option<WorkspaceConfig>,
115}
116
117use crate::error::{CargoScriptError, create_tool_not_found_error, create_toolchain_not_found_error};
118
119// ---------------------------------------------------------------------------
120// Public options & result types
121// ---------------------------------------------------------------------------
122
123/// Bundle of all execution options for `run_script`. Designed so callers do
124/// not have to change every signature when new options are added.
125#[derive(Debug, Clone, Default)]
126pub struct RunOptions {
127    pub env_overrides: Vec<String>,
128    pub dry_run: bool,
129    pub quiet: bool,
130    pub verbose: bool,
131    pub show_metrics: bool,
132    /// CLI parameters in `key=value` form (or positional, see [`parse_script_args`]).
133    pub script_args: Vec<String>,
134    /// Explicit workspace mode override from CLI.
135    pub workspace_override: Option<WorkspaceMode>,
136    /// When true, ignore any workspace mode declared in the script.
137    pub no_workspace: bool,
138    /// When true, emit results as a JSON document on stdout.
139    pub json_output: bool,
140}
141
142impl RunOptions {
143    pub fn new() -> Self {
144        Self {
145            show_metrics: true,
146            ..Default::default()
147        }
148    }
149}
150
151/// Structured result of executing a script (used for JSON output).
152#[derive(Debug, Clone, serde::Serialize)]
153pub struct ExecutionResult {
154    pub success: bool,
155    pub script: String,
156    pub command: Option<String>,
157    pub duration_ms: u128,
158    pub exit_code: Option<i32>,
159    pub error: Option<String>,
160    pub includes: Vec<ExecutionResult>,
161    pub hooks: Vec<ExecutionResult>,
162}
163
164impl ExecutionResult {
165    pub fn new(script: &str) -> Self {
166        Self {
167            success: true,
168            script: script.to_string(),
169            command: None,
170            duration_ms: 0,
171            exit_code: None,
172            error: None,
173            includes: Vec::new(),
174            hooks: Vec::new(),
175        }
176    }
177}
178
179// ---------------------------------------------------------------------------
180// Script field accessors (avoid duplicating match arms everywhere)
181// ---------------------------------------------------------------------------
182
183/// Borrowed view over the (extended) fields of a script. Lets callers handle
184/// `Inline` and `CILike` uniformly.
185pub struct ScriptView<'a> {
186    pub command: Option<&'a String>,
187    pub requires: Option<&'a Vec<String>>,
188    pub toolchain: Option<&'a String>,
189    pub info: Option<&'a String>,
190    pub env: Option<&'a HashMap<String, String>>,
191    pub include: Option<&'a Vec<String>>,
192    pub interpreter: Option<&'a String>,
193    pub script_file: Option<&'a String>,
194    pub args: Option<&'a Vec<String>>,
195    pub defaults: Option<&'a HashMap<String, String>>,
196    pub workspace: Option<WorkspaceMode>,
197    pub pre: Option<&'a Vec<String>>,
198    pub post: Option<&'a Vec<String>>,
199    pub on_success: Option<&'a Vec<String>>,
200    pub on_failure: Option<&'a Vec<String>>,
201}
202
203pub fn view(script: &Script) -> Option<ScriptView<'_>> {
204    match script {
205        Script::Default(_) => None,
206        Script::Inline { command, requires, toolchain, info, env, include, interpreter, script_file, args, defaults, workspace, pre, post, on_success, on_failure }
207        | Script::CILike { command, requires, toolchain, info, env, include, interpreter, script_file, args, defaults, workspace, pre, post, on_success, on_failure, .. } => {
208            Some(ScriptView {
209                command: command.as_ref(),
210                requires: requires.as_ref(),
211                toolchain: toolchain.as_ref(),
212                info: info.as_ref(),
213                env: env.as_ref(),
214                include: include.as_ref(),
215                interpreter: interpreter.as_ref(),
216                script_file: script_file.as_ref(),
217                args: args.as_ref(),
218                defaults: defaults.as_ref(),
219                workspace: *workspace,
220                pre: pre.as_ref(),
221                post: post.as_ref(),
222                on_success: on_success.as_ref(),
223                on_failure: on_failure.as_ref(),
224            })
225        }
226    }
227}
228
229// ---------------------------------------------------------------------------
230// Parameter substitution
231// ---------------------------------------------------------------------------
232
233/// Parse user-supplied script arguments. Supports two styles, freely mixed:
234///
235/// * `key=value` — explicit named argument.
236/// * `value` — positional, mapped to the script's `args` definition by index.
237pub fn parse_script_args(view: &ScriptView<'_>, raw: &[String]) -> HashMap<String, String> {
238    let mut out: HashMap<String, String> = HashMap::new();
239    if let Some(defaults) = view.defaults {
240        out.extend(defaults.iter().map(|(k, v)| (k.clone(), v.clone())));
241    }
242
243    let names: Vec<String> = view
244        .args
245        .map(|a| a.iter().cloned().collect())
246        .unwrap_or_default();
247    let mut positional_idx = 0usize;
248
249    for token in raw {
250        if let Some((k, v)) = token.split_once('=') {
251            out.insert(k.to_string(), v.to_string());
252        } else if positional_idx < names.len() {
253            out.insert(names[positional_idx].clone(), token.clone());
254            positional_idx += 1;
255        }
256    }
257    out
258}
259
260/// Substitute `{{name}}` placeholders inside `command` with values from `args`.
261pub fn substitute_variables(command: &str, args: &HashMap<String, String>) -> String {
262    let mut result = command.to_string();
263    for (key, value) in args {
264        result = result.replace(&format!("{{{{{}}}}}", key), value);
265    }
266    result
267}
268
269/// Verify that every required argument (declared via `args`) has a value.
270pub fn check_required_args(
271    script_name: &str,
272    view: &ScriptView<'_>,
273    resolved: &HashMap<String, String>,
274) -> Result<(), CargoScriptError> {
275    if let Some(arg_names) = view.args {
276        for name in arg_names {
277            if !resolved.contains_key(name) {
278                return Err(CargoScriptError::MissingScriptArgument {
279                    script_name: script_name.to_string(),
280                    argument: name.clone(),
281                });
282            }
283        }
284    }
285    Ok(())
286}
287
288// ---------------------------------------------------------------------------
289// Top-level run_script
290// ---------------------------------------------------------------------------
291
292/// Run a script by name with the legacy 7-argument signature. Kept as a thin
293/// wrapper around the new options-based API for backward compatibility with
294/// any external callers.
295pub fn run_script(
296    scripts: &Scripts,
297    script_name: &str,
298    env_overrides: Vec<String>,
299    dry_run: bool,
300    quiet: bool,
301    verbose: bool,
302    show_metrics: bool,
303) -> Result<(), CargoScriptError> {
304    let opts = RunOptions {
305        env_overrides,
306        dry_run,
307        quiet,
308        verbose,
309        show_metrics,
310        ..RunOptions::default()
311    };
312    run_script_with_options(scripts, script_name, &opts).map(|_| ())
313}
314
315/// Run a script with full execution options. Returns the structured
316/// [`ExecutionResult`] which is useful for JSON output and for tests.
317pub fn run_script_with_options(
318    scripts: &Scripts,
319    script_name: &str,
320    opts: &RunOptions,
321) -> Result<ExecutionResult, CargoScriptError> {
322    if opts.dry_run {
323        if !opts.quiet && !opts.json_output {
324            println!("{}", "DRY-RUN MODE: Preview of what would be executed".bold().yellow());
325            println!("{}\n", "=".repeat(80).yellow());
326        }
327        dry_run_script(scripts, script_name, opts.env_overrides.clone(), 0, opts.quiet, opts.verbose)?;
328        if !opts.quiet && !opts.json_output {
329            println!("\n{}", "No commands were actually executed.".italic().green());
330        }
331        return Ok(ExecutionResult::new(script_name));
332    }
333
334    // Workspace dispatch: when the script (or CLI) requests a workspace mode
335    // other than `Root`, hand off to the workspace executor.
336    if !opts.no_workspace {
337        let mode = opts.workspace_override.or_else(|| {
338            scripts
339                .scripts
340                .get(script_name)
341                .and_then(view)
342                .and_then(|v| v.workspace)
343        });
344        if matches!(mode, Some(WorkspaceMode::All) | Some(WorkspaceMode::Parallel)) {
345            return crate::commands::workspace::run_in_workspace(
346                scripts,
347                script_name,
348                mode.unwrap(),
349                opts,
350            );
351        }
352    }
353
354    let script_durations = Arc::new(Mutex::new(HashMap::new()));
355    let result = run_script_with_level(
356        scripts,
357        script_name,
358        opts.env_overrides.clone(),
359        0,
360        script_durations.clone(),
361        opts.quiet,
362        opts.verbose,
363        &opts.script_args,
364    )?;
365
366    if opts.show_metrics && !opts.quiet && !opts.json_output {
367        let durations = script_durations.lock().unwrap();
368        if !durations.is_empty() {
369            let total_duration: Duration = durations.values().cloned().sum();
370            println!("\n");
371            println!("{}", "Scripts Performance".bold().yellow());
372            println!("{}", "-".repeat(80).yellow());
373            for (script, duration) in durations.iter() {
374                println!("āœ”ļø  Script: {:<25}  šŸ•’ Running time: {:.2?}", script.green(), duration);
375            }
376            println!("\nšŸ•’ Total running time: {:.2?}", total_duration);
377        }
378    }
379
380    if opts.json_output {
381        crate::output::json::print_execution_result(&result);
382    }
383
384    Ok(result)
385}
386
387// ---------------------------------------------------------------------------
388// Recursive script execution
389// ---------------------------------------------------------------------------
390
391/// The main recursive executor. Handles includes, hooks, parameters, cargo
392/// scripts and regular shell commands.
393fn run_script_with_level(
394    scripts: &Scripts,
395    script_name: &str,
396    env_overrides: Vec<String>,
397    level: usize,
398    script_durations: Arc<Mutex<HashMap<String, Duration>>>,
399    quiet: bool,
400    verbose: bool,
401    script_args: &[String],
402) -> Result<ExecutionResult, CargoScriptError> {
403    let mut env_vars = scripts.global_env.clone().unwrap_or_default();
404    let indent = "  ".repeat(level);
405    let script_start_time = Instant::now();
406    let mut result = ExecutionResult::new(script_name);
407
408    let script = scripts.scripts.get(script_name).ok_or_else(|| {
409        let available_scripts: Vec<String> = scripts.scripts.keys().cloned().collect();
410        CargoScriptError::ScriptNotFound {
411            script_name: script_name.to_string(),
412            available_scripts,
413        }
414    })?;
415
416    match script {
417        Script::Default(cmd) => {
418            // Backward-compatible behaviour, plus auto-detection of cargo
419            // script files (any command literally pointing at an existing
420            // `.rs` file is executed via cargo-script).
421            if !quiet {
422                let msg = format!(
423                    "{}{}  {}: [ {} ]",
424                    indent,
425                    symbols::other_symbol::CHECK_MARK.glyph,
426                    "Running script".green(),
427                    script_name
428                );
429                println!("{}\n", msg);
430            }
431            let final_env = get_final_env(&env_vars, &env_overrides);
432            apply_env_vars(&env_vars, &env_overrides);
433
434            let trimmed = cmd.trim();
435            if is_cargo_script_path(trimmed) {
436                result.command = Some(trimmed.to_string());
437                crate::commands::cargo_script::execute_cargo_script(
438                    script_name,
439                    trimmed,
440                    &[],
441                    &final_env,
442                )?;
443            } else {
444                result.command = Some(cmd.clone());
445                execute_command(script_name, None, cmd, None, &final_env)?;
446            }
447        }
448        Script::Inline { .. } | Script::CILike { .. } => {
449            let v = view(script).expect("non-default scripts have a view");
450
451            if let Err(e) = check_requirements(
452                v.requires.map(|r| r.as_slice()).unwrap_or(&[]),
453                v.toolchain,
454            ) {
455                return Err(e);
456            }
457
458            // Resolve parameters early so they apply uniformly.
459            let resolved_args = parse_script_args(&v, script_args);
460            check_required_args(script_name, &v, &resolved_args)?;
461
462            // Always show description unless quiet.
463            let description = v.info.as_ref().map(|desc| {
464                format!(
465                    "{}  {}: {}",
466                    emoji::objects::book_paper::BOOKMARK_TABS.glyph,
467                    "Description".green(),
468                    desc
469                )
470            });
471
472            // -------- pre hooks --------
473            if let Some(pre_hooks) = v.pre {
474                for hook in pre_hooks {
475                    let hook_res = run_script_with_level(
476                        scripts,
477                        hook,
478                        env_overrides.clone(),
479                        level + 1,
480                        script_durations.clone(),
481                        quiet,
482                        verbose,
483                        &[],
484                    )
485                    .map_err(|e| CargoScriptError::HookFailed {
486                        hook_name: hook.clone(),
487                        script_name: script_name.to_string(),
488                        reason: e.to_string(),
489                    })?;
490                    result.hooks.push(hook_res);
491                }
492            }
493
494            // -------- includes --------
495            if let Some(include_scripts) = v.include {
496                if !quiet {
497                    let desc_str = description.as_deref().unwrap_or("");
498                    let msg = format!(
499                        "{}{}  {}: [ {} ]{}",
500                        indent,
501                        symbols::other_symbol::CHECK_MARK.glyph,
502                        "Running include script".green(),
503                        script_name,
504                        if desc_str.is_empty() { String::new() } else { format!("  {}", desc_str) }
505                    );
506                    println!("{}\n", msg);
507                }
508                for include_script in include_scripts {
509                    let inc_res = run_script_with_level(
510                        scripts,
511                        include_script,
512                        env_overrides.clone(),
513                        level + 1,
514                        script_durations.clone(),
515                        quiet,
516                        verbose,
517                        &[],
518                    )?;
519                    result.includes.push(inc_res);
520                }
521            }
522
523            // Determine env for the main command
524            if let Some(script_env) = v.env {
525                env_vars.extend(script_env.clone());
526            }
527            let final_env = get_final_env(&env_vars, &env_overrides);
528            apply_env_vars(&env_vars, &env_overrides);
529
530            // -------- main command / cargo-script --------
531            let main_outcome: Result<(), CargoScriptError> = if let Some(path) = v.script_file {
532                if !quiet {
533                    let desc_str = description.as_deref().unwrap_or("");
534                    println!(
535                        "{}{}  {}: [ {} ]{}",
536                        indent,
537                        symbols::other_symbol::CHECK_MARK.glyph,
538                        "Running cargo script".green(),
539                        script_name,
540                        if desc_str.is_empty() { String::new() } else { format!("  {}", desc_str) }
541                    );
542                    println!();
543                }
544                result.command = Some(path.clone());
545                let extra_args: Vec<String> = script_args.to_vec();
546                crate::commands::cargo_script::execute_cargo_script(
547                    script_name,
548                    path,
549                    &extra_args,
550                    &final_env,
551                )
552            } else if let Some(cmd) = v.command {
553                if !quiet {
554                    let desc_str = description.as_deref().unwrap_or("");
555                    let msg = format!(
556                        "{}{}  {}: [ {} ]{}",
557                        indent,
558                        symbols::other_symbol::CHECK_MARK.glyph,
559                        "Running script".green(),
560                        script_name,
561                        if desc_str.is_empty() { String::new() } else { format!("  {}", desc_str) }
562                    );
563                    println!("{}\n", msg);
564                }
565
566                let cmd_substituted = substitute_variables(cmd, &resolved_args);
567                let trimmed = cmd_substituted.trim();
568                result.command = Some(cmd_substituted.clone());
569
570                if is_cargo_script_path(trimmed) {
571                    crate::commands::cargo_script::execute_cargo_script(
572                        script_name,
573                        trimmed,
574                        &[],
575                        &final_env,
576                    )
577                } else {
578                    execute_command(
579                        script_name,
580                        v.interpreter.map(|s| s.as_str()),
581                        &cmd_substituted,
582                        v.toolchain.map(|s| s.as_str()),
583                        &final_env,
584                    )
585                }
586            } else {
587                // No command and no script_file - includes-only is fine.
588                Ok(())
589            };
590
591            // -------- post / on_success / on_failure hooks --------
592            // Post hooks always run (even on failure) for cleanup parity with
593            // tools like make / npm scripts.
594            let conditional_hooks = match &main_outcome {
595                Ok(_) => v.on_success,
596                Err(_) => v.on_failure,
597            };
598
599            if let Some(hooks) = conditional_hooks {
600                for hook in hooks {
601                    let hook_res = run_script_with_level(
602                        scripts,
603                        hook,
604                        env_overrides.clone(),
605                        level + 1,
606                        script_durations.clone(),
607                        quiet,
608                        verbose,
609                        &[],
610                    );
611                    if let Ok(r) = hook_res {
612                        result.hooks.push(r);
613                    }
614                }
615            }
616
617            if let Some(post_hooks) = v.post {
618                for hook in post_hooks {
619                    if let Ok(r) = run_script_with_level(
620                        scripts,
621                        hook,
622                        env_overrides.clone(),
623                        level + 1,
624                        script_durations.clone(),
625                        quiet,
626                        verbose,
627                        &[],
628                    ) {
629                        result.hooks.push(r);
630                    }
631                }
632            }
633
634            main_outcome?;
635        }
636    }
637
638    let script_duration = script_start_time.elapsed();
639    result.duration_ms = script_duration.as_millis();
640    if level > 0
641        || matches!(
642            scripts.scripts.get(script_name),
643            Some(Script::Default(_))
644                | Some(Script::Inline { command: Some(_), .. })
645                | Some(Script::CILike { command: Some(_), .. })
646        )
647    {
648        script_durations
649            .lock()
650            .unwrap()
651            .insert(script_name.to_string(), script_duration);
652    }
653
654    Ok(result)
655}
656
657// ---------------------------------------------------------------------------
658// Helpers (env, exec, dry-run, requirements, interactive)
659// ---------------------------------------------------------------------------
660
661/// Detect whether `cmd` should be treated as a cargo script invocation.
662/// A command is a cargo script when it points at a file ending in `.rs` that
663/// exists on disk (we deliberately keep this strict to avoid surprises).
664pub fn is_cargo_script_path(cmd: &str) -> bool {
665    let first = cmd.split_whitespace().next().unwrap_or("");
666    first.ends_with(".rs") && std::path::Path::new(first).exists()
667}
668
669fn get_final_env(env_vars: &HashMap<String, String>, env_overrides: &[String]) -> HashMap<String, String> {
670    let mut final_env = env_vars.clone();
671    for override_str in env_overrides {
672        if let Some((key, value)) = override_str.split_once('=') {
673            final_env.insert(key.to_string(), value.to_string());
674        }
675    }
676    final_env
677}
678
679fn apply_env_vars(env_vars: &HashMap<String, String>, env_overrides: &[String]) {
680    let final_env = get_final_env(env_vars, env_overrides);
681    for (key, value) in &final_env {
682        // SAFETY: we are about to spawn a child; setting env vars in the
683        // current process is the same approach used by the original
684        // implementation. See note in the original v0.5 source.
685        unsafe {
686            env::set_var(key, value);
687        }
688    }
689}
690
691fn execute_command(
692    script_name: &str,
693    interpreter: Option<&str>,
694    command: &str,
695    toolchain: Option<&str>,
696    env_vars: &HashMap<String, String>,
697) -> Result<(), CargoScriptError> {
698    let mut cmd = if let Some(tc) = toolchain {
699        let mut command_with_toolchain = format!("cargo +{} ", tc);
700        command_with_toolchain.push_str(command);
701        let mut cmd = if cfg!(target_os = "windows") {
702            let mut c = Command::new("cmd");
703            c.args(["/C", &command_with_toolchain]);
704            c
705        } else {
706            let mut c = Command::new("sh");
707            c.arg("-c").arg(&command_with_toolchain);
708            c
709        };
710        cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
711        for (key, value) in env_vars {
712            cmd.env(key, value);
713        }
714        cmd.spawn().map_err(|e| CargoScriptError::ExecutionError {
715            script: script_name.to_string(),
716            command: command.to_string(),
717            source: e,
718        })?
719    } else {
720        spawn_with_interpreter(interpreter, command, env_vars).map_err(|e| {
721            CargoScriptError::ExecutionError {
722                script: script_name.to_string(),
723                command: command.to_string(),
724                source: e,
725            }
726        })?
727    };
728
729    let exit_status = cmd.wait().map_err(|e| CargoScriptError::ExecutionError {
730        script: script_name.to_string(),
731        command: command.to_string(),
732        source: e,
733    })?;
734
735    if !exit_status.success() {
736        let is_self_replace_attempt = cfg!(target_os = "windows")
737            && (command.contains("cargo install --path .")
738                || command.contains("cargo install --path")
739                || (command.contains("cargo install") && command.contains("--path")));
740
741        if is_self_replace_attempt {
742            return Err(CargoScriptError::WindowsSelfReplacementError {
743                script: script_name.to_string(),
744                command: command.to_string(),
745            });
746        }
747
748        return Err(CargoScriptError::ExecutionError {
749            script: script_name.to_string(),
750            command: command.to_string(),
751            source: std::io::Error::new(
752                std::io::ErrorKind::Other,
753                format!("exited with status: {}", exit_status),
754            ),
755        });
756    }
757
758    Ok(())
759}
760
761fn spawn_with_interpreter(
762    interpreter: Option<&str>,
763    command: &str,
764    env_vars: &HashMap<String, String>,
765) -> std::io::Result<std::process::Child> {
766    let mut cmd = match interpreter {
767        Some("bash") => {
768            let mut c = Command::new("bash");
769            c.arg("-c").arg(command);
770            c
771        }
772        Some("zsh") => {
773            let mut c = Command::new("zsh");
774            c.arg("-c").arg(command);
775            c
776        }
777        Some("powershell") => {
778            let mut c = Command::new("powershell");
779            c.args(["-NoProfile", "-Command", command]);
780            c
781        }
782        Some("cmd") => {
783            let mut c = Command::new("cmd");
784            c.args(["/C", command]);
785            c
786        }
787        Some(other) => {
788            let mut c = Command::new(other);
789            c.arg("-c").arg(command);
790            c
791        }
792        None => {
793            if cfg!(target_os = "windows") {
794                let mut c = Command::new("cmd");
795                c.args(["/C", command]);
796                c
797            } else {
798                let mut c = Command::new("sh");
799                c.arg("-c").arg(command);
800                c
801            }
802        }
803    };
804
805    cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
806    for (key, value) in env_vars {
807        cmd.env(key, value);
808    }
809    cmd.spawn()
810}
811
812fn dry_run_script(
813    scripts: &Scripts,
814    script_name: &str,
815    env_overrides: Vec<String>,
816    level: usize,
817    quiet: bool,
818    verbose: bool,
819) -> Result<(), CargoScriptError> {
820    let indent = "  ".repeat(level);
821    let mut env_vars = scripts.global_env.clone().unwrap_or_default();
822
823    let script = scripts.scripts.get(script_name).ok_or_else(|| {
824        let available_scripts: Vec<String> = scripts.scripts.keys().cloned().collect();
825        CargoScriptError::ScriptNotFound {
826            script_name: script_name.to_string(),
827            available_scripts,
828        }
829    })?;
830
831    match script {
832        Script::Default(cmd) => {
833            if !quiet {
834                println!(
835                    "{}{}  {}: [ {} ]",
836                    indent,
837                    "šŸ“‹".yellow(),
838                    "Would run script".cyan(),
839                    script_name.bold()
840                );
841                println!("{}    Command: {}", indent, cmd.green());
842                let final_env = get_final_env(&env_vars, &env_overrides);
843                if !final_env.is_empty() {
844                    println!("{}    Environment variables:", indent);
845                    for (key, value) in &final_env {
846                        println!("{}      {} = {}", indent, key.cyan(), value.green());
847                    }
848                }
849                if level == 0 {
850                    println!();
851                }
852            }
853        }
854        Script::Inline { .. } | Script::CILike { .. } => {
855            let v = view(script).unwrap();
856            if !quiet {
857                if verbose {
858                    if let Some(reqs) = v.requires {
859                        if !reqs.is_empty() {
860                            println!(
861                                "{}{}  {}: [ {} ]",
862                                indent,
863                                "šŸ”".yellow(),
864                                "Would check requirements".cyan(),
865                                script_name.bold()
866                            );
867                            for req in reqs {
868                                println!("{}      - {}", indent, req.green());
869                            }
870                            println!();
871                        }
872                    }
873                    if let Some(tc) = v.toolchain {
874                        println!(
875                            "{}{}  {}: {}",
876                            indent,
877                            "šŸ”§".yellow(),
878                            "Would use toolchain".cyan(),
879                            tc.bold().green()
880                        );
881                        println!();
882                    }
883                    if let Some(desc) = v.info {
884                        println!(
885                            "{}{}  {}: {}",
886                            indent,
887                            "šŸ“".yellow(),
888                            "Description".cyan(),
889                            desc.green()
890                        );
891                        println!();
892                    }
893                }
894
895                if let Some(pre) = v.pre {
896                    println!("{}{}  {}: {:?}", indent, "ā†©ļø".yellow(), "Pre hooks".cyan(), pre);
897                }
898                if let Some(post) = v.post {
899                    println!("{}{}  {}: {:?}", indent, "ā†Ŗļø".yellow(), "Post hooks".cyan(), post);
900                }
901
902                if let Some(include_scripts) = v.include {
903                    println!(
904                        "{}{}  {}: [ {} ]",
905                        indent,
906                        "šŸ“‹".yellow(),
907                        "Would run include scripts".cyan(),
908                        script_name.bold()
909                    );
910                    if let Some(desc) = v.info {
911                        println!("{}    Description: {}", indent, desc.green());
912                    }
913                    println!();
914                    for include_script in include_scripts {
915                        dry_run_script(scripts, include_script, env_overrides.clone(), level + 1, quiet, verbose)?;
916                    }
917                }
918
919                if let Some(path) = v.script_file {
920                    println!(
921                        "{}{}  {}: [ {} ] -> {}",
922                        indent,
923                        "šŸ“‹".yellow(),
924                        "Would run cargo script".cyan(),
925                        script_name.bold(),
926                        path.green(),
927                    );
928                }
929
930                if let Some(cmd) = v.command {
931                    println!(
932                        "{}{}  {}: [ {} ]",
933                        indent,
934                        "šŸ“‹".yellow(),
935                        "Would run script".cyan(),
936                        script_name.bold()
937                    );
938
939                    if let Some(interp) = v.interpreter {
940                        println!("{}    Interpreter: {}", indent, interp.green());
941                    }
942                    if let Some(tc) = v.toolchain {
943                        println!("{}    Toolchain: {}", indent, tc.green());
944                    }
945                    println!("{}    Command: {}", indent, cmd.green());
946
947                    if let Some(script_env) = v.env {
948                        env_vars.extend(script_env.clone());
949                    }
950                    let final_env = get_final_env(&env_vars, &env_overrides);
951                    if !final_env.is_empty() {
952                        println!("{}    Environment variables:", indent);
953                        for (key, value) in &final_env {
954                            println!("{}      {} = {}", indent, key.cyan(), value.green());
955                        }
956                    }
957                    if level == 0 {
958                        println!();
959                    }
960                }
961            } else if let Some(include_scripts) = v.include {
962                for include_script in include_scripts {
963                    dry_run_script(scripts, include_script, env_overrides.clone(), level + 1, quiet, verbose)?;
964                }
965            }
966        }
967    }
968
969    Ok(())
970}
971
972/// Interactive script selection using a fuzzy finder.
973pub fn interactive_select_script(scripts: &Scripts, quiet: bool) -> Result<String, CargoScriptError> {
974    if scripts.scripts.is_empty() {
975        return Err(CargoScriptError::ScriptNotFound {
976            script_name: "".to_string(),
977            available_scripts: vec![],
978        });
979    }
980
981    let mut items: Vec<(String, String)> = scripts.scripts
982        .iter()
983        .map(|(name, script)| {
984            let description = match script {
985                Script::Default(_) => "".to_string(),
986                Script::Inline { info, .. } | Script::CILike { info, .. } => {
987                    info.clone().unwrap_or_else(|| "".to_string())
988                }
989            };
990            (name.clone(), description)
991        })
992        .collect();
993
994    items.sort_by(|a, b| a.0.cmp(&b.0));
995
996    let display_items: Vec<String> = items
997        .iter()
998        .map(|(name, desc)| {
999            if desc.is_empty() {
1000                name.clone()
1001            } else {
1002                format!("{} - {}", name, desc)
1003            }
1004        })
1005        .collect();
1006
1007    if !quiet {
1008        println!("{}", "Select a script to run:".cyan().bold());
1009        println!();
1010    }
1011
1012    let selection = FuzzySelect::new()
1013        .with_prompt("Script")
1014        .items(&display_items)
1015        .default(0)
1016        .interact()
1017        .map_err(|e| CargoScriptError::ExecutionError {
1018            script: "interactive".to_string(),
1019            command: "fuzzy_select".to_string(),
1020            source: std::io::Error::new(std::io::ErrorKind::Other, format!("Interactive selection failed: {}", e)),
1021        })?;
1022
1023    Ok(items[selection].0.clone())
1024}
1025
1026fn check_requirements(requires: &[String], toolchain: Option<&String>) -> Result<(), CargoScriptError> {
1027    for req in requires {
1028        if let Some((tool, version)) = req.split_once(' ') {
1029            let output = Command::new(tool)
1030                .arg("--version")
1031                .output()
1032                .map_err(|_| create_tool_not_found_error(tool, Some(version)))?;
1033            let output_str = String::from_utf8_lossy(&output.stdout);
1034
1035            if !output_str.contains(version) {
1036                return Err(create_tool_not_found_error(tool, Some(version)));
1037            }
1038        } else {
1039            Command::new(req)
1040                .output()
1041                .map_err(|_| create_tool_not_found_error(req, None))?;
1042        }
1043    }
1044
1045    if let Some(tc) = toolchain {
1046        let output = Command::new("rustup")
1047            .arg("toolchain")
1048            .arg("list")
1049            .output()
1050            .map_err(|_| create_tool_not_found_error("rustup", None))?;
1051        let output_str = String::from_utf8_lossy(&output.stdout);
1052
1053        if !output_str.contains(tc) {
1054            return Err(create_toolchain_not_found_error(tc));
1055        }
1056    }
1057
1058    Ok(())
1059}