Skip to main content

crate_plugin_kit/store/
install.rs

1//! Installing, updating and uninstalling a plugin.
2//!
3//! These are the only calls that take the install lock and touch the install directory:
4//! `install` refuses a crate that is already present, `update` replaces it either way,
5//! and `uninstall` deletes it — but not while this process has its library loaded, since
6//! a `dlopen`ed library cannot always be removed.
7
8use crate::cache::Index;
9use crate::error::{KitError, KitResult};
10use crate::install::{self, build_host, prebuilt, Installed};
11
12use super::CratePluginKit;
13
14impl<T> CratePluginKit<T> {
15    /// Installs a plugin.
16    ///
17    /// `name` may be a short name (`"cargo"`, to which [`crate::KitConfig::crate_prefix`]
18    /// is prepended) or a full crate name. With `version` set to `None`, the latest
19    /// version is looked up on crates.io.
20    ///
21    /// # Errors
22    ///
23    /// - [`KitError::AlreadyInstalled`]: it is already installed. Use [`Self::update`]
24    ///   to replace it.
25    pub fn install(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
26        let crate_name = self.cfg.normalize_crate_name(name);
27
28        let _lock = self.lock()?;
29
30        let dir = self.paths.plugin_dir(&crate_name);
31        if dir.is_dir() {
32            return Err(KitError::AlreadyInstalled {
33                name: crate_name,
34                path: dir,
35            });
36        }
37
38        let version = self.resolve_version(&crate_name, version)?;
39        let installed = self.install_locked(&crate_name, &version)?;
40        self.record(&installed)?;
41        Ok(installed)
42    }
43
44    /// Updates (or reinstalls) a plugin. Replaces it if present, installs it if not.
45    pub fn update(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
46        let crate_name = self.cfg.normalize_crate_name(name);
47
48        let _lock = self.lock()?;
49
50        let version = self.resolve_version(&crate_name, version)?;
51        let installed = self.install_locked(&crate_name, &version)?;
52        self.record(&installed)?;
53        Ok(installed)
54    }
55
56    /// Uninstalls a plugin.
57    ///
58    /// # Errors
59    ///
60    /// - [`KitError::NotInstalled`]: it was not installed in the first place.
61    /// - [`KitError::PluginInUse`]: this process has loaded its library. A `.dll`
62    ///   that is currently `dlopen`ed cannot be deleted on Windows; on Linux the
63    ///   removal succeeds but the disk space is not reclaimed. Rather than gamble on
64    ///   it, ask the user to retry from a clean process.
65    pub fn uninstall(&self, name: &str) -> KitResult<()> {
66        let crate_name = self.cfg.normalize_crate_name(name);
67
68        let _lock = self.lock()?;
69
70        let dir = self.paths.plugin_dir(&crate_name);
71        if !dir.is_dir() {
72            return Err(KitError::NotInstalled { name: crate_name });
73        }
74
75        if self.loaded.borrow().contains(&crate_name) {
76            return Err(KitError::PluginInUse {
77                name: crate_name.clone(),
78            });
79        }
80
81        std::fs::remove_dir_all(&dir)?;
82
83        let mut idx = Index::load(&self.paths.index_file);
84        idx.remove(&crate_name);
85        idx.save(&self.paths.index_file)?;
86
87        Ok(())
88    }
89
90    /// The actual install. The caller must already hold the lock.
91    fn install_locked(&self, crate_name: &str, version: &str) -> KitResult<Installed> {
92        // Clear the old directory first (the update path)
93        install::remove_dir_if_exists(&self.paths.plugin_dir(crate_name))?;
94
95        if self.cfg.prefer_prebuilt {
96            match prebuilt::try_install(
97                self.config(),
98                self.paths(),
99                self.registry(),
100                crate_name,
101                version,
102            ) {
103                Ok(Some(installed)) => return Ok(installed),
104                // No prebuilt asset — this is exactly the signal to fall back to
105                // build-host
106                Ok(None) => {}
107                // Broken network or a corrupt asset: fall back as well. build-host
108                // goes through cargo, which is a different route from GitHub and may
109                // well work.
110                Err(_) => {}
111            }
112        }
113
114        build_host::install(self.config(), self.paths(), crate_name, version)
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::super::tests::{kit, place_plugin};
121    use super::*;
122
123    #[test]
124    fn uninstall_reports_a_plugin_that_is_not_installed() {
125        let tmp = tempfile::tempdir().unwrap();
126        let k = kit(&tmp.path().join("store"));
127
128        assert!(matches!(
129            k.uninstall("nope"),
130            Err(KitError::NotInstalled { .. })
131        ));
132    }
133
134    #[test]
135    fn uninstall_removes_the_directory() {
136        let tmp = tempfile::tempdir().unwrap();
137        let root = tmp.path().join("store");
138        let k = kit(&root);
139        let dir = place_plugin(&root, "myapp-plugin-foo");
140
141        assert!(dir.is_dir());
142        k.uninstall("foo").expect("should uninstall");
143        assert!(!dir.exists(), "the directory should have been deleted");
144        assert!(k.list().unwrap().is_empty());
145    }
146
147    /// `install` does not overwrite an existing installation — use `update` to
148    /// replace it.
149    ///
150    /// The check happens after the lock is taken and before any network or compile
151    /// work, so the test needs no network access.
152    #[test]
153    fn install_refuses_when_already_installed() {
154        let tmp = tempfile::tempdir().unwrap();
155        let root = tmp.path().join("store");
156        let k = kit(&root);
157        place_plugin(&root, "myapp-plugin-foo");
158
159        match k.install("foo", Some("0.1.0")) {
160            Err(KitError::AlreadyInstalled { name, .. }) => {
161                assert_eq!(name, "myapp-plugin-foo")
162            }
163            other => panic!("expected AlreadyInstalled, got {other:?}"),
164        }
165    }
166}