1use std::ffi::OsStr;
8use std::path::{Path, PathBuf};
9
10pub use byob_sandbox::which;
11
12pub const PYTHON_ENV: &str = "BYOB_PYTHON";
14
15pub fn managed_root(data_dir: &Path) -> PathBuf {
17 data_dir.join("python")
18}
19
20pub fn managed_venv(data_dir: &Path) -> PathBuf {
21 managed_root(data_dir).join("venv")
22}
23
24pub fn venv_python(venv: &Path) -> PathBuf {
25 if cfg!(windows) { venv.join("Scripts").join("python.exe") } else { venv.join("bin").join("python") }
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Python {
31 pub path: PathBuf,
32 pub managed: bool,
34}
35
36impl Python {
37 pub fn resolve(data_dir: Option<&Path>) -> Option<Self> {
39 Self::resolve_in(data_dir, &[])
40 }
41
42 pub fn resolve_in(data_dir: Option<&Path>, env_path: &[PathBuf]) -> Option<Self> {
45 if let Some(p) = std::env::var_os(PYTHON_ENV).filter(|p| !p.is_empty()) {
46 return which(&p).map(|path| Self { path, managed: false });
47 }
48 for dir in env_path {
49 for name in ["python3", "python"] {
50 let p = dir.join(if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() });
51 if which(p.as_os_str()).is_some() {
52 return Some(Self { path: p, managed: false });
53 }
54 }
55 }
56 if let Some(d) = data_dir {
57 let p = venv_python(&managed_venv(d));
58 if p.exists() {
59 return Some(Self { path: p, managed: true });
60 }
61 }
62 system_python().map(|path| Self { path, managed: false })
63 }
64
65 pub fn read_paths(&self) -> Vec<PathBuf> {
68 byob_sandbox::interpreter_read_paths(self.path.as_os_str())
69 }
70}
71
72pub fn system_python() -> Option<PathBuf> {
76 let found = ["python3", "python"].into_iter().filter_map(|n| which(OsStr::new(n))).find(|p| !is_store_alias(p));
77 if found.is_some() || !cfg!(windows) {
78 return found;
79 }
80 let launcher = which(OsStr::new("py"))?;
81 let out = std::process::Command::new(launcher)
82 .args(["-3", "-c", "import sys; print(sys.executable)"])
83 .stdin(std::process::Stdio::null())
84 .stderr(std::process::Stdio::null())
85 .output()
86 .ok()
87 .filter(|o| o.status.success())?;
88 let path = PathBuf::from(String::from_utf8(out.stdout).ok()?.trim());
89 (path.is_absolute() && path.is_file() && !is_store_alias(&path)).then_some(path)
90}
91
92fn is_store_alias(p: &Path) -> bool {
94 p.components().any(|c| c.as_os_str().eq_ignore_ascii_case("WindowsApps"))
95}
96
97pub fn valid_requirement(s: &str) -> bool {
100 let Some(first) = s.chars().next() else { return false };
101 s.len() <= 100 && first.is_ascii_alphanumeric() && s.chars().all(|c| c.is_ascii_alphanumeric() || "._-[],<>=!~".contains(c))
102}
103
104#[cfg(test)]
105mod tests {
106 #[cfg(windows)]
109 #[test]
110 fn windows_finds_an_installed_python() {
111 let p = system_python().expect("a Python on PATH or through py");
112 assert!(!is_store_alias(&p) && p.is_file(), "{}", p.display());
113 }
114
115 #[test]
116 fn store_aliases_are_not_python() {
117 assert!(is_store_alias(Path::new("/Users/me/AppData/Local/Microsoft/WindowsApps/python.exe")));
118 assert!(is_store_alias(Path::new("/x/windowsapps/python3.exe")));
119 assert!(!is_store_alias(Path::new("/usr/bin/python3")));
120 }
121
122 use super::*;
123
124 #[test]
125 fn requirements() {
126 for ok in ["pandas", "scikit-learn>=1.4", "xarray[io]", "numpy==2.1.0", "a.b_c"] {
127 assert!(valid_requirement(ok), "{ok}");
128 }
129 for bad in ["", "-r", "--index-url=x", "../x", "git+https://x", "a b", "pkg@ https://x", "/abs", "x;rm", &"a".repeat(101)] {
130 assert!(!valid_requirement(bad), "{bad}");
131 }
132 }
133
134 #[cfg(unix)]
135 #[test]
136 fn venv_read_paths() {
137 use std::os::unix::fs::PermissionsExt;
138 let d = tempfile::tempdir().unwrap();
139 let venv = d.path().join("venv");
140 std::fs::create_dir_all(venv.join("bin")).unwrap();
141 std::fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
142 std::fs::write(venv.join("bin/python"), "").unwrap();
143 std::fs::set_permissions(venv.join("bin/python"), std::fs::Permissions::from_mode(0o755)).unwrap();
144 let p = Python { path: venv.join("bin/python"), managed: true };
145 assert!(p.read_paths().contains(&venv.canonicalize().unwrap()));
146 std::fs::create_dir_all(d.path().join("bin")).unwrap();
148 std::fs::write(d.path().join("bin/python3"), "").unwrap();
149 std::fs::set_permissions(d.path().join("bin/python3"), std::fs::Permissions::from_mode(0o755)).unwrap();
150 let p = Python { path: d.path().join("bin/python3"), managed: false };
151 assert!(p.read_paths().is_empty());
152 }
153}