kitchen-services 0.0.13

The services a neuro-kitchen app's frame shows, without the frame: background jobs, the activity log, people, script environments, and what the Changes panel compares
Documentation
//! The Python tools an app favours without shipping them: uv (environments, running scripts), ruff
//! (format, lint) and ty (types). Each is found, picked at another path, or off ([`Choice`]);
//! `$UV`, `$RUFF` and `$TY` win over the choice, as `$UV` always has. The choices are one
//! [`PythonTools`], kept in a file the app names ([`load`], [`save`]; JSON, read and written whole)
//! and set for the process with [`set_current`], so every part of the app finds the same tools
//! ([`find`]). Nothing here installs a tool: a missing one is reported with its install page.
//!
//! A project's own `pyproject.toml` / `ruff.toml` configure the tools; the app only picks them.

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::RwLock;

use serde::{Deserialize, Serialize};

/// One of the tools.
#[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];

    /// Its program name (`uv`).
    pub fn name(self) -> &'static str {
        match self {
            PyTool::Uv => "uv",
            PyTool::Ruff => "ruff",
            PyTool::Ty => "ty",
        }
    }

    /// The environment variable that names its program and wins over the settings.
    pub fn env_var(self) -> &'static str {
        match self {
            PyTool::Uv => "UV",
            PyTool::Ruff => "RUFF",
            PyTool::Ty => "TY",
        }
    }

    /// What the app uses it for, in a sentence (the Settings row).
    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.",
        }
    }

    /// Where to install it.
    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() }
    }
}

/// How a tool is picked.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "use", content = "path")]
pub enum Choice {
    /// Wherever it is found: the `PATH`, then where its installer puts it.
    #[default]
    Found,
    /// This program.
    Path(PathBuf),
    /// Not used (plain `python3`, no formatting, no type checks).
    Off,
}

/// The app's Python tools and what they do.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PythonTools {
    pub uv: Choice,
    pub ruff: Choice,
    pub ty: Choice,
    /// ruff formats a script when it is saved.
    pub format_on_save: bool,
    /// The editor talks to ty's language server (type problems as you type, hover, completions,
    /// definitions) rather than running `ty check` after a save.
    pub ty_server: bool,
    /// The editor talks to ruff's language server (lint problems, fixes) rather than running
    /// `ruff check` after a save.
    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 {
    /// The choice for `tool`.
    pub fn choice(&self, tool: PyTool) -> &Choice {
        match tool {
            PyTool::Uv => &self.uv,
            PyTool::Ruff => &self.ruff,
            PyTool::Ty => &self.ty,
        }
    }

    /// Sets the choice for `tool`.
    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);

/// The process's choices (the defaults until [`set_current`]).
pub fn current() -> PythonTools {
    CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default()
}

/// Sets the process's choices (the app, after loading them or when Settings change).
pub fn set_current(tools: PythonTools) {
    *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(tools);
}

/// The choices kept at `path` (the defaults when there is no file yet or it cannot be read).
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()
}

/// Keeps `tools` at `path`.
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()))
}

/// `tool`'s program with the process's choices: `$<TOOL>` first, then the choice.
pub fn find(tool: PyTool) -> Option<PathBuf> {
    find_with(tool, &current())
}

/// `tool`'s program with `tools`' choice (`$<TOOL>` still first).
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),
    }
}

/// Where `tool` is when nothing picks it: the `PATH`, then where its installer puts it.
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())
    })
}

/// `program --version`'s first line (`ruff 0.14.2`); `None` when it does not run.
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())
}

/// What the Settings row of `tool` says: its program and version, or why there is none.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Status {
    /// Used: the program, its version, and whether the environment variable picked it.
    Used { program: PathBuf, version: Option<String>, from_env: bool },
    /// Off in the settings.
    Off,
    /// Not found (or the path picked is not a program).
    Missing,
}

/// `tool`'s status with `tools`' choices (runs `--version`: call it off the UI thread).
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);
    }
}