Skip to main content

crate_plugin_kit/store/
list.rs

1//! Queries: what is installed, and what crates.io has.
2//!
3//! These never take the lock and never write: they read the plugin directories under
4//! `<data-dir>/plugins`, and the last two forward to the registry.
5
6use std::path::{Path, PathBuf};
7
8use crate::cache::Index;
9use crate::error::KitResult;
10use crate::manifest::PluginManifest;
11use crate::registry::{CrateInfo, CrateSummary};
12
13use super::{CratePluginKit, PluginInfo};
14
15impl<T> CratePluginKit<T> {
16    /// Lists the installed plugins.
17    ///
18    /// The manifests on disk are authoritative; `.plugins.json` only supplies
19    /// information the manifest does not carry, such as the source and install time.
20    /// A lost cache therefore never hides a plugin.
21    pub fn list(&self) -> KitResult<Vec<PluginInfo>> {
22        let idx = Index::load(&self.paths.index_file);
23        let mut out = Vec::new();
24
25        let entries = match std::fs::read_dir(&self.paths.plugins) {
26            Ok(e) => e,
27            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
28            Err(e) => return Err(e.into()),
29        };
30
31        for entry in entries {
32            let entry = entry?;
33            if !entry.file_type()?.is_dir() {
34                continue;
35            }
36            let crate_name = entry.file_name().to_string_lossy().into_owned();
37
38            // The directory is there but the manifest is missing or broken: skip it,
39            // so one bad plugin cannot make the whole list fail
40            let manifest_path = entry.path().join(&self.cfg.manifest_name);
41            let Ok(manifest) = PluginManifest::read(&manifest_path) else {
42                continue;
43            };
44
45            let source = idx
46                .get(&crate_name)
47                .map(|e| e.source.clone())
48                .unwrap_or_default();
49
50            // Broken apart rather than cloned: the summary and the host's own sections
51            // are all this read is for, so nothing is copied on the way out.
52            let PluginManifest { plugin, extra, .. } = manifest;
53
54            out.push(PluginInfo {
55                name: plugin.name,
56                crate_name,
57                version: plugin.version,
58                family: plugin.family,
59                abi: plugin.abi,
60                dir: entry.path(),
61                source,
62                extra,
63            });
64        }
65
66        out.sort_by(|a, b| a.crate_name.cmp(&b.crate_name));
67        Ok(out)
68    }
69
70    /// Reads the manifest of one plugin.
71    pub fn manifest_of(&self, name: &str) -> KitResult<PluginManifest> {
72        let crate_name = self.cfg.normalize_crate_name(name);
73        let path = self
74            .paths
75            .manifest_path(&crate_name, &self.cfg.manifest_name);
76        PluginManifest::read(&path)
77    }
78
79    /// Resolves a path relative to `name` into an absolute path.
80    pub fn resolve(&self, name: &str, relative: impl AsRef<Path>) -> PathBuf {
81        let crate_name = self.cfg.normalize_crate_name(name);
82        self.paths.plugin_dir(&crate_name).join(relative)
83    }
84
85    /// Searches for crates.
86    pub fn search(&self, keyword: &str, limit: usize) -> KitResult<Vec<CrateSummary>> {
87        self.registry.search(keyword, limit)
88    }
89
90    /// Looks up a crate by exact name.
91    pub fn view(&self, name: &str) -> KitResult<Option<CrateInfo>> {
92        let crate_name = self.cfg.normalize_crate_name(name);
93        self.registry.view(&crate_name)
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::super::tests::{kit, place_plugin};
100    use crate::cache::InstallSource;
101    use crate::error::KitError;
102
103    /// A host's own sections come back with the summary.
104    ///
105    /// This is what saves a host a second read of the manifest: it asked the kit what is
106    /// installed, so the kit hands over the sections it read on the way -- `[detect]` here,
107    /// which the kit itself has no opinion about.
108    #[test]
109    fn the_hosts_own_sections_come_back_with_the_summary() {
110        let tmp = tempfile::tempdir().unwrap();
111        let root = tmp.path().join("store");
112        place_plugin(&root, "myapp-plugin-foo");
113
114        let k = kit(&root);
115        let infos = k.list().unwrap();
116
117        assert_eq!(infos.len(), 1);
118        let strong = infos[0]
119            .extra
120            .get("detect")
121            .and_then(|detect| detect.get("strong"))
122            .and_then(|strong| strong.as_array())
123            .expect("the [detect] section has to survive the listing");
124        assert_eq!(strong.len(), 1);
125        assert_eq!(strong[0].as_str(), Some("fake.lock"));
126
127        assert_eq!(infos[0].name, "foo");
128        assert_eq!(infos[0].family.as_deref(), Some("node"));
129        assert_eq!(infos[0].abi, Some(1));
130    }
131
132    #[test]
133    fn a_fresh_store_lists_nothing() {
134        let tmp = tempfile::tempdir().unwrap();
135        let k = kit(&tmp.path().join("store"));
136        assert!(k.list().unwrap().is_empty());
137    }
138
139    /// When the directory does not exist at all, `list` still returns an empty list
140    /// instead of an error.
141    #[test]
142    fn list_tolerates_a_missing_plugins_directory() {
143        let tmp = tempfile::tempdir().unwrap();
144        let root = tmp.path().join("store");
145        let k = kit(&root);
146
147        std::fs::remove_dir_all(&root).unwrap();
148        assert!(k.list().unwrap().is_empty());
149    }
150
151    /// Key behavior: the manifest on disk is the source of truth, not
152    /// `.plugins.json`. A plugin placed by hand (with no cache entry) must still be
153    /// listed.
154    #[test]
155    fn list_reads_manifests_from_disk_not_the_cache() {
156        let tmp = tempfile::tempdir().unwrap();
157        let root = tmp.path().join("store");
158        let k = kit(&root);
159
160        place_plugin(&root, "myapp-plugin-foo");
161
162        let all = k.list().unwrap();
163        assert_eq!(all.len(), 1, "the cache is empty but the disk has a plugin");
164        let info = &all[0];
165        assert_eq!(info.name, "foo");
166        assert_eq!(info.crate_name, "myapp-plugin-foo");
167        assert_eq!(info.version, "0.1.0");
168        assert_eq!(info.abi, Some(1));
169        assert_eq!(info.family.as_deref(), Some("node"));
170        // No cache entry → falls back to the default source
171        assert_eq!(info.source, InstallSource::BuildHost);
172    }
173
174    /// A broken manifest must not fail the whole `list()` — skipping it is enough.
175    #[test]
176    fn list_skips_a_directory_with_a_broken_manifest() {
177        let tmp = tempfile::tempdir().unwrap();
178        let root = tmp.path().join("store");
179        let k = kit(&root);
180
181        place_plugin(&root, "myapp-plugin-good");
182        let bad = root.join("plugins").join("myapp-plugin-bad");
183        std::fs::create_dir_all(&bad).unwrap();
184        std::fs::write(bad.join("myapp-plugin.toml"), "this is not toml").unwrap();
185
186        // A directory that does not even have a manifest
187        let empty = root.join("plugins").join("myapp-plugin-empty");
188        std::fs::create_dir_all(&empty).unwrap();
189
190        let all = k.list().unwrap();
191        assert_eq!(all.len(), 1, "only the good one should be listed: {all:?}");
192        assert_eq!(all[0].crate_name, "myapp-plugin-good");
193    }
194
195    #[test]
196    fn list_is_sorted_by_crate_name() {
197        let tmp = tempfile::tempdir().unwrap();
198        let root = tmp.path().join("store");
199        let k = kit(&root);
200
201        for name in ["myapp-plugin-c", "myapp-plugin-a", "myapp-plugin-b"] {
202            place_plugin(&root, name);
203        }
204
205        let names: Vec<_> = k
206            .list()
207            .unwrap()
208            .into_iter()
209            .map(|i| i.crate_name)
210            .collect();
211        assert_eq!(
212            names,
213            vec!["myapp-plugin-a", "myapp-plugin-b", "myapp-plugin-c"]
214        );
215    }
216
217    #[test]
218    fn manifest_of_reads_the_plugin() {
219        let tmp = tempfile::tempdir().unwrap();
220        let root = tmp.path().join("store");
221        let k = kit(&root);
222        place_plugin(&root, "myapp-plugin-foo");
223
224        let m = k
225            .manifest_of("foo")
226            .expect("the short name should work too");
227        assert_eq!(m.plugin.name, "foo");
228        assert!(m.extra.contains_key("detect"), "the host's section is kept");
229    }
230
231    #[test]
232    fn manifest_of_reports_a_missing_plugin() {
233        let tmp = tempfile::tempdir().unwrap();
234        let k = kit(&tmp.path().join("store"));
235        assert!(matches!(
236            k.manifest_of("nope"),
237            Err(KitError::ManifestRead { .. })
238        ));
239    }
240
241    #[test]
242    fn resolve_points_into_the_plugin_directory() {
243        let tmp = tempfile::tempdir().unwrap();
244        let root = tmp.path().join("store");
245        let k = kit(&root);
246
247        assert_eq!(
248            k.resolve("foo", "extra.txt"),
249            root.join("plugins")
250                .join("myapp-plugin-foo")
251                .join("extra.txt")
252        );
253        // The short and the full name must land in the same place
254        assert_eq!(k.resolve("foo", "x"), k.resolve("myapp-plugin-foo", "x"));
255    }
256}