use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::plugin::PluginInfo;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginKind {
pub app: String,
pub prefix: String,
pub env: String,
pub user_dir: PathBuf,
pub system: bool,
}
impl PluginKind {
pub fn new(app: &str, prefix: &str, env: &str) -> Self {
let data = std::env::var_os("XDG_DATA_HOME")
.filter(|d| !d.is_empty())
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
.unwrap_or_else(std::env::temp_dir);
Self {
app: app.into(),
prefix: prefix.into(),
env: env.into(),
user_dir: data.join(app).join("plugins"),
system: true,
}
}
pub fn with_user_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.user_dir = dir.into();
self
}
pub fn without_system(mut self) -> Self {
self.system = false;
self
}
pub fn dirs(&self) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if let Some(v) = std::env::var_os(&self.env) {
dirs.extend(std::env::split_paths(&v));
}
dirs.push(self.user_dir.clone());
if self.system {
if let Some(exe_dir) = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf)) {
dirs.push(exe_dir);
}
if let Some(p) = std::env::var_os("PATH") {
dirs.extend(std::env::split_paths(&p));
}
}
dirs
}
pub fn is_plugin(&self, path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false };
let stem = name.strip_suffix(".exe").unwrap_or(name);
stem.starts_with(&self.prefix) && stem.len() > self.prefix.len() && !stem.contains('.') && path.is_file()
}
pub fn short_name<'a>(&self, program: &'a str) -> &'a str {
let stem = program.strip_suffix(".exe").unwrap_or(program);
stem.strip_prefix(self.prefix.as_str()).unwrap_or(stem)
}
pub fn programs(&self) -> BTreeMap<String, PathBuf> {
let mut out = BTreeMap::new();
for dir in self.dirs() {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for e in entries.flatten() {
let p = e.path();
if self.is_plugin(&p) {
let name = p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
out.entry(name).or_insert(p);
}
}
}
out
}
pub fn discover(&self) -> Vec<(PathBuf, Result<PluginInfo, String>)> {
self.programs()
.into_iter()
.map(|(name, path)| {
let info = info(&name, &path);
(path, info)
})
.collect()
}
}
pub fn info(name: &str, path: &Path) -> Result<PluginInfo, String> {
let out = Command::new(path).arg("info").output().map_err(|e| format!("{name}: {e}"))?;
if !out.status.success() {
return Err(format!("{name}: {}", String::from_utf8_lossy(&out.stderr).trim()));
}
let mut info: PluginInfo =
serde_json::from_slice(&out.stdout).map_err(|e| format!("{name}: its manifest does not read: {e}"))?;
info.program = path.to_string_lossy().into_owned();
info.compatible()?;
Ok(info)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_programs_with_the_prefix_are_plugins() {
let dir = std::env::temp_dir().join(format!("kitchen-plugin-discover-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for n in ["demo-ml-sam", "demo-ml-sam.d", "demo-ml-", "demo-app", "notes.txt"] {
std::fs::write(dir.join(n), b"").unwrap();
}
let kind =
PluginKind::new("demo", "demo-ml-", "KITCHEN_PLUGIN_TEST_UNSET").with_user_dir(&dir).without_system();
let found: Vec<String> = kind.programs().into_keys().collect();
assert_eq!(found, vec!["demo-ml-sam".to_string()]);
assert_eq!(kind.short_name("demo-ml-sam"), "sam");
let _ = std::fs::remove_dir_all(&dir);
}
}