Skip to main content

cargo_run/commands/
cargo_script.rs

1//! Integration with Cargo's single-file packages (RFC 3502, "cargo script").
2//!
3//! On stable Rust 1.93+ (when `cargo script` lands), invocation is direct:
4//!     cargo /path/to/script.rs <args...>
5//!
6//! On older toolchains, we transparently fall back to:
7//!     cargo +nightly -Zscript /path/to/script.rs <args...>
8//!
9//! Both forms support both the comment-frontmatter and the
10//! `---cargo` ... `---` frontmatter styles.
11
12use std::collections::HashMap;
13use std::process::{Command, Stdio};
14use std::sync::OnceLock;
15
16use crate::error::CargoScriptError;
17
18/// Cached detection result. We probe `cargo` once per process.
19static SUPPORTS_STABLE: OnceLock<bool> = OnceLock::new();
20
21/// Detect whether the host's stable cargo already understands single-file
22/// packages (RFC 3502).
23///
24/// We probe `cargo script --version`. There are three cases:
25///
26/// 1. **RFC 3502 stable Cargo** — Cargo handles `script` itself and prints
27///    its own version line, e.g. `cargo 1.96.0 (f2d3ce0bd 2026-03-21)`.
28/// 2. **Third-party `cargo-script` on PATH** (including older versions of
29///    *this* tool) — Cargo dispatches to the external binary, which prints
30///    its own banner, e.g. `cargo-script 0.5.2`. This is *not* RFC 3502
31///    and routing `.rs` files through it would fail.
32/// 3. **No `script` subcommand at all** — exit non-zero.
33///
34/// We accept only case 1 by requiring the first line of stdout to look like
35/// Cargo's own version line: starts with `cargo` followed by whitespace and
36/// a digit (so `cargo-script 0.5.2`, `cargo-make 0.37.0`, etc. are
37/// rejected).
38pub fn stable_cargo_script_supported() -> bool {
39    *SUPPORTS_STABLE.get_or_init(|| {
40        let out = Command::new("cargo")
41            .args(["script", "--version"])
42            .stderr(Stdio::null())
43            .output();
44        match out {
45            Ok(o) if o.status.success() => {
46                let stdout = String::from_utf8_lossy(&o.stdout);
47                stdout
48                    .lines()
49                    .next()
50                    .map(is_builtin_cargo_version_line)
51                    .unwrap_or(false)
52            }
53            _ => false,
54        }
55    })
56}
57
58/// Returns true when `line` looks like Cargo's own `--version` output
59/// (e.g. `"cargo 1.96.0 (abc123 2026-04-01)"`), as opposed to a third-party
60/// `cargo-<something>` subcommand banner.
61pub fn is_builtin_cargo_version_line(line: &str) -> bool {
62    let trimmed = line.trim();
63    let mut parts = trimmed.splitn(2, char::is_whitespace);
64    let head = parts.next().unwrap_or("");
65    let rest = parts.next().unwrap_or("").trim_start();
66    head == "cargo" && rest.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false)
67}
68
69/// Returns true when `cargo` is callable at all.
70pub fn cargo_available() -> bool {
71    Command::new("cargo")
72        .arg("--version")
73        .stdout(Stdio::null())
74        .stderr(Stdio::null())
75        .status()
76        .map(|s| s.success())
77        .unwrap_or(false)
78}
79
80/// Returns true when `rustup` reports a `nightly` toolchain.
81pub fn nightly_available() -> bool {
82    let out = Command::new("rustup")
83        .args(["toolchain", "list"])
84        .output();
85    match out {
86        Ok(o) => String::from_utf8_lossy(&o.stdout).contains("nightly"),
87        Err(_) => false,
88    }
89}
90
91/// Which cargo invocation strategy to use for an `.rs` script file.
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93pub enum CargoScriptInvocation {
94    /// Stable cargo with RFC 3502: `cargo script <path> [-- <args>]`
95    Stable,
96    /// Nightly fallback: `cargo +nightly -Zscript <path> [-- <args>]`
97    Nightly,
98}
99
100/// Build the argv for a `.rs` cargo-script invocation.
101///
102/// Pulled out of [`execute_cargo_script`] so it can be unit-tested without
103/// requiring a nightly toolchain or a stable cargo with RFC 3502 enabled.
104///
105/// Returns `(program, args)`. `args` already includes the `--` separator
106/// and forwarded `extra_args` when present.
107pub fn build_cargo_script_argv(
108    invocation: CargoScriptInvocation,
109    path: &str,
110    extra_args: &[String],
111) -> (&'static str, Vec<String>) {
112    let mut args: Vec<String> = match invocation {
113        CargoScriptInvocation::Stable => vec!["script".into(), path.to_string()],
114        CargoScriptInvocation::Nightly => {
115            vec!["+nightly".into(), "-Zscript".into(), path.to_string()]
116        }
117    };
118    if !extra_args.is_empty() {
119        args.push("--".into());
120        args.extend(extra_args.iter().cloned());
121    }
122    ("cargo", args)
123}
124
125/// Execute the cargo script located at `path`, forwarding `extra_args` and
126/// the resolved environment.
127///
128/// `script_name` is used purely for error reporting.
129pub fn execute_cargo_script(
130    script_name: &str,
131    path: &str,
132    extra_args: &[String],
133    env_vars: &HashMap<String, String>,
134) -> Result<(), CargoScriptError> {
135    if !cargo_available() {
136        return Err(CargoScriptError::CargoScriptNotAvailable {
137            suggestion: "  Install Rust toolchain from https://rustup.rs/".to_string(),
138        });
139    }
140
141    let invocation = if stable_cargo_script_supported() {
142        CargoScriptInvocation::Stable
143    } else if nightly_available() {
144        CargoScriptInvocation::Nightly
145    } else {
146        return Err(CargoScriptError::CargoScriptNotAvailable {
147            suggestion:
148                "  cargo script (RFC 3502) requires either a stable cargo with the \
149                 feature stabilized, or `rustup toolchain install nightly`."
150                    .to_string(),
151        });
152    };
153
154    let (program, full_args) = build_cargo_script_argv(invocation, path, extra_args);
155    // For error messages, keep the base invocation (without forwarded args).
156    let base_args: Vec<String> = match invocation {
157        CargoScriptInvocation::Stable => vec!["script".into(), path.to_string()],
158        CargoScriptInvocation::Nightly => {
159            vec!["+nightly".into(), "-Zscript".into(), path.to_string()]
160        }
161    };
162
163    let mut cmd = Command::new(program);
164    cmd.args(&full_args);
165    cmd.stdout(Stdio::inherit()).stderr(Stdio::inherit());
166    for (k, v) in env_vars {
167        cmd.env(k, v);
168    }
169
170    let mut child = cmd
171        .spawn()
172        .map_err(|e| CargoScriptError::ExecutionError {
173            script: script_name.to_string(),
174            command: format!("{} {}", program, base_args.join(" ")),
175            source: e,
176        })?;
177
178    let status = child.wait().map_err(|e| CargoScriptError::ExecutionError {
179        script: script_name.to_string(),
180        command: format!("{} {}", program, base_args.join(" ")),
181        source: e,
182    })?;
183
184    if !status.success() {
185        return Err(CargoScriptError::ExecutionError {
186            script: script_name.to_string(),
187            command: format!("{} {}", program, base_args.join(" ")),
188            source: std::io::Error::new(
189                std::io::ErrorKind::Other,
190                format!("cargo script exited with status: {}", status),
191            ),
192        });
193    }
194
195    Ok(())
196}
197
198/// Best-effort heuristic: does `path` look like a cargo script file?
199pub fn looks_like_cargo_script(path: &str) -> bool {
200    path.ends_with(".rs") && std::path::Path::new(path).exists()
201}