Skip to main content

schedr_bin/
interpreter.rs

1//! Which Python the built-in `python` interpreter is, when `[interpreters]` doesn't define it.
2//!
3//! The local commands (`standalone`, `dags check`, `dags test`) look, first match winning: an
4//! active virtualenv (`$VIRTUAL_ENV`), a project venv (`.venv`, then `venv`, in the current
5//! directory and its parents), the `python3` next to the `schedr` binary, then `python3` on
6//! `PATH`; a pyenv shim found there is resolved once with `pyenv which python3`, in the user's
7//! environment and directory, since tasks get a clean environment and run elsewhere. A
8//! configured `python` always wins. See archive/PROJECT.md, Configuration: built-in interpreter.
9
10use 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
22/// The interpreter name the built-in one is registered under.
23const PYTHON: &str = "python";
24
25/// The project venv directories looked for, in order.
26pub const PROJECT_VENVS: [&str; 2] = [".venv", "venv"];
27
28/// Where the process runs: what discovery looks at.
29#[derive(Debug, Clone, Copy)]
30pub struct Host<'a> {
31    /// The user's environment (`VIRTUAL_ENV`, `PATH`, `PYENV_ROOT`, `HOME`, ...).
32    pub env: &'a BTreeMap<String, String>,
33    /// The current directory, if known.
34    pub cwd: Option<&'a Path>,
35    /// The running `schedr` executable, if known.
36    pub exe: Option<&'a Path>,
37}
38
39/// How the interpreter was found.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum How {
42    /// `$VIRTUAL_ENV/bin/python3`.
43    ActiveVenv,
44    /// `.venv/bin/python3` or `venv/bin/python3` in the current directory or a parent.
45    ProjectVenv,
46    /// `python3` in the `schedr` binary's directory.
47    NextToBinary,
48    /// `python3` on `PATH`.
49    Path,
50    /// A pyenv shim on `PATH`, resolved with `pyenv which python3`.
51    Pyenv,
52    /// Nothing found: plain `python3`, left to the system to find.
53    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/// The interpreter found, and how.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Found {
72    /// The executable, used as written (a venv's `python3` must not be resolved).
73    pub path: PathBuf,
74    /// How it was found.
75    pub how: How,
76}
77
78/// A pyenv shim that pyenv couldn't resolve.
79#[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    /// The shim.
87    pub shim: PathBuf,
88    /// What pyenv said.
89    pub message: String,
90}
91
92/// Finds the Python for the built-in `python` interpreter.
93///
94/// `project` turns on the steps that depend on the user's shell and directory (an active
95/// virtualenv, a project venv): the local commands use them, a worker won't (milestone M2).
96/// `pyenv` resolves a shim (normally [`pyenv_which`]).
97///
98/// # Errors
99///
100/// [`PyenvError`] if `python3` on `PATH` is a pyenv shim that pyenv can't resolve.
101pub 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
157/// Runs `pyenv which python3` in the user's environment and directory.
158///
159/// # Errors
160///
161/// What went wrong, as text: pyenv couldn't be started, failed (its stderr), or printed no
162/// path.
163pub 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
185/// Sets the built-in `python` interpreter, if `[interpreters]` doesn't define it and the DAG
186/// interpreter is `python`, and records how it was found ([`Config::builtin_python`]).
187/// Another DAG interpreter needs no lookup. `project` as for [`discover`]: on for the local
188/// commands, off for a worker.
189///
190/// # Errors
191///
192/// [`PyenvError`] as for [`discover`].
193pub 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}