Skip to main content

kitchen_services/
python_tools.rs

1//! The Python tools an app favours without shipping them: uv (environments, running scripts), ruff
2//! (format, lint) and ty (types). Each is found, picked at another path, or off ([`Choice`]);
3//! `$UV`, `$RUFF` and `$TY` win over the choice, as `$UV` always has. The choices are one
4//! [`PythonTools`], kept in a file the app names ([`load`], [`save`]; JSON, read and written whole)
5//! and set for the process with [`set_current`], so every part of the app finds the same tools
6//! ([`find`]). Nothing here installs a tool: a missing one is reported with its install page.
7//!
8//! A project's own `pyproject.toml` / `ruff.toml` configure the tools; the app only picks them.
9
10use std::path::{Path, PathBuf};
11use std::process::Command;
12use std::sync::RwLock;
13
14use serde::{Deserialize, Serialize};
15
16/// One of the tools.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum PyTool {
19    Uv,
20    Ruff,
21    Ty,
22}
23
24impl PyTool {
25    pub const ALL: [PyTool; 3] = [PyTool::Uv, PyTool::Ruff, PyTool::Ty];
26
27    /// Its program name (`uv`).
28    pub fn name(self) -> &'static str {
29        match self {
30            PyTool::Uv => "uv",
31            PyTool::Ruff => "ruff",
32            PyTool::Ty => "ty",
33        }
34    }
35
36    /// The environment variable that names its program and wins over the settings.
37    pub fn env_var(self) -> &'static str {
38        match self {
39            PyTool::Uv => "UV",
40            PyTool::Ruff => "RUFF",
41            PyTool::Ty => "TY",
42        }
43    }
44
45    /// What the app uses it for, in a sentence (the Settings row).
46    pub fn purpose(self) -> &'static str {
47        match self {
48            PyTool::Uv => "Makes the project's environment and runs scripts in it (uv run).",
49            PyTool::Ruff => "Formats on save and finds lint problems.",
50            PyTool::Ty => "Finds type problems; its language server gives hover, completions and definitions.",
51        }
52    }
53
54    /// Where to install it.
55    pub fn install_url(self) -> &'static str {
56        match self {
57            PyTool::Uv => "https://docs.astral.sh/uv/getting-started/installation/",
58            PyTool::Ruff => "https://docs.astral.sh/ruff/installation/",
59            PyTool::Ty => "https://docs.astral.sh/ty/installation/",
60        }
61    }
62
63    fn exe(self) -> String {
64        if cfg!(windows) { format!("{}.exe", self.name()) } else { self.name().to_string() }
65    }
66}
67
68/// How a tool is picked.
69#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case", tag = "use", content = "path")]
71pub enum Choice {
72    /// Wherever it is found: the `PATH`, then where its installer puts it.
73    #[default]
74    Found,
75    /// This program.
76    Path(PathBuf),
77    /// Not used (plain `python3`, no formatting, no type checks).
78    Off,
79}
80
81/// The app's Python tools and what they do.
82#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(default)]
84pub struct PythonTools {
85    pub uv: Choice,
86    pub ruff: Choice,
87    pub ty: Choice,
88    /// ruff formats a script when it is saved.
89    pub format_on_save: bool,
90    /// The editor talks to ty's language server (type problems as you type, hover, completions,
91    /// definitions) rather than running `ty check` after a save.
92    pub ty_server: bool,
93    /// The editor talks to ruff's language server (lint problems, fixes) rather than running
94    /// `ruff check` after a save.
95    pub ruff_server: bool,
96}
97
98impl Default for PythonTools {
99    fn default() -> Self {
100        Self {
101            uv: Choice::Found,
102            ruff: Choice::Found,
103            ty: Choice::Found,
104            format_on_save: true,
105            ty_server: true,
106            ruff_server: false,
107        }
108    }
109}
110
111impl PythonTools {
112    /// The choice for `tool`.
113    pub fn choice(&self, tool: PyTool) -> &Choice {
114        match tool {
115            PyTool::Uv => &self.uv,
116            PyTool::Ruff => &self.ruff,
117            PyTool::Ty => &self.ty,
118        }
119    }
120
121    /// Sets the choice for `tool`.
122    pub fn set_choice(&mut self, tool: PyTool, choice: Choice) {
123        match tool {
124            PyTool::Uv => self.uv = choice,
125            PyTool::Ruff => self.ruff = choice,
126            PyTool::Ty => self.ty = choice,
127        }
128    }
129}
130
131static CURRENT: RwLock<Option<PythonTools>> = RwLock::new(None);
132
133/// The process's choices (the defaults until [`set_current`]).
134pub fn current() -> PythonTools {
135    CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default()
136}
137
138/// Sets the process's choices (the app, after loading them or when Settings change).
139pub fn set_current(tools: PythonTools) {
140    *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(tools);
141}
142
143/// The choices kept at `path` (the defaults when there is no file yet or it cannot be read).
144pub fn load(path: &Path) -> PythonTools {
145    std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
146}
147
148/// Keeps `tools` at `path`.
149pub fn save(path: &Path, tools: &PythonTools) -> Result<(), String> {
150    if let Some(dir) = path.parent() {
151        std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
152    }
153    let text = serde_json::to_string_pretty(tools).map_err(|e| e.to_string())?;
154    std::fs::write(path, text + "\n").map_err(|e| format!("{}: {e}", path.display()))
155}
156
157/// `tool`'s program with the process's choices: `$<TOOL>` first, then the choice.
158pub fn find(tool: PyTool) -> Option<PathBuf> {
159    find_with(tool, &current())
160}
161
162/// `tool`'s program with `tools`' choice (`$<TOOL>` still first).
163pub fn find_with(tool: PyTool, tools: &PythonTools) -> Option<PathBuf> {
164    if let Some(p) = std::env::var_os(tool.env_var()).map(PathBuf::from).filter(|p| p.is_file()) {
165        return Some(p);
166    }
167    match tools.choice(tool) {
168        Choice::Off => None,
169        Choice::Path(p) => p.is_file().then(|| p.clone()),
170        Choice::Found => found(tool),
171    }
172}
173
174/// Where `tool` is when nothing picks it: the `PATH`, then where its installer puts it.
175pub fn found(tool: PyTool) -> Option<PathBuf> {
176    let exe = tool.exe();
177    let on_path =
178        std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join(&exe)).find(|c| c.is_file()));
179    on_path.or_else(|| {
180        let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)?;
181        [home.join(".local/bin").join(&exe), home.join(".cargo/bin").join(&exe)].into_iter().find(|c| c.is_file())
182    })
183}
184
185/// `program --version`'s first line (`ruff 0.14.2`); `None` when it does not run.
186pub fn version(program: &Path) -> Option<String> {
187    let out = Command::new(program).arg("--version").output().ok()?;
188    out.status.success().then(|| String::from_utf8_lossy(&out.stdout).lines().next().unwrap_or("").trim().to_string())
189}
190
191/// What the Settings row of `tool` says: its program and version, or why there is none.
192#[derive(Clone, Debug, PartialEq, Eq)]
193pub enum Status {
194    /// Used: the program, its version, and whether the environment variable picked it.
195    Used { program: PathBuf, version: Option<String>, from_env: bool },
196    /// Off in the settings.
197    Off,
198    /// Not found (or the path picked is not a program).
199    Missing,
200}
201
202/// `tool`'s status with `tools`' choices (runs `--version`: call it off the UI thread).
203pub fn status(tool: PyTool, tools: &PythonTools) -> Status {
204    let from_env = std::env::var_os(tool.env_var()).map(PathBuf::from).is_some_and(|p| p.is_file());
205    match find_with(tool, tools) {
206        Some(program) => Status::Used { version: version(&program), program, from_env },
207        None if *tools.choice(tool) == Choice::Off && !from_env => Status::Off,
208        None => Status::Missing,
209    }
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    #[test]
217    fn choices_round_trip_and_off_or_a_bad_path_finds_nothing() {
218        let dir = std::env::temp_dir().join(format!("kitchen-python-tools-{}", std::process::id()));
219        let file = dir.join("python-tools.json");
220        assert_eq!(load(&file), PythonTools::default(), "no file: the defaults");
221        let mut t = PythonTools::default();
222        t.set_choice(PyTool::Ruff, Choice::Off);
223        t.set_choice(PyTool::Ty, Choice::Path(dir.join("no-such-ty")));
224        t.format_on_save = false;
225        save(&file, &t).unwrap();
226        assert_eq!(load(&file), t);
227        if std::env::var_os("RUFF").is_none() {
228            assert_eq!(find_with(PyTool::Ruff, &t), None, "off");
229            assert_eq!(status(PyTool::Ruff, &t), Status::Off);
230        }
231        if std::env::var_os("TY").is_none() {
232            assert_eq!(find_with(PyTool::Ty, &t), None, "a path that is not a program");
233            assert_eq!(status(PyTool::Ty, &t), Status::Missing);
234        }
235        let _ = std::fs::remove_dir_all(&dir);
236    }
237}