Skip to main content

kitchen_tools/plugin/
manager.rs

1//! The plugin manager: what is installed and how much room it takes; install a plugin from a
2//! file or a verified download ([`kitchen_downloads`]), update it, remove it (and what it downloaded).
3//! A plugin is installed only after it answers the handshake (its manifest, the same protocol).
4
5use std::path::{Path, PathBuf};
6use std::sync::atomic::AtomicBool;
7
8use kitchen_downloads::{Artifact, Hub, dir_size};
9
10use crate::plugin::PluginInfo;
11use crate::plugin::discover::{PluginKind, info};
12
13/// A plugin found, and what the manager knows of it.
14#[derive(Debug, Clone)]
15pub struct Installed {
16    /// Its program's file name (`lumen-ml-sam`).
17    pub name: String,
18    /// Its program.
19    pub program: PathBuf,
20    /// Its manifest, or why it could not be read.
21    pub info: Result<PluginInfo, String>,
22    /// Bytes it takes: its program and what it downloaded (its family in the hub).
23    pub bytes: u64,
24    /// Whether the manager installed it (in the user's plugin folder), so it can remove it.
25    pub removable: bool,
26}
27
28/// An app's plugin manager.
29#[derive(Debug, Clone)]
30pub struct Manager {
31    /// The app's plugins.
32    pub kind: PluginKind,
33    /// Where plugins keep what they download (one family per plugin, by its short name).
34    pub hub: Option<Hub>,
35}
36
37impl Manager {
38    /// A manager of `kind`'s plugins, whose downloads are in `hub`.
39    pub fn new(kind: PluginKind, hub: Option<Hub>) -> Self {
40        Self { kind, hub }
41    }
42
43    /// Every plugin found (each asked for its manifest; blocking: call it off the UI thread).
44    pub fn list(&self) -> Vec<Installed> {
45        self.kind
46            .discover()
47            .into_iter()
48            .map(|(program, info)| {
49                let name = program.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
50                let data = self.hub.as_ref().map_or(0, |h| h.disk_use(Some(self.kind.short_name(&name))));
51                let bytes = std::fs::metadata(&program).map(|m| m.len()).unwrap_or(0) + data;
52                let removable = program.parent() == Some(self.kind.user_dir.as_path());
53                Installed { name, program, info, bytes, removable }
54            })
55            .collect()
56    }
57
58    /// Installs (or updates) the plugin program at `source` into the user's plugin folder, after
59    /// it answers the handshake; returns its manifest.
60    pub fn install_from(&self, source: &Path) -> Result<PluginInfo, String> {
61        let name = source.file_name().map(|n| n.to_string_lossy().into_owned()).ok_or("no file name")?;
62        if !self.kind.is_plugin(source) {
63            return Err(format!("{name}: not a plugin of this app (its name starts with {})", self.kind.prefix));
64        }
65        info(&name, source)?;
66        std::fs::create_dir_all(&self.kind.user_dir).map_err(|e| format!("{}: {e}", self.kind.user_dir.display()))?;
67        let dest = self.kind.user_dir.join(&name);
68        // Copied beside, then renamed over the old one: a running copy keeps working
69        let part = dest.with_extension("part");
70        std::fs::copy(source, &part).map_err(|e| format!("{}: {e}", part.display()))?;
71        make_executable(&part)?;
72        std::fs::rename(&part, &dest).map_err(|e| format!("{}: {e}", dest.display()))?;
73        info(&name, &dest)
74    }
75
76    /// Downloads a plugin program published as `artifact` (verified by its hash), then installs it.
77    pub fn install_artifact(
78        &self,
79        artifact: &Artifact,
80        progress: &mut dyn FnMut(u64, u64),
81        cancel: Option<&AtomicBool>,
82    ) -> Result<PluginInfo, String> {
83        let hub = self.hub.as_ref().ok_or("no download cache set")?;
84        let file = hub.pull(artifact, progress, cancel)?;
85        // The downloaded file keeps the program's name
86        let named = file.with_file_name(&artifact.file_name);
87        make_executable(&named)?;
88        self.install_from(&named)
89    }
90
91    /// Removes the installed plugin `name` (and, with `data`, what it downloaded).
92    pub fn remove(&self, name: &str, data: bool) -> Result<(), String> {
93        let program = self.kind.user_dir.join(name);
94        if !program.is_file() {
95            return Err(format!("{name} is not in {}: it was not installed here", self.kind.user_dir.display()));
96        }
97        std::fs::remove_file(&program).map_err(|e| format!("{}: {e}", program.display()))?;
98        if data && let Some(hub) = &self.hub {
99            let dir = hub.family_dir(self.kind.short_name(name));
100            if dir.exists() {
101                std::fs::remove_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
102            }
103        }
104        Ok(())
105    }
106
107    /// Bytes every plugin takes with what it downloaded.
108    pub fn disk_use(&self) -> u64 {
109        dir_size(&self.kind.user_dir) + self.hub.as_ref().map_or(0, |h| h.disk_use(None))
110    }
111}
112
113#[cfg(unix)]
114fn make_executable(path: &Path) -> Result<(), String> {
115    use std::os::unix::fs::PermissionsExt as _;
116    let mut p = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.permissions();
117    p.set_mode(p.mode() | 0o755);
118    std::fs::set_permissions(path, p).map_err(|e| format!("{}: {e}", path.display()))
119}
120
121#[cfg(not(unix))]
122fn make_executable(_: &Path) -> Result<(), String> {
123    Ok(())
124}