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 std::path::Path;
9
10use crate::cache::{Index, InstallSource};
11use crate::error::{KitError, KitResult};
12use crate::install::{self, build_host, prebuilt, Installed};
13use crate::manifest::PluginManifest;
14
15use super::CratePluginKit;
16
17impl<T> CratePluginKit<T> {
18    /// Installs a plugin.
19    ///
20    /// `name` may be a short name (`"cargo"`, to which [`crate::KitConfig::crate_prefix`]
21    /// is prepended) or a full crate name. With `version` set to `None`, the latest
22    /// version is looked up on crates.io.
23    ///
24    /// # Errors
25    ///
26    /// - [`KitError::AlreadyInstalled`]: it is already installed. Use [`Self::update`]
27    ///   to replace it.
28    pub fn install(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
29        let crate_name = self.cfg.normalize_crate_name(name);
30
31        let _lock = self.lock()?;
32
33        let dir = self.paths.plugin_dir(&crate_name);
34        if dir.is_dir() {
35            return Err(KitError::AlreadyInstalled {
36                name: crate_name,
37                path: dir,
38            });
39        }
40
41        let version = self.resolve_version(&crate_name, version)?;
42        let installed = self.install_locked(&crate_name, &version)?;
43        self.record(&installed)?;
44        Ok(installed)
45    }
46
47    /// Installs a plugin from a checkout on this machine.
48    ///
49    /// The checkout is an ordinary plugin crate: a plain rlib with its manifest beside its
50    /// `Cargo.toml`. It is built exactly the way a published one is — through the same
51    /// generated wrapper, landing the same two files — so nothing downstream (loading,
52    /// listing, uninstalling) can tell the two apart. What differs is only where the source
53    /// comes from.
54    ///
55    /// This is the development loop: build and install what you are working on without
56    /// publishing it first. [`Self::update`] on such a plugin rebuilds from the same
57    /// directory, and the prebuilt download is skipped (there is no release to download).
58    ///
59    /// # Errors
60    ///
61    /// - [`KitError::NoManifest`]: the directory has no `Cargo.toml`.
62    /// - [`KitError::ManifestRead`]: it has no readable `<id>-plugin.toml` beside it.
63    /// - [`KitError::AlreadyInstalled`]: that plugin is already installed. Use
64    ///   [`Self::update`] to replace it.
65    pub fn install_from_path(&self, plugin_dir: impl AsRef<Path>) -> KitResult<Installed> {
66        let dir = plugin_dir.as_ref().canonicalize()?;
67
68        let _lock = self.lock()?;
69
70        // Checked before the build rather than after it: a checkout that cannot be installed
71        // should say so in a second, not after a `cargo build`.
72        if !dir.join("Cargo.toml").is_file() {
73            return Err(KitError::NoManifest { dir });
74        }
75        let manifest = PluginManifest::read(&dir.join(&self.cfg.manifest_name))?;
76
77        let crate_name = self.cfg.normalize_crate_name(&manifest.plugin.name);
78        let dir_installed = self.paths.plugin_dir(&crate_name);
79        if dir_installed.is_dir() {
80            return Err(KitError::AlreadyInstalled {
81                name: crate_name,
82                path: dir_installed,
83            });
84        }
85
86        let installed = build_host::install_from_path(
87            self.config(),
88            self.paths(),
89            &crate_name,
90            &manifest.plugin.version,
91            &dir,
92        )?;
93        self.record(&installed)?;
94        Ok(installed)
95    }
96
97    /// Updates (or reinstalls) a plugin. Replaces it if present, installs it if not.
98    ///
99    /// A plugin that was installed from a checkout is rebuilt from that checkout: the
100    /// registry has nothing to say about a version that was never published, and rebuilding
101    /// the directory is what updating it means.
102    pub fn update(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
103        let crate_name = self.cfg.normalize_crate_name(name);
104
105        let _lock = self.lock()?;
106
107        // The recorded source decides, not the argument: a `version` has no meaning for a
108        // checkout.
109        let recorded = Index::load(&self.paths.index_file)
110            .get(&crate_name)
111            .map(|entry| entry.source.clone());
112        if let Some(InstallSource::Local { path }) = recorded {
113            let manifest = PluginManifest::read(&path.join(&self.cfg.manifest_name))?;
114            let installed = build_host::install_from_path(
115                self.config(),
116                self.paths(),
117                &crate_name,
118                &manifest.plugin.version,
119                &path,
120            )?;
121            self.record(&installed)?;
122            return Ok(installed);
123        }
124
125        let version = self.resolve_version(&crate_name, version)?;
126        let installed = self.install_locked(&crate_name, &version)?;
127        self.record(&installed)?;
128        Ok(installed)
129    }
130
131    /// Uninstalls a plugin.
132    ///
133    /// # Errors
134    ///
135    /// - [`KitError::NotInstalled`]: it was not installed in the first place.
136    /// - [`KitError::PluginInUse`]: this process has loaded its library. A `.dll`
137    ///   that is currently `dlopen`ed cannot be deleted on Windows; on Linux the
138    ///   removal succeeds but the disk space is not reclaimed. Rather than gamble on
139    ///   it, ask the user to retry from a clean process.
140    pub fn uninstall(&self, name: &str) -> KitResult<()> {
141        let crate_name = self.cfg.normalize_crate_name(name);
142
143        let _lock = self.lock()?;
144
145        let dir = self.paths.plugin_dir(&crate_name);
146        if !dir.is_dir() {
147            return Err(KitError::NotInstalled { name: crate_name });
148        }
149
150        if self.loaded.borrow().contains(&crate_name) {
151            return Err(KitError::PluginInUse {
152                name: crate_name.clone(),
153            });
154        }
155
156        std::fs::remove_dir_all(&dir)?;
157
158        let mut idx = Index::load(&self.paths.index_file);
159        idx.remove(&crate_name);
160        idx.save(&self.paths.index_file)?;
161
162        Ok(())
163    }
164
165    /// The actual install. The caller must already hold the lock.
166    fn install_locked(&self, crate_name: &str, version: &str) -> KitResult<Installed> {
167        // Clear the old directory first (the update path)
168        install::remove_dir_if_exists(&self.paths.plugin_dir(crate_name))?;
169
170        if self.cfg.prefer_prebuilt {
171            match prebuilt::try_install(
172                self.config(),
173                self.paths(),
174                self.registry(),
175                crate_name,
176                version,
177            ) {
178                Ok(Some(installed)) => return Ok(installed),
179                // No prebuilt asset — this is exactly the signal to fall back to
180                // build-host
181                Ok(None) => {}
182                // Broken network or a corrupt asset: fall back as well. build-host
183                // goes through cargo, which is a different route from GitHub and may
184                // well work.
185                Err(_) => {}
186            }
187        }
188
189        build_host::install(self.config(), self.paths(), crate_name, version)
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::super::tests::{kit, place_plugin};
196    use super::*;
197
198    #[test]
199    fn uninstall_reports_a_plugin_that_is_not_installed() {
200        let tmp = tempfile::tempdir().unwrap();
201        let k = kit(&tmp.path().join("store"));
202
203        assert!(matches!(
204            k.uninstall("nope"),
205            Err(KitError::NotInstalled { .. })
206        ));
207    }
208
209    #[test]
210    fn uninstall_removes_the_directory() {
211        let tmp = tempfile::tempdir().unwrap();
212        let root = tmp.path().join("store");
213        let k = kit(&root);
214        let dir = place_plugin(&root, "myapp-plugin-foo");
215
216        assert!(dir.is_dir());
217        k.uninstall("foo").expect("should uninstall");
218        assert!(!dir.exists(), "the directory should have been deleted");
219        assert!(k.list().unwrap().is_empty());
220    }
221
222    /// A directory that is not a plugin crate is refused before anything is built.
223    #[test]
224    fn install_from_path_needs_a_cargo_manifest() {
225        let tmp = tempfile::tempdir().unwrap();
226        let root = tmp.path().join("store");
227        let k = kit(&root);
228
229        let checkout = tmp.path().join("checkout");
230        std::fs::create_dir_all(&checkout).unwrap();
231
232        match k.install_from_path(&checkout) {
233            Err(KitError::NoManifest { dir }) => {
234                assert!(dir.ends_with("checkout"), "{dir:?}")
235            }
236            other => panic!("expected NoManifest, got {other:?}"),
237        }
238    }
239
240    /// A crate without the manifest beside it is refused too — and again before the
241    /// compile, which is the point of checking up front.
242    #[test]
243    fn install_from_path_needs_the_manifest() {
244        let tmp = tempfile::tempdir().unwrap();
245        let root = tmp.path().join("store");
246        let k = kit(&root);
247
248        let checkout = tmp.path().join("checkout");
249        std::fs::create_dir_all(checkout.join("src")).unwrap();
250        std::fs::write(
251            checkout.join("Cargo.toml"),
252            "[package]\nname = \"myapp-plugin-foo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
253        )
254        .unwrap();
255
256        assert!(
257            k.install_from_path(&checkout).is_err(),
258            "a crate with no manifest is not a plugin checkout"
259        );
260    }
261
262    /// The same refusal an install from crates.io gives: one plugin name, one directory.
263    #[test]
264    fn install_from_path_refuses_when_already_installed() {
265        let tmp = tempfile::tempdir().unwrap();
266        let root = tmp.path().join("store");
267        let k = kit(&root);
268        place_plugin(&root, "myapp-plugin-foo");
269
270        let checkout = tmp.path().join("checkout");
271        std::fs::create_dir_all(checkout.join("src")).unwrap();
272        std::fs::write(
273            checkout.join("Cargo.toml"),
274            "[package]\nname = \"myapp-plugin-foo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
275        )
276        .unwrap();
277        std::fs::write(
278            checkout.join("myapp-plugin.toml"),
279            super::super::tests::MANIFEST,
280        )
281        .unwrap();
282
283        match k.install_from_path(&checkout) {
284            Err(KitError::AlreadyInstalled { name, .. }) => {
285                assert_eq!(name, "myapp-plugin-foo")
286            }
287            other => panic!("expected AlreadyInstalled, got {other:?}"),
288        }
289    }
290
291    /// `install` does not overwrite an existing installation — use `update` to
292    /// replace it.
293    ///
294    /// The check happens after the lock is taken and before any network or compile
295    /// work, so the test needs no network access.
296    #[test]
297    fn install_refuses_when_already_installed() {
298        let tmp = tempfile::tempdir().unwrap();
299        let root = tmp.path().join("store");
300        let k = kit(&root);
301        place_plugin(&root, "myapp-plugin-foo");
302
303        match k.install("foo", Some("0.1.0")) {
304            Err(KitError::AlreadyInstalled { name, .. }) => {
305                assert_eq!(name, "myapp-plugin-foo")
306            }
307            other => panic!("expected AlreadyInstalled, got {other:?}"),
308        }
309    }
310}