use std::fmt::Write as _;
use std::path::Path;
use crate::config::KitConfig;
use super::{ContractDep, PluginSource};
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,
);
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 {
writeln!(toml, "{name} = {{ path = \"{}\" }}", slash(path))
.expect("writing into a String cannot fail");
}
}
toml
}
pub(super) fn slash(path: &Path) -> String {
let raw = path.display().to_string();
let raw = if let Some(rest) = raw.strip_prefix(r"\\?\UNC\") {
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;
#[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");
}
#[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"
);
}
}