Skip to main content

crate_plugin_kit/pack/
mod.rs

1//! Producing the two files a plugin release carries.
2//!
3//! This is the mirror image of [`crate::install`]: instead of turning a published crate
4//! into a cdylib on the user's machine, it turns a checkout into the assets that let
5//! [`crate::install::prebuilt`] skip the build entirely.
6//!
7//! ```text
8//! {crate}-{version}-{target}.{so|dylib|dll}   <-- the cdylib
9//! {crate}-{version}-{target}.toml             <-- the plugin manifest, verbatim
10//! ```
11//!
12//! # Why these names
13//!
14//! [`crate::install::prebuilt`] builds its download URL by putting these two names after
15//! `.../releases/download/v{version}/`. Producing and consuming are one convention:
16//! change either side alone and every release silently falls back to building from
17//! source. Nothing here may be renamed without renaming it there too.
18//!
19//! # What it does
20//!
21//! 1. `cargo metadata` the plugin's manifest, for the crate name and version.
22//! 2. Check that the plugin manifest beside it declares the same version — a manifest
23//!    that lags behind `Cargo.toml` would publish assets nobody can consume.
24//! 3. Generate the wrapper — the same one [`crate::install`] builds, coming from the
25//!    private `wrapper` module — with the plugin as a **path** dependency, and
26//!    `cargo build --release --target <triple>` it.
27//! 4. Copy the cdylib and the plugin manifest into the output directory under the names
28//!    above, and — when the build target is this machine — `dlopen` the result to prove
29//!    it really exports the entry symbol.
30//!
31//! A failed build leaves the generated wrapper in the temp directory, which is where
32//! someone looks to see why; a successful one removes it again.
33//!
34//! # Layout
35//!
36//! The naming convention above is written down once, in [`PackedAssets::base_name`].
37//! `naming` says where the generated wrapper is built, which is a lifetime question
38//! rather than a naming one.
39
40use std::path::{Path, PathBuf};
41use std::process::Command;
42
43use crate::config::KitConfig;
44use crate::error::{KitError, KitResult};
45use crate::install::remove_dir_if_exists;
46use crate::manifest::PluginManifest;
47use crate::wrapper::{self, cargo_metadata_json, declared_contract_dep, PluginSource};
48
49mod naming;
50
51use naming::wrapper_dir;
52
53/// Options for [`build`].
54#[derive(Debug, Clone)]
55pub struct PackOptions {
56    /// Where cargo puts its build.
57    ///
58    /// `None` uses `<plugin dir>/target`, which is the directory a CI cache action
59    /// normally keeps — so the dependency builds are cached between releases.
60    pub target_dir: Option<PathBuf>,
61
62    /// `dlopen` the finished cdylib and look for the entry symbol.
63    ///
64    /// Defaults to `true`. It only happens when the build target is the machine doing
65    /// the packing: a cross-compiled artifact cannot be loaded here, so that case is
66    /// skipped silently rather than reported as a failure.
67    pub verify_export: bool,
68}
69
70impl Default for PackOptions {
71    fn default() -> Self {
72        Self {
73            target_dir: None,
74            verify_export: true,
75        }
76    }
77}
78
79/// The two files that were written.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct PackedAssets {
82    /// Full crate name, such as `bmux-plugin-cargo`.
83    pub crate_name: String,
84    /// The crate's own version.
85    pub version: String,
86    /// Target triple the cdylib was built for.
87    pub target: String,
88    /// Path of the written cdylib.
89    pub library: PathBuf,
90    /// Path of the written manifest.
91    pub manifest: PathBuf,
92}
93
94impl PackedAssets {
95    /// The base name both files share: `{crate}-{version}-{target}`.
96    pub fn base_name(&self) -> String {
97        format!("{}-{}-{}", self.crate_name, self.version, self.target)
98    }
99}
100
101/// Builds a plugin checkout into the two files a release carries.
102///
103/// `cfg` supplies the naming rules (it is the same [`KitConfig`] the host installs
104/// with); `plugin_dir` is the root of the plugin crate; `out_dir` is created if needed.
105///
106/// # Errors
107///
108/// - [`KitError::CargoNotFound`]: no `cargo` on `PATH`;
109/// - [`KitError::NoManifest`]: no `Cargo.toml` in `plugin_dir`;
110/// - [`KitError::NoPackage`]: `cargo metadata` did not describe that manifest;
111/// - [`KitError::ManifestMissingField`] / [`KitError::ManifestParse`]: the plugin
112///   manifest is missing or unreadable;
113/// - [`KitError::VersionMismatch`]: the plugin manifest and `Cargo.toml` disagree;
114/// - [`KitError::BuildFailed`] / [`KitError::BuildArtifactMissing`]: the wrapper build
115///   failed or produced nothing loadable;
116/// - [`KitError::LibraryLoad`] / [`KitError::SymbolMissing`]: the artifact does not
117///   export the entry symbol, so publishing it would produce an unloadable plugin.
118pub fn build(
119    cfg: &KitConfig,
120    plugin_dir: impl AsRef<Path>,
121    out_dir: impl AsRef<Path>,
122    options: &PackOptions,
123) -> KitResult<PackedAssets> {
124    let cargo = which::which("cargo").map_err(|_| KitError::CargoNotFound)?;
125
126    let plugin_dir = plugin_dir.as_ref().canonicalize()?;
127    let manifest_path = plugin_dir.join("Cargo.toml");
128    if !manifest_path.is_file() {
129        return Err(KitError::NoManifest { dir: plugin_dir });
130    }
131
132    // 1. what the crate calls itself, and which version this is
133    let metadata = cargo_metadata_json(&cargo, &manifest_path)?;
134    let (crate_name, version) = wrapper::package_identity(&metadata, &manifest_path)?;
135
136    // 2. the manifest that travels with the cdylib has to agree with Cargo.toml.
137    //    A host reads the manifest before it downloads anything, and the asset file
138    //    name is built from the crate version; if the two disagree, one of them lies.
139    let plugin_manifest = plugin_dir.join(&cfg.manifest_name);
140    let manifest = PluginManifest::read(&plugin_manifest)?;
141    if manifest.plugin.version != version {
142        return Err(KitError::VersionMismatch {
143            path: plugin_manifest,
144            declared: manifest.plugin.version,
145            crate_version: version,
146        });
147    }
148
149    // 3. the wrapper, then the build
150    let target = cfg.effective_target().to_string();
151    let target_dir = options
152        .target_dir
153        .clone()
154        .unwrap_or_else(|| plugin_dir.join("target"));
155
156    // A directory of this run's own. Sharing one by crate name would mean two runs — two
157    // tests, or two pack calls in one program — deleting and writing the same files at
158    // once; on Windows deleting a directory another process still has open fails outright
159    // with "access denied".
160    let wrapper_dir = wrapper_dir(cfg, &crate_name);
161    std::fs::create_dir_all(wrapper_dir.join("src"))?;
162
163    let stem = cfg.lib_stem(&crate_name);
164    let contract = declared_contract_dep(&metadata, &crate_name, &cfg.contract_crate);
165    wrapper::write(
166        cfg,
167        &wrapper_dir,
168        &crate_name,
169        &stem,
170        PluginSource::Path { dir: &plugin_dir },
171        contract.as_ref(),
172    )?;
173
174    // stdio is inherited: this can take a while and the caller should see cargo's output
175    let status = Command::new(&cargo)
176        .arg("build")
177        .arg("--release")
178        .arg("--manifest-path")
179        .arg(wrapper_dir.join("Cargo.toml"))
180        .arg("--target")
181        .arg(&target)
182        .arg("--target-dir")
183        .arg(&target_dir)
184        .status()
185        .map_err(KitError::Io)?;
186
187    if !status.success() {
188        return Err(KitError::BuildFailed {
189            code: status.code(),
190        });
191    }
192
193    // 4. name it the way `prebuilt` looks for it
194    let release_dir = target_dir.join(&target).join("release");
195    let built =
196        crate::loader::find_library_for_target(&release_dir, &stem, &target).map_err(|_| {
197            KitError::BuildArtifactMissing {
198                stem: stem.clone(),
199                dir: release_dir.display().to_string(),
200            }
201        })?;
202
203    let out_dir = out_dir.as_ref();
204    std::fs::create_dir_all(out_dir)?;
205
206    let base = format!("{crate_name}-{version}-{target}");
207    let library = out_dir.join(format!(
208        "{base}.{}",
209        crate::loader::lib_ext_for_target(&target)
210    ));
211    std::fs::copy(&built, &library)?;
212
213    let manifest_out = out_dir.join(format!("{base}.toml"));
214    std::fs::copy(&plugin_manifest, &manifest_out)?;
215
216    if options.verify_export && target == crate::TARGET_TRIPLE {
217        // The one check that cannot be made by inspecting file names: the symbol a host
218        // resolves before it calls anything. Catching it here costs a `dlopen`; catching
219        // it in the field costs a release.
220        //
221        // `()` as the entry type: the pointer is never dereferenced, so no layout
222        // assumption is made (see `loader::open`).
223        let _loaded = unsafe { crate::loader::open::<()>(&library, &cfg.entry_symbol) }?;
224    }
225
226    // Only worth keeping while something went wrong; a caller that packs repeatedly should
227    // not leave a trail of scaffolding in the temp directory. This removes the whole per-run
228    // directory, the crate directory inside it included.
229    //
230    // Failure is ignored on purpose: see `wrapper_dir` for why removing it can be refused on
231    // Windows, and a leftover directory is not a reason to fail a successful pack.
232    if let Some(run_root) = wrapper_dir.parent() {
233        let _ = remove_dir_if_exists(run_root);
234    }
235
236    Ok(PackedAssets {
237        crate_name,
238        version,
239        target,
240        library,
241        manifest: manifest_out,
242    })
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn base_name_is_crate_version_target() {
251        let assets = PackedAssets {
252            crate_name: "bmux-plugin-cargo".to_string(),
253            version: "0.1.0".to_string(),
254            target: "x86_64-pc-windows-msvc".to_string(),
255            library: PathBuf::from("a.dll"),
256            manifest: PathBuf::from("a.toml"),
257        };
258
259        assert_eq!(
260            assets.base_name(),
261            "bmux-plugin-cargo-0.1.0-x86_64-pc-windows-msvc"
262        );
263    }
264
265    #[test]
266    fn verify_export_is_on_by_default() {
267        assert!(PackOptions::default().verify_export);
268        assert!(PackOptions::default().target_dir.is_none());
269    }
270
271    #[test]
272    fn a_missing_manifest_is_reported_as_such() {
273        let tmp = tempfile::tempdir().unwrap();
274        let cfg = KitConfig::new("myapp");
275
276        let err = build(
277            &cfg,
278            tmp.path(),
279            tmp.path().join("dist"),
280            &PackOptions::default(),
281        )
282        .unwrap_err();
283
284        assert!(matches!(err, KitError::NoManifest { .. }), "{err:?}");
285    }
286}