use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::RwLock;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PyTool {
Uv,
Ruff,
Ty,
}
impl PyTool {
pub const ALL: [PyTool; 3] = [PyTool::Uv, PyTool::Ruff, PyTool::Ty];
pub fn name(self) -> &'static str {
match self {
PyTool::Uv => "uv",
PyTool::Ruff => "ruff",
PyTool::Ty => "ty",
}
}
pub fn env_var(self) -> &'static str {
match self {
PyTool::Uv => "UV",
PyTool::Ruff => "RUFF",
PyTool::Ty => "TY",
}
}
pub fn purpose(self) -> &'static str {
match self {
PyTool::Uv => "Makes the project's environment and runs scripts in it (uv run).",
PyTool::Ruff => "Formats on save and finds lint problems.",
PyTool::Ty => "Finds type problems; its language server gives hover, completions and definitions.",
}
}
pub fn install_url(self) -> &'static str {
match self {
PyTool::Uv => "https://docs.astral.sh/uv/getting-started/installation/",
PyTool::Ruff => "https://docs.astral.sh/ruff/installation/",
PyTool::Ty => "https://docs.astral.sh/ty/installation/",
}
}
fn exe(self) -> String {
if cfg!(windows) { format!("{}.exe", self.name()) } else { self.name().to_string() }
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "use", content = "path")]
pub enum Choice {
#[default]
Found,
Path(PathBuf),
Off,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PythonTools {
pub uv: Choice,
pub ruff: Choice,
pub ty: Choice,
pub format_on_save: bool,
pub ty_server: bool,
pub ruff_server: bool,
}
impl Default for PythonTools {
fn default() -> Self {
Self {
uv: Choice::Found,
ruff: Choice::Found,
ty: Choice::Found,
format_on_save: true,
ty_server: true,
ruff_server: false,
}
}
}
impl PythonTools {
pub fn choice(&self, tool: PyTool) -> &Choice {
match tool {
PyTool::Uv => &self.uv,
PyTool::Ruff => &self.ruff,
PyTool::Ty => &self.ty,
}
}
pub fn set_choice(&mut self, tool: PyTool, choice: Choice) {
match tool {
PyTool::Uv => self.uv = choice,
PyTool::Ruff => self.ruff = choice,
PyTool::Ty => self.ty = choice,
}
}
}
static CURRENT: RwLock<Option<PythonTools>> = RwLock::new(None);
pub fn current() -> PythonTools {
CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default()
}
pub fn set_current(tools: PythonTools) {
*CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(tools);
}
pub fn load(path: &Path) -> PythonTools {
std::fs::read_to_string(path).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
}
pub fn save(path: &Path, tools: &PythonTools) -> Result<(), String> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
}
let text = serde_json::to_string_pretty(tools).map_err(|e| e.to_string())?;
std::fs::write(path, text + "\n").map_err(|e| format!("{}: {e}", path.display()))
}
pub fn find(tool: PyTool) -> Option<PathBuf> {
find_with(tool, ¤t())
}
pub fn find_with(tool: PyTool, tools: &PythonTools) -> Option<PathBuf> {
if let Some(p) = std::env::var_os(tool.env_var()).map(PathBuf::from).filter(|p| p.is_file()) {
return Some(p);
}
match tools.choice(tool) {
Choice::Off => None,
Choice::Path(p) => p.is_file().then(|| p.clone()),
Choice::Found => found(tool),
}
}
pub fn found(tool: PyTool) -> Option<PathBuf> {
let exe = tool.exe();
let on_path =
std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join(&exe)).find(|c| c.is_file()));
on_path.or_else(|| {
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from)?;
[home.join(".local/bin").join(&exe), home.join(".cargo/bin").join(&exe)].into_iter().find(|c| c.is_file())
})
}
pub fn version(program: &Path) -> Option<String> {
let out = Command::new(program).arg("--version").output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).lines().next().unwrap_or("").trim().to_string())
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
Used { program: PathBuf, version: Option<String>, from_env: bool },
Off,
Missing,
}
pub fn status(tool: PyTool, tools: &PythonTools) -> Status {
let from_env = std::env::var_os(tool.env_var()).map(PathBuf::from).is_some_and(|p| p.is_file());
match find_with(tool, tools) {
Some(program) => Status::Used { version: version(&program), program, from_env },
None if *tools.choice(tool) == Choice::Off && !from_env => Status::Off,
None => Status::Missing,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn choices_round_trip_and_off_or_a_bad_path_finds_nothing() {
let dir = std::env::temp_dir().join(format!("kitchen-python-tools-{}", std::process::id()));
let file = dir.join("python-tools.json");
assert_eq!(load(&file), PythonTools::default(), "no file: the defaults");
let mut t = PythonTools::default();
t.set_choice(PyTool::Ruff, Choice::Off);
t.set_choice(PyTool::Ty, Choice::Path(dir.join("no-such-ty")));
t.format_on_save = false;
save(&file, &t).unwrap();
assert_eq!(load(&file), t);
if std::env::var_os("RUFF").is_none() {
assert_eq!(find_with(PyTool::Ruff, &t), None, "off");
assert_eq!(status(PyTool::Ruff, &t), Status::Off);
}
if std::env::var_os("TY").is_none() {
assert_eq!(find_with(PyTool::Ty, &t), None, "a path that is not a program");
assert_eq!(status(PyTool::Ty, &t), Status::Missing);
}
let _ = std::fs::remove_dir_all(&dir);
}
}