Skip to main content

crate_plugin_kit/install/
prebuilt.rs

1//! prebuilt:从 GitHub Releases 直接下载 cdylib + manifest。
2//!
3//! 这是**加速路径**,不是默认路径。因为它走的是 GitHub,会绕开用户已经配好的
4//! cargo registry / 镜像 —— 国内环境往往连不上。所以:
5//!
6//! - 默认仍然是 build-host(走 `cargo build`,天然吃镜像配置);
7//! - prebuilt 只在前者被显式关闭、或调用方想"先试试能不能省几分钟"时用;
8//! - 任何一步拿到 `None` 都表示"没有可用的 prebuilt",调用方**必须回落 build-host**。
9//!
10//! # 产物命名约定
11//!
12//! Release 里放**两个裸文件**(不是压缩包,省掉 tar/gzip/zip 三个依赖):
13//!
14//! ```text
15//! {crate}-{version}-{target}.{so|dylib|dll}   ← cdylib 本体
16//! {crate}-{version}-{target}.toml             ← manifest
17//! ```
18//!
19//! 例:`bmux-plugin-cargo-0.1.0-x86_64-pc-windows-msvc.dll`
20//!
21//! 仓库地址从 **crates.io 的 `repository` 字段**取 —— 因为此时插件还没装上,
22//! 我们唯一能问的就是 registry。
23
24use std::path::PathBuf;
25
26use crate::cache::InstallSource;
27use crate::config::{KitConfig, KitPaths};
28use crate::error::{KitError, KitResult};
29use crate::install::{remove_dir_if_exists, Installed};
30use crate::manifest::PluginManifest;
31use crate::registry::Registry;
32
33/// 单个产物的大小上限。防着"下到一个几百 MB 的东西"。
34const MAX_ASSET_BYTES: u64 = 128 * 1024 * 1024;
35
36/// 试装 prebuilt。
37///
38/// - `Ok(Some(_))`:装好了。
39/// - `Ok(None)`:没有可用的 prebuilt(没发、或者资产缺失),**调用方应回落 build-host**。
40/// - `Err(_)`:网络之类的硬错误。调用方**仍然可以**选择回落,但值得先把错误透出去。
41pub fn try_install(
42    cfg: &KitConfig,
43    paths: &KitPaths,
44    registry: &Registry,
45    crate_name: &str,
46    version: &str,
47) -> KitResult<Option<Installed>> {
48    // ① 仓库地址只能问 registry
49    let Some(info) = registry.view(crate_name)? else {
50        return Ok(None);
51    };
52    let Some(repo) = info.repository.as_deref() else {
53        return Ok(None);
54    };
55    let Some((owner, name)) = parse_github_repo(repo) else {
56        // 不是 GitHub 就没有我们能猜的 Release URL
57        return Ok(None);
58    };
59
60    let target = cfg.effective_target();
61    let ext = platform_lib_ext();
62    let base = format!("https://github.com/{owner}/{name}/releases/download/v{version}/{crate_name}-{version}-{target}");
63
64    let lib_url = format!("{base}.{ext}");
65    let manifest_url = format!("{base}.toml");
66
67    // ② 先取 cdylib。404 就是"没发 prebuilt"。
68    let Some(lib_bytes) = registry.try_download(&lib_url, MAX_ASSET_BYTES)? else {
69        return Ok(None);
70    };
71
72    // ③ manifest 必须一起发出来。缺了它这个 prebuilt 不可用 ——
73    //    没有 manifest 就没法检测,装了也白装。
74    let Some(manifest_bytes) = registry.try_download(&manifest_url, MAX_ASSET_BYTES)? else {
75        return Ok(None);
76    };
77
78    // ④ 内容要自洽:manifest 里写的名字和版本必须就是我们下的那个
79    let manifest_text = String::from_utf8(manifest_bytes)
80        .map_err(|e| KitError::Registry(format!("{manifest_url} 不是合法 UTF-8:{e}")))?;
81    let manifest = PluginManifest::parse(&manifest_text, &PathBuf::from(&manifest_url))?;
82
83    if manifest.plugin.version != version {
84        return Err(KitError::Registry(format!(
85            "prebuilt manifest 版本不符:资产声明 {},要装的是 {version}",
86            manifest.plugin.version
87        )));
88    }
89
90    // ⑤ 落地
91    let plugin_dir = paths.plugin_dir(crate_name);
92    remove_dir_if_exists(&plugin_dir)?;
93    std::fs::create_dir_all(&plugin_dir)?;
94
95    let lib_name = format!("{}.{ext}", manifest.effective_lib_stem(cfg, crate_name));
96    let dest_lib = plugin_dir.join(&lib_name);
97    std::fs::write(&dest_lib, lib_bytes)?;
98
99    manifest.write(&paths.manifest_path(crate_name, &cfg.manifest_name))?;
100
101    Ok(Some(Installed {
102        crate_name: crate_name.to_string(),
103        version: version.to_string(),
104        dir: plugin_dir,
105        library: dest_lib,
106        source: InstallSource::Prebuilt,
107    }))
108}
109
110/// 当前平台的 cdylib 扩展名。
111fn platform_lib_ext() -> &'static str {
112    match std::env::consts::OS {
113        "windows" => "dll",
114        "macos" => "dylib",
115        _ => "so",
116    }
117}
118
119/// 从 GitHub URL 里取出 `(owner, repo)`。
120///
121/// 认这些形态:
122///
123/// ```text
124/// https://github.com/owner/repo
125/// https://github.com/owner/repo.git
126/// https://github.com/owner/repo/
127/// git+https://github.com/owner/repo
128/// ```
129pub fn parse_github_repo(url: &str) -> Option<(String, String)> {
130    let rest = url
131        .trim()
132        .strip_prefix("git+")
133        .unwrap_or(url)
134        .strip_prefix("https://github.com/")
135        .or_else(|| url.strip_prefix("http://github.com/"))?;
136
137    let mut parts = rest.trim_end_matches('/').split('/');
138    let owner = parts.next()?.trim();
139    let repo = parts.next()?.trim().trim_end_matches(".git");
140
141    if owner.is_empty() || repo.is_empty() {
142        return None;
143    }
144    Some((owner.to_string(), repo.to_string()))
145}
146
147#[cfg(test)]
148mod tests {
149    use super::parse_github_repo;
150
151    #[test]
152    fn parses_common_forms() {
153        let want = Some(("imba97".to_string(), "bmux-plugin-cargo".to_string()));
154        assert_eq!(
155            parse_github_repo("https://github.com/imba97/bmux-plugin-cargo"),
156            want
157        );
158        assert_eq!(
159            parse_github_repo("https://github.com/imba97/bmux-plugin-cargo.git"),
160            want
161        );
162        assert_eq!(
163            parse_github_repo("https://github.com/imba97/bmux-plugin-cargo/"),
164            want
165        );
166        assert_eq!(
167            parse_github_repo("git+https://github.com/imba97/bmux-plugin-cargo"),
168            want
169        );
170    }
171
172    #[test]
173    fn rejects_non_github() {
174        assert_eq!(parse_github_repo("https://gitlab.com/a/b"), None);
175        assert_eq!(parse_github_repo("https://github.com/onlyowner"), None);
176    }
177}