Skip to main content

cpa_plugin/
platform.rs

1//! Plugin file discovery and selection (internal/pluginhost/platform.go).
2//!
3//! Files are `<id>.<ext>` or `<id>-v<version>.<ext>` in `<dir>/<goos>/<goarch>` and then
4//! `<dir>`. The first directory to name an ID fixes its position; later files for the
5//! same ID replace the selection only when preferred (the desired version, else the
6//! higher version).
7
8use std::collections::{BTreeMap, HashMap, HashSet};
9use std::path::{Component, Path, PathBuf};
10
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct PluginFile {
13    pub id: String,
14    pub path: PathBuf,
15    pub version: String,
16}
17
18/// Go `pluginIDPattern`: `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`.
19pub fn valid_id(id: &str) -> bool {
20    let b = id.as_bytes();
21    !b.is_empty()
22        && b.len() <= 128
23        && b[0].is_ascii_alphanumeric()
24        && b[1..]
25            .iter()
26            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'_' | b'-'))
27}
28
29/// Go `validPluginVersion`: `^[0-9][0-9A-Za-z.+-]*$`.
30pub fn valid_version(version: &str) -> bool {
31    let b = version.as_bytes();
32    !b.is_empty()
33        && b[0].is_ascii_digit()
34        && b.iter()
35            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'.' | b'+' | b'-'))
36}
37
38/// Go `runtime.GOOS` for this build.
39pub fn goos() -> &'static str {
40    match std::env::consts::OS {
41        "macos" => "darwin",
42        other => other,
43    }
44}
45
46/// Go `runtime.GOARCH` for this build.
47pub fn goarch() -> &'static str {
48    match std::env::consts::ARCH {
49        "x86_64" => "amd64",
50        "aarch64" => "arm64",
51        "x86" => "386",
52        "loongarch64" => "loong64",
53        "powerpc64" if cfg!(target_endian = "little") => "ppc64le",
54        "powerpc64" => "ppc64",
55        other => other,
56    }
57}
58
59/// Go `PluginExtension`.
60pub fn extension(goos: &str) -> &'static str {
61    match goos {
62        "darwin" => ".dylib",
63        "windows" => ".dll",
64        _ => ".so",
65    }
66}
67
68/// Go `filepath.Clean`.
69pub fn clean(path: &Path) -> PathBuf {
70    let absolute = path.has_root();
71    let mut parts: Vec<&std::ffi::OsStr> = Vec::new();
72    for c in path.components() {
73        match c {
74            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
75            Component::ParentDir => {
76                if parts.last().is_some_and(|p| *p != "..") {
77                    parts.pop();
78                } else if !absolute {
79                    parts.push("..".as_ref());
80                }
81            }
82            Component::Normal(p) => parts.push(p),
83        }
84    }
85    let mut out = if absolute { PathBuf::from("/") } else { PathBuf::new() };
86    for p in parts {
87        out.push(p);
88    }
89    if out.as_os_str().is_empty() {
90        out.push(".");
91    }
92    out
93}
94
95/// Go `filepath.Rel` (Unix rules): `targ` relative to `base`, both cleaned first;
96/// `None` when one is absolute and the other is not, or `base` climbs past `targ`.
97/// ponytail: Windows volume names and case-insensitive elements are not handled; the
98/// plugin host only loads native plugins on Unix.
99pub fn rel(base: &str, targ: &str) -> Option<String> {
100    let base = clean(Path::new(base)).to_string_lossy().into_owned();
101    let targ = clean(Path::new(targ)).to_string_lossy().into_owned();
102    if targ == base {
103        return Some(".".into());
104    }
105    let base = if base == "." { String::new() } else { base };
106    if base.starts_with('/') != targ.starts_with('/') {
107        return None;
108    }
109    let (b, t) = (base.as_bytes(), targ.as_bytes());
110    let (mut b0, mut bi, mut t0, mut ti) = (0, 0, 0, 0);
111    loop {
112        while bi < b.len() && b[bi] != b'/' {
113            bi += 1;
114        }
115        while ti < t.len() && t[ti] != b'/' {
116            ti += 1;
117        }
118        if t[t0..ti] != b[b0..bi] {
119            break;
120        }
121        if bi < b.len() {
122            bi += 1;
123        }
124        if ti < t.len() {
125            ti += 1;
126        }
127        b0 = bi;
128        t0 = ti;
129    }
130    if &b[b0..bi] == b"..".as_slice() {
131        return None;
132    }
133    if b0 != b.len() {
134        let seps = b[b0..].iter().filter(|c| **c == b'/').count();
135        let mut out = String::from("..");
136        for _ in 0..seps {
137            out.push_str("/..");
138        }
139        if t0 != t.len() {
140            out.push('/');
141            out.push_str(&targ[t0..]);
142        }
143        return Some(clean(Path::new(&out)).to_string_lossy().into_owned());
144    }
145    Some(targ[t0..].to_owned())
146}
147
148/// Go `pluginFileFromPath`.
149pub fn file_from_path(path: &Path, required_extension: &str) -> Option<PluginFile> {
150    let base = path.file_name()?.to_string_lossy().into_owned();
151    let lower = base.to_ascii_lowercase();
152    let extension = if required_extension.trim().is_empty() {
153        [".so", ".dylib", ".dll"].into_iter().find(|e| lower.ends_with(e))?
154    } else {
155        let required = required_extension.trim().to_ascii_lowercase();
156        if !lower.ends_with(&required) {
157            return None;
158        }
159        return split_name(&base, required.len(), path);
160    };
161    split_name(&base, extension.len(), path)
162}
163
164fn split_name(base: &str, ext_len: usize, path: &Path) -> Option<PluginFile> {
165    let name = &base[..base.len() - ext_len];
166    let mut id = name.to_owned();
167    let mut version = String::new();
168    if let Some(i) = name.rfind("-v").filter(|i| *i > 0) {
169        let (candidate_id, candidate_version) = (&name[..i], &name[i + 2..]);
170        if valid_id(candidate_id) && valid_version(candidate_version) {
171            id = candidate_id.to_owned();
172            version = candidate_version.to_owned();
173        }
174    }
175    valid_id(&id).then(|| PluginFile {
176        id,
177        path: path.to_owned(),
178        version,
179    })
180}
181
182/// Go `comparePluginVersions`: dot-separated non-negative integers; `None` when either
183/// side has a non-numeric segment. Missing segments count as 0.
184pub fn compare_versions(a: &str, b: &str) -> Option<std::cmp::Ordering> {
185    let (sa, sb): (Vec<&str>, Vec<&str>) = (a.split('.').collect(), b.split('.').collect());
186    for i in 0..sa.len().max(sb.len()) {
187        let seg = |s: &[&str]| match s.get(i) {
188            None => Some(0),
189            Some(x) => x.parse::<i64>().ok().filter(|n| *n >= 0),
190        };
191        let (na, nb) = (seg(&sa)?, seg(&sb)?);
192        if na != nb {
193            return Some(na.cmp(&nb));
194        }
195    }
196    Some(std::cmp::Ordering::Equal)
197}
198
199/// Go `pluginFilePreferred`.
200fn preferred(candidate: &PluginFile, current: &PluginFile) -> bool {
201    if candidate.version.is_empty() {
202        return false;
203    }
204    if current.version.is_empty() {
205        return true;
206    }
207    match compare_versions(&candidate.version, &current.version) {
208        Some(ordering) => ordering.is_gt(),
209        None => candidate.version > current.version,
210    }
211}
212
213/// Go `pluginFilePreferredForDesired`.
214fn preferred_for_desired(candidate: &PluginFile, current: &PluginFile, desired: &str) -> bool {
215    let desired = crate::config::normalize_version(desired);
216    if !desired.is_empty() {
217        let (cm, um) = (candidate.version == desired, current.version == desired);
218        if cm != um {
219            return cm;
220        }
221    }
222    preferred(candidate, current)
223}
224
225/// Go `candidateDirs`.
226pub fn candidate_dirs(root: &Path, goos: &str, goarch: &str) -> [PathBuf; 2] {
227    [root.join(goos).join(goarch), root.to_owned()]
228}
229
230/// Go `selectPluginFilesWithCandidates`: the selected file per ID (in first-seen order)
231/// and every candidate. An ID whose desired version has no file is not selected.
232pub fn select_with_candidates(
233    root: &Path,
234    desired: &BTreeMap<String, String>,
235) -> std::io::Result<(Vec<PluginFile>, Vec<PluginFile>)> {
236    let root = if root.as_os_str().is_empty() {
237        Path::new("plugins")
238    } else {
239        root
240    };
241    let desired: HashMap<String, String> = desired
242        .iter()
243        .filter_map(|(id, v)| {
244            let (id, v) = (id.trim(), crate::config::normalize_version(v));
245            (!id.is_empty() && !v.is_empty()).then(|| (id.to_owned(), v))
246        })
247        .collect();
248    let extension = extension(goos());
249    let mut selected: HashMap<String, PluginFile> = HashMap::new();
250    let mut order: Vec<String> = Vec::new();
251    let mut all = Vec::new();
252    for dir in candidate_dirs(root, goos(), goarch()) {
253        let entries = match std::fs::read_dir(&dir) {
254            Ok(entries) => entries,
255            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
256            Err(e) => return Err(e),
257        };
258        let mut files: Vec<PathBuf> = Vec::new();
259        for entry in entries {
260            let entry = entry?;
261            // Go's DirEntry type is lstat-based: symlinks are not regular files.
262            if !entry.file_type()?.is_file() {
263                continue;
264            }
265            if entry
266                .file_name()
267                .to_string_lossy()
268                .to_ascii_lowercase()
269                .ends_with(extension)
270            {
271                files.push(dir.join(entry.file_name()));
272            }
273        }
274        files.sort_by(|a, b| a.as_os_str().as_encoded_bytes().cmp(b.as_os_str().as_encoded_bytes()));
275        for path in files {
276            let Some(file) = file_from_path(&path, extension) else {
277                continue;
278            };
279            all.push(file.clone());
280            match selected.get(&file.id) {
281                None => {
282                    order.push(file.id.clone());
283                    selected.insert(file.id.clone(), file);
284                }
285                Some(current) => {
286                    let want = desired.get(&file.id).map(String::as_str).unwrap_or_default();
287                    if preferred_for_desired(&file, current, want) {
288                        selected.insert(file.id.clone(), file);
289                    }
290                }
291            }
292        }
293    }
294    let picked = order
295        .into_iter()
296        .filter_map(|id| {
297            let file = selected.remove(&id)?;
298            match desired.get(&id) {
299                Some(want) if file.version != *want => None,
300                _ => Some(file),
301            }
302        })
303        .collect();
304    Ok((picked, all))
305}
306
307/// Go `selectPluginFiles` / `DiscoverPluginFiles`.
308pub fn discover(root: &Path, desired: &BTreeMap<String, String>) -> std::io::Result<Vec<PluginFile>> {
309    select_with_candidates(root, desired).map(|(selected, _)| selected)
310}
311
312/// Go `cleanupUnselectedPluginFiles`: removes other versions of plugins that loaded.
313pub fn cleanup_unselected(root: &Path, loaded: &[PluginFile]) -> Result<(), String> {
314    if loaded.is_empty() {
315        return Ok(());
316    }
317    let (_, candidates) = select_with_candidates(root, &BTreeMap::new()).map_err(|e| e.to_string())?;
318    let mut keep: HashMap<&str, HashSet<PathBuf>> = HashMap::new();
319    for file in loaded {
320        if !file.id.trim().is_empty() && !file.path.as_os_str().is_empty() {
321            keep.entry(file.id.as_str()).or_default().insert(clean(&file.path));
322        }
323    }
324    let mut errors = Vec::new();
325    for candidate in candidates {
326        let Some(paths) = keep.get(candidate.id.as_str()) else {
327            continue;
328        };
329        if paths.contains(&clean(&candidate.path)) {
330            continue;
331        }
332        match std::fs::remove_file(&candidate.path) {
333            Ok(()) => {
334                tracing::info!(plugin_id = %candidate.id, version = %candidate.version, path = %candidate.path.display(), "pluginhost: old plugin file removed")
335            }
336            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
337            Err(e) => {
338                tracing::warn!(path = %candidate.path.display(), "pluginhost: failed to remove old plugin file {}: {e}", candidate.path.display());
339                errors.push(e.to_string());
340            }
341        }
342    }
343    if errors.is_empty() {
344        Ok(())
345    } else {
346        Err(errors.join("\n"))
347    }
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353
354    #[test]
355    fn names_and_versions_follow_go() {
356        let f = file_from_path(Path::new("/p/my-plugin-v1.2.0.SO"), "").unwrap();
357        assert_eq!((f.id.as_str(), f.version.as_str()), ("my-plugin", "1.2.0"));
358        let f = file_from_path(Path::new("/p/a-vbeta.so"), ".so").unwrap();
359        assert_eq!((f.id.as_str(), f.version.as_str()), ("a-vbeta", ""));
360        assert!(file_from_path(Path::new("/p/-v1.so"), ".so").is_none());
361        assert!(file_from_path(Path::new("/p/a.dll"), ".so").is_none());
362        assert_eq!(compare_versions("1.10", "1.9"), Some(std::cmp::Ordering::Greater));
363        assert_eq!(compare_versions("1.0", "1"), Some(std::cmp::Ordering::Equal));
364        assert_eq!(compare_versions("1.0-rc1", "1.0"), None);
365        assert!(valid_id("a.b_c-d") && !valid_id(".a") && !valid_id(&"a".repeat(129)));
366    }
367
368    /// Go `TestSelectPluginFiles*`: the arch directory fixes order, the highest version
369    /// wins, a desired version wins over a higher one and hides the ID when missing.
370    #[test]
371    fn selection_prefers_desired_then_highest() {
372        let root = std::env::temp_dir().join(format!("cpa-plugin-select-{}", std::process::id()));
373        let arch = root.join(goos()).join(goarch());
374        std::fs::create_dir_all(&arch).unwrap();
375        let ext = extension(goos());
376        for name in ["b-v1.0.0", "b-v1.10.0", "a", "c-v2.0.0"] {
377            std::fs::write(root.join(format!("{name}{ext}")), b"").unwrap();
378        }
379        std::fs::write(arch.join(format!("z-v0.1.0{ext}")), b"").unwrap();
380        let pick = |desired: &[(&str, &str)]| {
381            let desired = desired.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
382            discover(&root, &desired)
383                .unwrap()
384                .into_iter()
385                .map(|f| format!("{}@{}", f.id, f.version))
386                .collect::<Vec<_>>()
387        };
388        assert_eq!(pick(&[]), ["z@0.1.0", "a@", "b@1.10.0", "c@2.0.0"]);
389        assert_eq!(pick(&[("b", "v1.0.0"), ("c", "3.0.0")]), ["z@0.1.0", "a@", "b@1.0.0"]);
390        let loaded = discover(&root, &[("b".to_owned(), "1.0.0".to_owned())].into()).unwrap();
391        cleanup_unselected(&root, &loaded).unwrap();
392        assert!(!root.join(format!("b-v1.10.0{ext}")).exists());
393        assert!(root.join(format!("b-v1.0.0{ext}")).exists());
394        let _ = std::fs::remove_dir_all(&root);
395    }
396}