schedr_bin/
interpreter.rs1use std::collections::BTreeMap;
11use std::fmt;
12use std::path::{Path, PathBuf};
13use std::process::Command;
14
15use schedr_config::Config;
16use schedr_config::Interpreter;
17use schedr_config::config::BUILTIN_PYTHON;
18
19#[cfg(test)]
20mod tests;
21
22const PYTHON: &str = "python";
24
25pub const PROJECT_VENVS: [&str; 2] = [".venv", "venv"];
27
28#[derive(Debug, Clone, Copy)]
30pub struct Host<'a> {
31 pub env: &'a BTreeMap<String, String>,
33 pub cwd: Option<&'a Path>,
35 pub exe: Option<&'a Path>,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum How {
42 ActiveVenv,
44 ProjectVenv,
46 NextToBinary,
48 Path,
50 Pyenv,
52 NotFound,
54}
55
56impl fmt::Display for How {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58 f.write_str(match self {
59 Self::ActiveVenv => "active virtualenv, $VIRTUAL_ENV",
60 Self::ProjectVenv => "project venv",
61 Self::NextToBinary => "next to the schedr binary",
62 Self::Path => "python3 on PATH",
63 Self::Pyenv => "pyenv shim on PATH, resolved with `pyenv which python3`",
64 Self::NotFound => "no python3 found: left to the system",
65 })
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Found {
72 pub path: PathBuf,
74 pub how: How,
76}
77
78#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
80#[error(
81 "`python3` on PATH is a pyenv shim ({shim}), but `pyenv which python3` failed: {message}; \
82 choose a Python with `pyenv local`, or set [interpreters] python \
83 (SCHEDR_CONFIG__INTERPRETERS__PYTHON)"
84)]
85pub struct PyenvError {
86 pub shim: PathBuf,
88 pub message: String,
90}
91
92pub fn discover(
102 host: &Host<'_>,
103 project: bool,
104 pyenv: impl Fn(&Path, &Host<'_>) -> Result<PathBuf, String>,
105) -> Result<Found, PyenvError> {
106 let found = |path: PathBuf, how| Ok(Found { path, how });
107 if project {
108 if let Some(venv) = host.env.get("VIRTUAL_ENV").filter(|v| !v.is_empty()) {
109 let python = Path::new(venv).join("bin").join(BUILTIN_PYTHON);
110 if python.is_file() {
111 return found(python, How::ActiveVenv);
112 }
113 }
114 if let Some(cwd) = host.cwd {
115 for dir in cwd.ancestors() {
116 for venv in PROJECT_VENVS {
117 let python = dir.join(venv).join("bin").join(BUILTIN_PYTHON);
118 if python.is_file() {
119 return found(python, How::ProjectVenv);
120 }
121 }
122 }
123 }
124 }
125 if let Some(exe) = host.exe {
126 let exe = std::fs::canonicalize(exe).unwrap_or_else(|_| exe.to_path_buf());
127 if let Some(python) = exe.parent().map(|dir| dir.join(BUILTIN_PYTHON))
128 && python.is_file()
129 {
130 return found(python, How::NextToBinary);
131 }
132 }
133 let Some(python) = on_path(host, BUILTIN_PYTHON) else {
134 return found(PathBuf::from(BUILTIN_PYTHON), How::NotFound);
135 };
136 let Some(root) = pyenv_root(host) else {
137 return found(python, How::Path);
138 };
139 let shims = root.join("shims");
140 let is_shim = shims.is_dir()
141 && python.parent().is_some_and(|dir| {
142 dir == shims || std::fs::canonicalize(dir).ok() == std::fs::canonicalize(&shims).ok()
143 });
144 if !is_shim {
145 return found(python, How::Path);
146 }
147 let pyenv_bin = on_path(host, "pyenv").unwrap_or_else(|| root.join("bin").join("pyenv"));
148 match pyenv(&pyenv_bin, host) {
149 Ok(path) => found(path, How::Pyenv),
150 Err(message) => Err(PyenvError {
151 shim: python,
152 message,
153 }),
154 }
155}
156
157pub fn pyenv_which(pyenv: &Path, host: &Host<'_>) -> Result<PathBuf, String> {
164 let mut command = Command::new(pyenv);
165 command
166 .args(["which", BUILTIN_PYTHON])
167 .env_clear()
168 .envs(host.env);
169 if let Some(cwd) = host.cwd {
170 command.current_dir(cwd);
171 }
172 let output = command
173 .output()
174 .map_err(|e| format!("can't run {}: {e}", pyenv.display()))?;
175 if !output.status.success() {
176 return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
177 }
178 let path = String::from_utf8_lossy(&output.stdout).trim().to_owned();
179 if path.is_empty() {
180 return Err("it printed no path".to_owned());
181 }
182 Ok(PathBuf::from(path))
183}
184
185pub fn apply(config: &mut Config, host: &Host<'_>, project: bool) -> Result<(), PyenvError> {
194 if config.builtin_python.is_none() || config.dags.interpreter != PYTHON {
195 return Ok(());
196 }
197 let found = discover(host, project, pyenv_which)?;
198 tracing::info!(python = %found.path.display(), how = %found.how, "DAG interpreter");
199 config
200 .interpreters
201 .insert(PYTHON.to_owned(), Interpreter::path(found.path));
202 config.builtin_python = Some(found.how.to_string());
203 Ok(())
204}
205
206fn on_path(host: &Host<'_>, name: &str) -> Option<PathBuf> {
207 host.env
208 .get("PATH")?
209 .split(':')
210 .filter(|dir| !dir.is_empty())
211 .map(|dir| Path::new(dir).join(name))
212 .find(|candidate| candidate.is_file())
213}
214
215fn pyenv_root(host: &Host<'_>) -> Option<PathBuf> {
216 host.env
217 .get("PYENV_ROOT")
218 .filter(|r| !r.is_empty())
219 .map(PathBuf::from)
220 .or_else(|| host.env.get("HOME").map(|h| Path::new(h).join(".pyenv")))
221}