Skip to main content

kitchen_tools/plugin/
discover.rs

1//! Finding an app's plugin programs (from lumen's discovery): every executable named
2//! `<prefix><name>` in, in order, `$<ENV>` (folders separated as in `PATH`), the user's plugin
3//! folder (`$XDG_DATA_HOME/<app>/plugins` or `~/.local/share/<app>/plugins`), the folder of the
4//! running program (an installed app with its plugins beside it, or `target/<profile>` in
5//! development) and `PATH`. The first program of each name wins; each is asked for its manifest
6//! (`<program> info`).
7
8use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use crate::plugin::PluginInfo;
13
14/// An app's kind of plugin: how its programs are named and where they are looked for.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct PluginKind {
17    /// The app (`lumen`): names the user's plugin folder.
18    pub app: String,
19    /// Program names start with this (`lumen-ml-`).
20    pub prefix: String,
21    /// The variable listing more folders (`LUMEN_PLUGINS`).
22    pub env: String,
23    /// Where the manager installs plugins (the user's plugin folder by default).
24    pub user_dir: PathBuf,
25    /// Whether the running program's folder and `PATH` are searched too.
26    pub system: bool,
27}
28
29impl PluginKind {
30    /// The plugins of `app`, named `<prefix><name>`, with more folders in `$<env>`.
31    pub fn new(app: &str, prefix: &str, env: &str) -> Self {
32        let data = std::env::var_os("XDG_DATA_HOME")
33            .filter(|d| !d.is_empty())
34            .map(PathBuf::from)
35            .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
36            .unwrap_or_else(std::env::temp_dir);
37        Self {
38            app: app.into(),
39            prefix: prefix.into(),
40            env: env.into(),
41            user_dir: data.join(app).join("plugins"),
42            system: true,
43        }
44    }
45
46    /// Installs into, and looks first in, `dir` instead of the user's plugin folder.
47    pub fn with_user_dir(mut self, dir: impl Into<PathBuf>) -> Self {
48        self.user_dir = dir.into();
49        self
50    }
51
52    /// Looks only in `$<env>` and the user's plugin folder (not beside the program or on `PATH`).
53    pub fn without_system(mut self) -> Self {
54        self.system = false;
55        self
56    }
57
58    /// The folders searched, in order.
59    pub fn dirs(&self) -> Vec<PathBuf> {
60        let mut dirs = Vec::new();
61        if let Some(v) = std::env::var_os(&self.env) {
62            dirs.extend(std::env::split_paths(&v));
63        }
64        dirs.push(self.user_dir.clone());
65        if self.system {
66            if let Some(exe_dir) = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf)) {
67                dirs.push(exe_dir);
68            }
69            if let Some(p) = std::env::var_os("PATH") {
70                dirs.extend(std::env::split_paths(&p));
71            }
72        }
73        dirs
74    }
75
76    /// Whether `path` is one of these plugins by its name.
77    pub fn is_plugin(&self, path: &Path) -> bool {
78        let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false };
79        let stem = name.strip_suffix(".exe").unwrap_or(name);
80        // Build by-products (`lumen-ml-sam.d`) are not programs
81        stem.starts_with(&self.prefix) && stem.len() > self.prefix.len() && !stem.contains('.') && path.is_file()
82    }
83
84    /// The plugin's short name (`sam` of `lumen-ml-sam`).
85    pub fn short_name<'a>(&self, program: &'a str) -> &'a str {
86        let stem = program.strip_suffix(".exe").unwrap_or(program);
87        stem.strip_prefix(self.prefix.as_str()).unwrap_or(stem)
88    }
89
90    /// The plugin programs found, by name.
91    pub fn programs(&self) -> BTreeMap<String, PathBuf> {
92        let mut out = BTreeMap::new();
93        for dir in self.dirs() {
94            let Ok(entries) = std::fs::read_dir(&dir) else { continue };
95            for e in entries.flatten() {
96                let p = e.path();
97                if self.is_plugin(&p) {
98                    let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
99                    out.entry(name).or_insert(p);
100                }
101            }
102        }
103        out
104    }
105
106    /// Every plugin found and its manifest; a program that does not answer, or speaks another
107    /// protocol, is reported as an error (its name and why), not left out silently.
108    pub fn discover(&self) -> Vec<(PathBuf, Result<PluginInfo, String>)> {
109        self.programs()
110            .into_iter()
111            .map(|(name, path)| {
112                let info = info(&name, &path);
113                (path, info)
114            })
115            .collect()
116    }
117}
118
119/// Asks the program at `path` for its manifest and checks the protocol.
120pub fn info(name: &str, path: &Path) -> Result<PluginInfo, String> {
121    let out = Command::new(path).arg("info").output().map_err(|e| format!("{name}: {e}"))?;
122    if !out.status.success() {
123        return Err(format!("{name}: {}", String::from_utf8_lossy(&out.stderr).trim()));
124    }
125    let mut info: PluginInfo =
126        serde_json::from_slice(&out.stdout).map_err(|e| format!("{name}: its manifest does not read: {e}"))?;
127    info.program = path.to_string_lossy().into_owned();
128    info.compatible()?;
129    Ok(info)
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn only_programs_with_the_prefix_are_plugins() {
138        let dir = std::env::temp_dir().join(format!("kitchen-plugin-discover-{}", std::process::id()));
139        std::fs::create_dir_all(&dir).unwrap();
140        for n in ["demo-ml-sam", "demo-ml-sam.d", "demo-ml-", "demo-app", "notes.txt"] {
141            std::fs::write(dir.join(n), b"").unwrap();
142        }
143        let kind =
144            PluginKind::new("demo", "demo-ml-", "KITCHEN_PLUGIN_TEST_UNSET").with_user_dir(&dir).without_system();
145        let found: Vec<String> = kind.programs().into_keys().collect();
146        assert_eq!(found, vec!["demo-ml-sam".to_string()]);
147        assert_eq!(kind.short_name("demo-ml-sam"), "sam");
148        let _ = std::fs::remove_dir_all(&dir);
149    }
150}