crate-plugin-kit 0.3.2

Installs and loads cdylib plugins and builds their prebuilt assets.
Documentation
//! Rendering the wrapper's `Cargo.toml`.
//!
//! The manifest is assembled as one string: the exact plugin dependency, the contract
//! dependency copied from the plugin (see the module docs of [`crate::wrapper`] for why
//! it has to be copied), and the development-only `[patch.crates-io]` overrides.
//!
//! Every path that ends up inside a TOML string goes through [`slash`].

use std::fmt::Write as _;
use std::path::Path;

use crate::config::KitConfig;

use super::{ContractDep, PluginSource};

/// The text of the wrapper's `Cargo.toml`.
///
/// `rewritten` is the note written into the header comment, saying what rewrites this
/// file.
pub(super) fn wrapper_toml(
    cfg: &KitConfig,
    crate_name: &str,
    stem: &str,
    plugin: PluginSource<'_>,
    contract: Option<&ContractDep>,
    rewritten: &str,
) -> String {
    let plugin_dep = match plugin {
        PluginSource::Registry { version } => format!(r#"{crate_name} = "={version}""#),
        PluginSource::Path { dir } => {
            format!(r#"{crate_name} = {{ path = "{}" }}"#, slash(dir))
        }
    };

    let contract_dep = match contract {
        Some(ContractDep {
            path: Some(path),
            req,
        }) => match req {
            Some(req) => format!(
                r#"{contract}   = {{ path = "{}", version = "{req}" }}"#,
                slash(path),
                contract = cfg.contract_crate
            ),
            None => format!(
                r#"{contract}   = {{ path = "{}" }}"#,
                slash(path),
                contract = cfg.contract_crate
            ),
        },
        _ => format!(
            r#"{contract}   = "{version}""#,
            contract = cfg.contract_crate,
            version = contract
                .and_then(|c| c.req.as_deref())
                .unwrap_or(cfg.contract_version.as_str())
        ),
    };

    let mut toml = format!(
        r#"# Generated by crate-plugin-kit; do not edit by hand — {rewritten}.
[package]
name         = "{crate_name}-wrapper"
version      = "0.0.0"
edition      = "{edition}"
publish      = false

# Single-element workspace: the wrapper must not be claimed by any Cargo.toml above it.
[workspace]

[lib]
name       = "{stem}"
crate-type = ["cdylib"]

[dependencies]
{plugin_dep}
{contract_dep}
"#,
        edition = cfg.wrapper_edition,
    );

    // Local path overrides: during development, point the plugin and the contract
    // crate at a local checkout.
    if !cfg.local_overrides.is_empty() {
        toml.push_str(
            "\n# from KitConfig::local_overrides (development only)\n[patch.crates-io]\n",
        );
        for (name, path) in &cfg.local_overrides {
            // Writing into a String cannot fail
            writeln!(toml, "{name} = {{ path = \"{}\" }}", slash(path))
                .expect("writing into a String cannot fail");
        }
    }

    toml
}

/// A path written for a TOML string: forward slashes, and never the Windows verbatim
/// prefix.
///
/// Two things go wrong otherwise. Backslashes would be read as TOML escapes; and a
/// canonicalized Windows path starts with `\\?\`, which cargo parses as a path URL and
/// rejects outright (`invalid path url` once the separators are slashes). Both are silent
/// until a build fails on Windows only, so this is the one place paths become strings.
pub(super) fn slash(path: &Path) -> String {
    let raw = path.display().to_string();

    let raw = if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") {
        // \\?\UNC\server\share -> \\server\share
        format!(r"\\{rest}")
    } else if let Some(rest) = raw.strip_prefix(r"\\?\") {
        rest.to_string()
    } else {
        raw
    };

    raw.replace('\\', "/")
}

#[cfg(test)]
mod tests {
    use super::super::tests::{cfg, toml_of, write_into};
    use super::*;
    use std::path::PathBuf;

    /// A checkout that points at the contract crate by path keeps that path: the
    /// release path has to work before the contract crate is published anywhere.
    #[test]
    fn a_path_dependency_on_the_contract_crate_is_mirrored() {
        let dep = ContractDep {
            req: Some("^0.1.0".to_string()),
            path: Some(PathBuf::from("/local/contract")),
        };

        let c = cfg();
        let tmp = write_into(&c, PluginSource::Registry { version: "0.1.0" }, Some(&dep));
        assert!(
            toml_of(&tmp)
                .contains(r#"myapp-plugin   = { path = "/local/contract", version = "^0.1.0" }"#),
            "{}",
            toml_of(&tmp)
        );
    }

    #[test]
    fn paths_are_written_with_forward_slashes() {
        assert_eq!(slash(Path::new(r"D:\local\plugin")), "D:/local/plugin");
        assert_eq!(slash(Path::new("/local/plugin")), "/local/plugin");
    }

    /// `canonicalize()` on Windows returns a verbatim path (`\\?\C:\...`), and cargo
    /// rejects that spelling inside a manifest: with the separators turned into slashes it
    /// becomes `//?/C:/...`, which is not a valid path URL. The prefix has to go.
    #[test]
    fn the_verbatim_prefix_is_stripped() {
        assert_eq!(
            slash(Path::new(r"\\?\C:\Users\me\plugin")),
            "C:/Users/me/plugin"
        );
        assert_eq!(
            slash(Path::new(r"\\?\UNC\server\share\plugin")),
            "//server/share/plugin"
        );
    }
}