Skip to main content

crate_plugin_kit/install/
prebuilt.rs

1//! prebuilt: downloads a cdylib plus manifest straight from GitHub Releases.
2//!
3//! This is an accelerator path, not the default. It goes through GitHub, which
4//! bypasses the cargo registry or mirror the user has configured, so it may not be
5//! reachable:
6//!
7//! - the default stays build-host (`cargo build`, which naturally picks up the mirror
8//!   configuration);
9//! - prebuilt is only used when build-host is explicitly turned off, or when the
10//!   caller wants to try saving a few minutes first;
11//! - a `None` from any step means "no usable prebuilt", and the caller must fall back
12//!   to build-host.
13//!
14//! # Artifact naming convention
15//!
16//! A release carries two bare files (not archives, which saves three dependencies —
17//! tar/gzip/zip):
18//!
19//! ```text
20//! {crate}-{version}-{target}.{so|dylib|dll}   <-- the cdylib itself
21//! {crate}-{version}-{target}.toml             <-- the manifest
22//! ```
23//!
24//! Example: `bmux-plugin-cargo-0.1.0-x86_64-pc-windows-msvc.dll`
25//!
26//! The repository URL comes from the crates.io `repository` field — at this point the
27//! plugin is not installed yet, so the registry is the only thing we can ask.
28
29use std::path::PathBuf;
30
31use crate::cache::InstallSource;
32use crate::config::{KitConfig, KitPaths};
33use crate::error::{KitError, KitResult};
34use crate::install::{remove_dir_if_exists, Installed};
35use crate::manifest::PluginManifest;
36use crate::registry::Registry;
37
38/// Size limit for a single artifact. Guards against downloading something hundreds of
39/// megabytes large.
40const MAX_ASSET_BYTES: u64 = 128 * 1024 * 1024;
41
42/// Tries to install a prebuilt.
43///
44/// - `Ok(Some(_))`: installed.
45/// - `Ok(None)`: no usable prebuilt (none published, or assets missing); the caller
46///   should fall back to build-host.
47/// - `Err(_)`: a hard error such as a network failure. The caller may still fall back,
48///   but the error is worth surfacing first.
49pub fn try_install(
50    cfg: &KitConfig,
51    paths: &KitPaths,
52    registry: &Registry,
53    crate_name: &str,
54    version: &str,
55) -> KitResult<Option<Installed>> {
56    // 1. the repository URL can only come from the registry
57    let Some(info) = registry.view(crate_name)? else {
58        return Ok(None);
59    };
60    let Some(repo) = info.repository.as_deref() else {
61        return Ok(None);
62    };
63    let Some((owner, name)) = parse_github_repo(repo) else {
64        // Not GitHub, so there is no release URL we could guess
65        return Ok(None);
66    };
67
68    let target = cfg.effective_target();
69    let ext = platform_lib_ext();
70    let base = format!("https://github.com/{owner}/{name}/releases/download/v{version}/{crate_name}-{version}-{target}");
71
72    let lib_url = format!("{base}.{ext}");
73    let manifest_url = format!("{base}.toml");
74
75    // 2. fetch the cdylib first. A 404 means "no prebuilt was published".
76    let Some(lib_bytes) = registry.try_download(&lib_url, MAX_ASSET_BYTES)? else {
77        return Ok(None);
78    };
79
80    // 3. the manifest has to be published alongside it. Without it this prebuilt is
81    //    unusable — no manifest means nothing can be detected, so installing it
82    //    achieves nothing.
83    let Some(manifest_bytes) = registry.try_download(&manifest_url, MAX_ASSET_BYTES)? else {
84        return Ok(None);
85    };
86
87    // 4. the contents have to be consistent: the name and version in the manifest must
88    //    be the ones we just downloaded
89    let manifest_text = String::from_utf8(manifest_bytes)
90        .map_err(|e| KitError::Registry(format!("{manifest_url} is not valid UTF-8: {e}")))?;
91    let manifest = PluginManifest::parse(&manifest_text, &PathBuf::from(&manifest_url))?;
92
93    if manifest.plugin.version != version {
94        return Err(KitError::Registry(format!(
95            "prebuilt manifest version mismatch: the asset declares {}, but {version} was requested",
96            manifest.plugin.version
97        )));
98    }
99
100    // 5. land it
101    let plugin_dir = paths.plugin_dir(crate_name);
102    remove_dir_if_exists(&plugin_dir)?;
103    std::fs::create_dir_all(&plugin_dir)?;
104
105    let lib_name = format!("{}.{ext}", manifest.effective_lib_stem(cfg, crate_name));
106    let dest_lib = plugin_dir.join(&lib_name);
107    std::fs::write(&dest_lib, lib_bytes)?;
108
109    manifest.write(&paths.manifest_path(crate_name, &cfg.manifest_name))?;
110
111    Ok(Some(Installed {
112        crate_name: crate_name.to_string(),
113        version: version.to_string(),
114        dir: plugin_dir,
115        library: dest_lib,
116        source: InstallSource::Prebuilt,
117    }))
118}
119
120/// cdylib extension for the current platform.
121fn platform_lib_ext() -> &'static str {
122    match std::env::consts::OS {
123        "windows" => "dll",
124        "macos" => "dylib",
125        _ => "so",
126    }
127}
128
129/// Extracts `(owner, repo)` from a GitHub URL.
130///
131/// These forms are recognized:
132///
133/// ```text
134/// https://github.com/owner/repo
135/// https://github.com/owner/repo.git
136/// https://github.com/owner/repo/
137/// git+https://github.com/owner/repo
138/// ```
139pub fn parse_github_repo(url: &str) -> Option<(String, String)> {
140    let rest = url
141        .trim()
142        .strip_prefix("git+")
143        .unwrap_or(url)
144        .strip_prefix("https://github.com/")
145        .or_else(|| url.strip_prefix("http://github.com/"))?;
146
147    let mut parts = rest.trim_end_matches('/').split('/');
148    let owner = parts.next()?.trim();
149    let repo = parts.next()?.trim().trim_end_matches(".git");
150
151    if owner.is_empty() || repo.is_empty() {
152        return None;
153    }
154    Some((owner.to_string(), repo.to_string()))
155}
156
157#[cfg(test)]
158mod tests {
159    use super::parse_github_repo;
160
161    #[test]
162    fn parses_common_forms() {
163        let want = Some(("imba97".to_string(), "bmux-plugin-cargo".to_string()));
164        assert_eq!(
165            parse_github_repo("https://github.com/imba97/bmux-plugin-cargo"),
166            want
167        );
168        assert_eq!(
169            parse_github_repo("https://github.com/imba97/bmux-plugin-cargo.git"),
170            want
171        );
172        assert_eq!(
173            parse_github_repo("https://github.com/imba97/bmux-plugin-cargo/"),
174            want
175        );
176        assert_eq!(
177            parse_github_repo("git+https://github.com/imba97/bmux-plugin-cargo"),
178            want
179        );
180    }
181
182    #[test]
183    fn rejects_non_github() {
184        assert_eq!(parse_github_repo("https://gitlab.com/a/b"), None);
185        assert_eq!(parse_github_repo("https://github.com/onlyowner"), None);
186    }
187}