Skip to main content

kitchen_services/
env.rs

1//! A project's environments for its scripts: what Python runs them, with which packages, and which
2//! Rust toolchain builds them. The project folder holds them, so a project (and a pipeline built
3//! in it) runs the same on another computer:
4//!
5//! ```text
6//! scripts/
7//!   pyproject.toml  uv.lock  .venv/               Python: the packages, locked; the environment
8//!   Cargo.toml  Cargo.lock  rust-toolchain.toml   Rust: the crates, locked; the toolchain
9//! ```
10//!
11//! - **Python** runs with the environment's own interpreter (`.venv/bin/python`): the project's
12//!   `.venv`, else the one activated (`$VIRTUAL_ENV`), else the app's default environment. uv
13//!   makes and syncs it from `pyproject.toml` and `uv.lock` ([`sync_python`]); the lock, not the
14//!   `.venv`, is what travels (a `.venv` names its base interpreter, so it is made again elsewhere).
15//! - **Rust** has no environment to activate: `Cargo.toml` and `Cargo.lock` are the crates, and
16//!   `rust-toolchain.toml` pins the toolchain (rustup reads it from the folder Cargo runs in).
17//!   [`ensure_rust`] writes them; builds share one target folder.
18
19use std::path::{Path, PathBuf};
20use std::process::Command;
21
22/// Where a Python environment comes from.
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum PythonSource {
25    /// The project's own (`scripts/.venv`).
26    Project,
27    /// The one activated in the shell the app started from (`$VIRTUAL_ENV`).
28    Active,
29    /// The app's default environment (for projects that have none).
30    Default,
31}
32
33impl PythonSource {
34    /// What Settings calls it.
35    pub fn title(self) -> &'static str {
36        match self {
37            PythonSource::Project => "the project's",
38            PythonSource::Active => "the active one ($VIRTUAL_ENV)",
39            PythonSource::Default => "the app's default",
40        }
41    }
42}
43
44/// A Python environment (a venv).
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct PythonEnv {
47    /// The environment's folder (`.venv`).
48    pub root: PathBuf,
49    /// Its interpreter.
50    pub python: PathBuf,
51    /// Where it comes from.
52    pub source: PythonSource,
53}
54
55/// The interpreter inside the venv at `root`, if there is one.
56pub fn venv_python(root: &Path) -> Option<PathBuf> {
57    let candidates: &[&str] = if cfg!(windows) { &["Scripts/python.exe"] } else { &["bin/python", "bin/python3"] };
58    candidates.iter().map(|c| root.join(c)).find(|p| p.exists())
59}
60
61impl PythonEnv {
62    /// The environment for `scripts` (a project's scripts folder; `None` without a project), else
63    /// the active one, else the default one in `default_root` (when it was made).
64    pub fn find(scripts: Option<&Path>, default_root: &Path) -> Option<PythonEnv> {
65        let at = |root: PathBuf, source| venv_python(&root).map(|python| PythonEnv { root, python, source });
66        scripts
67            .and_then(|d| at(d.join(".venv"), PythonSource::Project))
68            .or_else(|| {
69                std::env::var_os("VIRTUAL_ENV")
70                    .filter(|v| !v.is_empty())
71                    .and_then(|v| at(PathBuf::from(v), PythonSource::Active))
72            })
73            .or_else(|| at(default_root.to_path_buf(), PythonSource::Default))
74    }
75
76    /// A command running this environment's Python (as an activated venv would: `VIRTUAL_ENV`
77    /// set, its `bin` first on the `PATH`).
78    pub fn command(&self) -> Command {
79        let mut c = Command::new(&self.python);
80        c.env("VIRTUAL_ENV", &self.root);
81        if let Some(bin) = self.python.parent() {
82            let path = std::env::var_os("PATH").unwrap_or_default();
83            let joined = std::env::join_paths(std::iter::once(bin.to_path_buf()).chain(std::env::split_paths(&path)))
84                .unwrap_or(path);
85            c.env("PATH", joined);
86        }
87        c.env_remove("PYTHONHOME");
88        c
89    }
90
91    /// Its Python version (`3.13.1`), from `pyvenv.cfg` (no process started).
92    pub fn version(&self) -> Option<String> {
93        let cfg = std::fs::read_to_string(self.root.join("pyvenv.cfg")).ok()?;
94        cfg.lines().find_map(|l| {
95            let (k, v) = l.split_once('=')?;
96            matches!(k.trim(), "version" | "version_info").then(|| v.trim().to_string())
97        })
98    }
99
100    /// The packages installed (their names, sorted), from the `*.dist-info` folders.
101    pub fn packages(&self) -> Vec<String> {
102        let lib = if cfg!(windows) {
103            vec![self.root.join("Lib").join("site-packages")]
104        } else {
105            std::fs::read_dir(self.root.join("lib"))
106                .into_iter()
107                .flatten()
108                .flatten()
109                .map(|e| e.path().join("site-packages"))
110                .collect()
111        };
112        let mut out: Vec<String> = lib
113            .iter()
114            .flat_map(|d| std::fs::read_dir(d).into_iter().flatten().flatten())
115            .filter_map(|e| {
116                let name = e.file_name().to_string_lossy().into_owned();
117                let stem = name.strip_suffix(".dist-info")?;
118                Some(stem.rsplit_once('-').map_or(stem, |(n, _)| n).replace('_', "-").to_lowercase())
119            })
120            .collect();
121        out.sort();
122        out.dedup();
123        out
124    }
125}
126
127/// uv, if used: `$UV`, then the Settings' choice (found on the `PATH` or where its installer puts
128/// it, another path, or off; [`crate::python_tools`]).
129pub fn uv() -> Option<PathBuf> {
130    crate::python_tools::find(crate::python_tools::PyTool::Uv)
131}
132
133/// The `pyproject.toml` written for a new environment: a project of scripts, not a package.
134fn pyproject(name: &str, packages: &[&str]) -> String {
135    let deps = packages.iter().map(|p| format!("    \"{p}\",")).collect::<Vec<_>>().join("\n");
136    format!(
137        "[project]\nname = \"{name}\"\nversion = \"0.0.0\"\ndescription = \"The packages this project's Python scripts use\"\nrequires-python = \">=3.10\"\ndependencies = [\n{deps}\n]\n\n[tool.uv]\npackage = false\n"
138    )
139}
140
141fn run(cmd: &mut Command, what: &str) -> Result<String, String> {
142    let out = cmd.output().map_err(|e| format!("{what}: {e}"))?;
143    let text =
144        format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)).trim().to_string();
145    if out.status.success() { Ok(text) } else { Err(format!("{what} failed: {text}")) }
146}
147
148/// Makes or updates the Python environment in `dir` with uv: writes `pyproject.toml` first when
149/// there is none (with `packages`, the app's own needs such as NumPy), then `uv sync` (the
150/// `.venv` matching `uv.lock`, made when missing). Returns uv's report.
151pub fn sync_python(dir: &Path, name: &str, packages: &[&str]) -> Result<String, String> {
152    let uv =
153        uv().ok_or("uv is not installed (https://docs.astral.sh/uv): it makes and syncs the project's environment")?;
154    std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
155    let project = dir.join("pyproject.toml");
156    if !project.exists() {
157        std::fs::write(&project, pyproject(name, packages)).map_err(|e| format!("{}: {e}", project.display()))?;
158    }
159    run(Command::new(&uv).arg("sync").arg("--project").arg(dir).env_remove("VIRTUAL_ENV"), "uv sync")
160}
161
162/// Adds `packages` to the environment in `dir` (`uv add`: `pyproject.toml`, `uv.lock` and the
163/// `.venv` together).
164pub fn add_python(dir: &Path, packages: &[String]) -> Result<String, String> {
165    let uv = uv().ok_or("uv is not installed")?;
166    run(Command::new(&uv).arg("add").arg("--project").arg(dir).args(packages).env_remove("VIRTUAL_ENV"), "uv add")
167}
168
169/// The Rust toolchain a folder pins (`channel` of its `rust-toolchain.toml`).
170pub fn rust_toolchain(dir: &Path) -> Option<String> {
171    let text = std::fs::read_to_string(dir.join("rust-toolchain.toml")).ok()?;
172    text.lines().find_map(|l| {
173        let (k, v) = l.split_once('=')?;
174        (k.trim() == "channel").then(|| v.trim().trim_matches('"').to_string())
175    })
176}
177
178/// The version of the Rust compiler found (`1.95.0`), the one a new pin names.
179pub fn rustc_version() -> Option<String> {
180    let out = Command::new("rustc").arg("--version").output().ok()?;
181    String::from_utf8_lossy(&out.stdout).split_whitespace().nth(1).map(str::to_string)
182}
183
184/// Makes `dir` a Rust environment when it is not one yet: a Cargo workspace whose members are the
185/// scripts' crates (`members`, globs allowed), and `rust-toolchain.toml` pinning the compiler found
186/// now. The lock (`Cargo.lock`) is written by the first build. Returns the toolchain pinned.
187pub fn ensure_rust(dir: &Path, members: &[&str]) -> Result<Option<String>, String> {
188    std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
189    let manifest = dir.join("Cargo.toml");
190    if !manifest.exists() {
191        let list = members.iter().map(|m| format!("\"{m}\"")).collect::<Vec<_>>().join(", ");
192        std::fs::write(&manifest, format!("# The crates this project's Rust scripts use; Cargo.lock beside it locks them.\n[workspace]\nresolver = \"3\"\nmembers = [{list}]\n")).map_err(|e| format!("{}: {e}", manifest.display()))?;
193    }
194    let pin = dir.join("rust-toolchain.toml");
195    if !pin.exists()
196        && let Some(v) = rustc_version()
197    {
198        std::fs::write(&pin, format!("# The compiler this project's Rust scripts are built with (rustup reads it).\n[toolchain]\nchannel = \"{v}\"\n")).map_err(|e| format!("{}: {e}", pin.display()))?;
199    }
200    Ok(rust_toolchain(dir))
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206
207    fn temp(name: &str) -> PathBuf {
208        let d = std::env::temp_dir().join(format!("kitchen-env-{name}-{}", std::process::id()));
209        let _ = std::fs::remove_dir_all(&d);
210        std::fs::create_dir_all(&d).unwrap();
211        d
212    }
213
214    /// A venv laid out by hand: found in the project, its version and packages read without
215    /// running anything.
216    #[test]
217    fn a_project_venv_is_found_and_read() {
218        let d = temp("venv");
219        let venv = d.join(".venv");
220        let bin = if cfg!(windows) { venv.join("Scripts") } else { venv.join("bin") };
221        std::fs::create_dir_all(&bin).unwrap();
222        std::fs::write(bin.join(if cfg!(windows) { "python.exe" } else { "python" }), "").unwrap();
223        std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\nversion_info = 3.13.1\n").unwrap();
224        let site =
225            if cfg!(windows) { venv.join("Lib/site-packages") } else { venv.join("lib/python3.13/site-packages") };
226        std::fs::create_dir_all(site.join("numpy-2.3.1.dist-info")).unwrap();
227        std::fs::create_dir_all(site.join("scikit_image-0.25.2.dist-info")).unwrap();
228        let env = PythonEnv::find(Some(&d), &d.join("default")).expect("the project's venv");
229        assert_eq!(env.source, PythonSource::Project);
230        assert_eq!(env.version().as_deref(), Some("3.13.1"));
231        assert_eq!(env.packages(), vec!["numpy".to_string(), "scikit-image".to_string()]);
232        std::fs::remove_dir_all(&d).ok();
233    }
234
235    /// A Rust environment: a workspace manifest and the toolchain pinned, written once.
236    #[test]
237    fn a_rust_environment_is_written_once() {
238        let d = temp("rust");
239        let pinned = ensure_rust(&d, &["build/*"]).unwrap();
240        let manifest = std::fs::read_to_string(d.join("Cargo.toml")).unwrap();
241        assert!(manifest.contains("[workspace]") && manifest.contains("\"build/*\""));
242        if let Some(v) = rustc_version() {
243            assert_eq!(pinned.as_deref(), Some(v.as_str()));
244        }
245        std::fs::write(d.join("rust-toolchain.toml"), "[toolchain]\nchannel = \"1.90.0\"\n").unwrap();
246        ensure_rust(&d, &["build/*"]).unwrap();
247        assert_eq!(rust_toolchain(&d).as_deref(), Some("1.90.0"), "an existing pin stays");
248        std::fs::remove_dir_all(&d).ok();
249    }
250
251    #[test]
252    fn a_new_pyproject_is_a_project_of_scripts() {
253        let p = pyproject("case-12-scripts", &["numpy"]);
254        assert!(p.contains("name = \"case-12-scripts\"") && p.contains("\"numpy\",") && p.contains("package = false"));
255    }
256}