kitchen_tools/plugin/
discover.rs1use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10use std::process::Command;
11
12use crate::plugin::PluginInfo;
13
14#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct PluginKind {
17 pub app: String,
19 pub prefix: String,
21 pub env: String,
23 pub user_dir: PathBuf,
25 pub system: bool,
27}
28
29impl PluginKind {
30 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 pub fn with_user_dir(mut self, dir: impl Into<PathBuf>) -> Self {
48 self.user_dir = dir.into();
49 self
50 }
51
52 pub fn without_system(mut self) -> Self {
54 self.system = false;
55 self
56 }
57
58 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 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 stem.starts_with(&self.prefix) && stem.len() > self.prefix.len() && !stem.contains('.') && path.is_file()
82 }
83
84 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 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 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
119pub 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}