use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Duration;
use crate::error::{KitError, KitResult};
pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Debug, Clone)]
pub struct KitConfig {
pub id: String,
pub manifest_name: String,
pub crate_prefix: String,
pub entry_symbol: Vec<u8>,
pub lib_stem_prefix: String,
pub contract_crate: String,
pub contract_version: String,
pub wrapper_edition: String,
pub wrapper_body: String,
pub data_dir: Option<PathBuf>,
pub lock_timeout: Duration,
pub prefer_prebuilt: bool,
pub target_triple: Option<String>,
pub registry: String,
pub local_overrides: BTreeMap<String, PathBuf>,
}
impl KitConfig {
pub fn new(id: impl Into<String>) -> Self {
let id = id.into();
let snake = id.replace('-', "_");
Self {
manifest_name: format!("{id}-plugin.toml"),
crate_prefix: format!("{id}-plugin-"),
entry_symbol: format!("{snake}_plugin_entry_v1").into_bytes(),
lib_stem_prefix: format!("{snake}_plugin_"),
contract_crate: format!("{id}-plugin"),
contract_version: "0.1".to_string(),
wrapper_edition: "2021".to_string(),
wrapper_body: format!("{snake}_plugin::export!({{crate_ident}}::create);\n"),
data_dir: None,
lock_timeout: DEFAULT_LOCK_TIMEOUT,
prefer_prebuilt: true,
target_triple: None,
registry: "https://crates.io".to_string(),
local_overrides: BTreeMap::new(),
id,
}
}
pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
self.data_dir = Some(dir.into());
self
}
pub fn with_lock_timeout(mut self, t: Duration) -> Self {
self.lock_timeout = t;
self
}
pub fn effective_target(&self) -> &str {
self.target_triple
.as_deref()
.unwrap_or(crate::TARGET_TRIPLE)
}
pub fn normalize_crate_name(&self, name: &str) -> String {
if name.starts_with(&self.crate_prefix) {
name.to_string()
} else {
format!("{}{}", self.crate_prefix, name)
}
}
pub fn lib_stem(&self, crate_name: &str) -> String {
let tail = crate_name
.strip_prefix(&self.crate_prefix)
.unwrap_or(crate_name);
format!("{}{}", self.lib_stem_prefix, tail.replace('-', "_"))
}
pub fn paths(&self) -> KitResult<KitPaths> {
let root = match &self.data_dir {
Some(d) => d.clone(),
None => default_data_dir(&self.id)?,
};
Ok(KitPaths {
plugins: root.join("plugins"),
build: root.join("build"),
lock_file: root.join(".lock"),
index_file: root.join("plugins").join(".plugins.json"),
root,
})
}
}
fn default_data_dir(id: &str) -> KitResult<PathBuf> {
let home = directories::UserDirs::new()
.map(|d| d.home_dir().to_path_buf())
.ok_or(KitError::NoDataDir)?;
Ok(home.join(format!(".{id}")))
}
#[derive(Debug, Clone)]
pub struct KitPaths {
pub root: PathBuf,
pub plugins: PathBuf,
pub build: PathBuf,
pub lock_file: PathBuf,
pub index_file: PathBuf,
}
impl KitPaths {
pub fn plugin_dir(&self, crate_name: &str) -> PathBuf {
self.plugins.join(crate_name)
}
pub fn manifest_path(&self, crate_name: &str, manifest_name: &str) -> PathBuf {
self.plugin_dir(crate_name).join(manifest_name)
}
pub fn build_dir(&self, crate_name: &str) -> PathBuf {
self.build.join(crate_name)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn cfg() -> KitConfig {
KitConfig::new("myapp")
}
#[test]
fn new_derives_names_from_the_id() {
let c = cfg();
assert_eq!(c.id, "myapp");
assert_eq!(c.manifest_name, "myapp-plugin.toml");
assert_eq!(c.crate_prefix, "myapp-plugin-");
assert_eq!(c.lib_stem_prefix, "myapp_plugin_");
assert_eq!(c.contract_crate, "myapp-plugin");
}
#[test]
fn normalizes_short_and_full_crate_names() {
let c = cfg();
assert_eq!(c.normalize_crate_name("foo"), "myapp-plugin-foo");
assert_eq!(
c.normalize_crate_name("myapp-plugin-foo"),
"myapp-plugin-foo"
);
}
#[test]
fn derives_lib_stem_from_crate_name() {
let c = cfg();
assert_eq!(c.lib_stem("myapp-plugin-foo"), "myapp_plugin_foo");
assert_eq!(c.lib_stem("myapp-plugin-a-b"), "myapp_plugin_a_b");
}
#[test]
fn target_falls_back_to_compile_time_triple() {
let c = cfg();
assert_eq!(c.effective_target(), crate::TARGET_TRIPLE);
let mut overridden = cfg();
overridden.target_triple = Some("aarch64-apple-darwin".to_string());
assert_eq!(overridden.effective_target(), "aarch64-apple-darwin");
}
#[test]
fn paths_honour_the_data_dir_override() {
let root = PathBuf::from("some").join("dir");
let c = cfg().with_data_dir(&root);
let p = c.paths().expect("override 时不该碰 HOME");
assert_eq!(p.root, root);
assert_eq!(p.plugins, root.join("plugins"));
assert_eq!(p.build, root.join("build"));
assert_eq!(p.lock_file, root.join(".lock"));
assert_eq!(p.index_file, root.join("plugins").join(".plugins.json"));
}
#[test]
fn plugin_paths_sit_under_the_plugins_dir() {
let root = PathBuf::from("some").join("dir");
let c = cfg().with_data_dir(&root);
let p = c.paths().unwrap();
assert_eq!(
p.plugin_dir("myapp-plugin-foo"),
root.join("plugins").join("myapp-plugin-foo")
);
assert_eq!(
p.build_dir("myapp-plugin-foo"),
root.join("build").join("myapp-plugin-foo")
);
assert_eq!(
p.manifest_path("myapp-plugin-foo", "myapp-plugin.toml"),
root.join("plugins")
.join("myapp-plugin-foo")
.join("myapp-plugin.toml")
);
}
#[test]
fn with_lock_timeout_replaces_the_default() {
let c = cfg().with_lock_timeout(Duration::from_millis(5));
assert_eq!(c.lock_timeout, Duration::from_millis(5));
}
}