1use std::path::{Path, PathBuf};
20use std::process::Command;
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum PythonSource {
25 Project,
27 Active,
29 Default,
31}
32
33impl PythonSource {
34 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#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct PythonEnv {
47 pub root: PathBuf,
49 pub python: PathBuf,
51 pub source: PythonSource,
53}
54
55pub 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 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 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 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 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
127pub fn uv() -> Option<PathBuf> {
129 if let Some(p) = std::env::var_os("UV").map(PathBuf::from).filter(|p| p.is_file()) {
130 return Some(p);
131 }
132 let exe = if cfg!(windows) { "uv.exe" } else { "uv" };
133 let on_path =
134 std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join(exe)).find(|c| c.is_file()));
135 on_path.or_else(|| {
136 let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)?;
137 [home.join(".local/bin").join(exe), home.join(".cargo/bin").join(exe)].into_iter().find(|c| c.is_file())
138 })
139}
140
141fn pyproject(name: &str, packages: &[&str]) -> String {
143 let deps = packages.iter().map(|p| format!(" \"{p}\",")).collect::<Vec<_>>().join("\n");
144 format!(
145 "[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"
146 )
147}
148
149fn run(cmd: &mut Command, what: &str) -> Result<String, String> {
150 let out = cmd.output().map_err(|e| format!("{what}: {e}"))?;
151 let text =
152 format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)).trim().to_string();
153 if out.status.success() { Ok(text) } else { Err(format!("{what} failed: {text}")) }
154}
155
156pub fn sync_python(dir: &Path, name: &str, packages: &[&str]) -> Result<String, String> {
160 let uv =
161 uv().ok_or("uv is not installed (https://docs.astral.sh/uv): it makes and syncs the project's environment")?;
162 std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
163 let project = dir.join("pyproject.toml");
164 if !project.exists() {
165 std::fs::write(&project, pyproject(name, packages)).map_err(|e| format!("{}: {e}", project.display()))?;
166 }
167 run(Command::new(&uv).arg("sync").arg("--project").arg(dir).env_remove("VIRTUAL_ENV"), "uv sync")
168}
169
170pub fn add_python(dir: &Path, packages: &[String]) -> Result<String, String> {
173 let uv = uv().ok_or("uv is not installed")?;
174 run(Command::new(&uv).arg("add").arg("--project").arg(dir).args(packages).env_remove("VIRTUAL_ENV"), "uv add")
175}
176
177pub fn rust_toolchain(dir: &Path) -> Option<String> {
179 let text = std::fs::read_to_string(dir.join("rust-toolchain.toml")).ok()?;
180 text.lines().find_map(|l| {
181 let (k, v) = l.split_once('=')?;
182 (k.trim() == "channel").then(|| v.trim().trim_matches('"').to_string())
183 })
184}
185
186pub fn rustc_version() -> Option<String> {
188 let out = Command::new("rustc").arg("--version").output().ok()?;
189 String::from_utf8_lossy(&out.stdout).split_whitespace().nth(1).map(str::to_string)
190}
191
192pub fn ensure_rust(dir: &Path, members: &[&str]) -> Result<Option<String>, String> {
196 std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
197 let manifest = dir.join("Cargo.toml");
198 if !manifest.exists() {
199 let list = members.iter().map(|m| format!("\"{m}\"")).collect::<Vec<_>>().join(", ");
200 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()))?;
201 }
202 let pin = dir.join("rust-toolchain.toml");
203 if !pin.exists()
204 && let Some(v) = rustc_version()
205 {
206 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()))?;
207 }
208 Ok(rust_toolchain(dir))
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 fn temp(name: &str) -> PathBuf {
216 let d = std::env::temp_dir().join(format!("kitchen-env-{name}-{}", std::process::id()));
217 let _ = std::fs::remove_dir_all(&d);
218 std::fs::create_dir_all(&d).unwrap();
219 d
220 }
221
222 #[test]
225 fn a_project_venv_is_found_and_read() {
226 let d = temp("venv");
227 let venv = d.join(".venv");
228 let bin = if cfg!(windows) { venv.join("Scripts") } else { venv.join("bin") };
229 std::fs::create_dir_all(&bin).unwrap();
230 std::fs::write(bin.join(if cfg!(windows) { "python.exe" } else { "python" }), "").unwrap();
231 std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\nversion_info = 3.13.1\n").unwrap();
232 let site =
233 if cfg!(windows) { venv.join("Lib/site-packages") } else { venv.join("lib/python3.13/site-packages") };
234 std::fs::create_dir_all(site.join("numpy-2.3.1.dist-info")).unwrap();
235 std::fs::create_dir_all(site.join("scikit_image-0.25.2.dist-info")).unwrap();
236 let env = PythonEnv::find(Some(&d), &d.join("default")).expect("the project's venv");
237 assert_eq!(env.source, PythonSource::Project);
238 assert_eq!(env.version().as_deref(), Some("3.13.1"));
239 assert_eq!(env.packages(), vec!["numpy".to_string(), "scikit-image".to_string()]);
240 std::fs::remove_dir_all(&d).ok();
241 }
242
243 #[test]
245 fn a_rust_environment_is_written_once() {
246 let d = temp("rust");
247 let pinned = ensure_rust(&d, &["build/*"]).unwrap();
248 let manifest = std::fs::read_to_string(d.join("Cargo.toml")).unwrap();
249 assert!(manifest.contains("[workspace]") && manifest.contains("\"build/*\""));
250 if let Some(v) = rustc_version() {
251 assert_eq!(pinned.as_deref(), Some(v.as_str()));
252 }
253 std::fs::write(d.join("rust-toolchain.toml"), "[toolchain]\nchannel = \"1.90.0\"\n").unwrap();
254 ensure_rust(&d, &["build/*"]).unwrap();
255 assert_eq!(rust_toolchain(&d).as_deref(), Some("1.90.0"), "an existing pin stays");
256 std::fs::remove_dir_all(&d).ok();
257 }
258
259 #[test]
260 fn a_new_pyproject_is_a_project_of_scripts() {
261 let p = pyproject("case-12-scripts", &["numpy"]);
262 assert!(p.contains("name = \"case-12-scripts\"") && p.contains("\"numpy\",") && p.contains("package = false"));
263 }
264}