crate_plugin_kit/
config.rs1use std::collections::BTreeMap;
8use std::path::PathBuf;
9use std::time::Duration;
10
11use crate::error::{KitError, KitResult};
12
13pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(30);
15
16#[derive(Debug, Clone)]
18pub struct KitConfig {
19 pub id: String,
21
22 pub manifest_name: String,
27
28 pub crate_prefix: String,
32
33 pub entry_symbol: Vec<u8>,
35
36 pub lib_stem_prefix: String,
41
42 pub contract_crate: String,
44
45 pub contract_version: String,
47
48 pub wrapper_edition: String,
50
51 pub wrapper_body: String,
56
57 pub data_dir: Option<PathBuf>,
59
60 pub lock_timeout: Duration,
62
63 pub prefer_prebuilt: bool,
65
66 pub target_triple: Option<String>,
68
69 pub registry: String,
71
72 pub local_overrides: BTreeMap<String, PathBuf>,
78}
79
80impl KitConfig {
81 pub fn new(id: impl Into<String>) -> Self {
98 let id = id.into();
99 let snake = id.replace('-', "_");
100 Self {
101 manifest_name: format!("{id}-plugin.toml"),
102 crate_prefix: format!("{id}-plugin-"),
103 entry_symbol: format!("{snake}_plugin_entry_v1").into_bytes(),
104 lib_stem_prefix: format!("{snake}_plugin_"),
105 contract_crate: format!("{id}-plugin"),
106 contract_version: "0.1".to_string(),
107 wrapper_edition: "2021".to_string(),
108 wrapper_body: format!("{snake}_plugin::export!({{crate_ident}}::create);\n"),
109 data_dir: None,
110 lock_timeout: DEFAULT_LOCK_TIMEOUT,
111 prefer_prebuilt: true,
112 target_triple: None,
113 registry: "https://crates.io".to_string(),
114 local_overrides: BTreeMap::new(),
115 id,
116 }
117 }
118
119 pub fn with_data_dir(mut self, dir: impl Into<PathBuf>) -> Self {
121 self.data_dir = Some(dir.into());
122 self
123 }
124
125 pub fn with_lock_timeout(mut self, t: Duration) -> Self {
127 self.lock_timeout = t;
128 self
129 }
130
131 pub fn effective_target(&self) -> &str {
133 self.target_triple
134 .as_deref()
135 .unwrap_or(crate::TARGET_TRIPLE)
136 }
137
138 pub fn normalize_crate_name(&self, name: &str) -> String {
142 if name.starts_with(&self.crate_prefix) {
143 name.to_string()
144 } else {
145 format!("{}{}", self.crate_prefix, name)
146 }
147 }
148
149 pub fn lib_stem(&self, crate_name: &str) -> String {
153 let tail = crate_name
154 .strip_prefix(&self.crate_prefix)
155 .unwrap_or(crate_name);
156 format!("{}{}", self.lib_stem_prefix, tail.replace('-', "_"))
157 }
158
159 pub fn paths(&self) -> KitResult<KitPaths> {
161 let root = match &self.data_dir {
162 Some(d) => d.clone(),
163 None => default_data_dir(&self.id)?,
164 };
165 Ok(KitPaths {
166 plugins: root.join("plugins"),
167 build: root.join("build"),
168 lock_file: root.join(".lock"),
169 index_file: root.join("plugins").join(".plugins.json"),
170 root,
171 })
172 }
173}
174
175fn default_data_dir(id: &str) -> KitResult<PathBuf> {
177 let home = directories::UserDirs::new()
178 .map(|d| d.home_dir().to_path_buf())
179 .ok_or(KitError::NoDataDir)?;
180 Ok(home.join(format!(".{id}")))
181}
182
183#[derive(Debug, Clone)]
185pub struct KitPaths {
186 pub root: PathBuf,
188 pub plugins: PathBuf,
190 pub build: PathBuf,
192 pub lock_file: PathBuf,
194 pub index_file: PathBuf,
196}
197
198impl KitPaths {
199 pub fn plugin_dir(&self, crate_name: &str) -> PathBuf {
201 self.plugins.join(crate_name)
202 }
203
204 pub fn manifest_path(&self, crate_name: &str, manifest_name: &str) -> PathBuf {
206 self.plugin_dir(crate_name).join(manifest_name)
207 }
208
209 pub fn build_dir(&self, crate_name: &str) -> PathBuf {
211 self.build.join(crate_name)
212 }
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218
219 fn cfg() -> KitConfig {
220 KitConfig::new("myapp")
221 }
222
223 #[test]
224 fn new_derives_names_from_the_id() {
225 let c = cfg();
226 assert_eq!(c.id, "myapp");
227 assert_eq!(c.manifest_name, "myapp-plugin.toml");
228 assert_eq!(c.crate_prefix, "myapp-plugin-");
229 assert_eq!(c.lib_stem_prefix, "myapp_plugin_");
230 assert_eq!(c.contract_crate, "myapp-plugin");
231 }
232
233 #[test]
234 fn normalizes_short_and_full_crate_names() {
235 let c = cfg();
236 assert_eq!(c.normalize_crate_name("foo"), "myapp-plugin-foo");
237 assert_eq!(
239 c.normalize_crate_name("myapp-plugin-foo"),
240 "myapp-plugin-foo"
241 );
242 }
243
244 #[test]
245 fn derives_lib_stem_from_crate_name() {
246 let c = cfg();
247 assert_eq!(c.lib_stem("myapp-plugin-foo"), "myapp_plugin_foo");
248 assert_eq!(c.lib_stem("myapp-plugin-a-b"), "myapp_plugin_a_b");
250 }
251
252 #[test]
253 fn target_falls_back_to_compile_time_triple() {
254 let c = cfg();
255 assert_eq!(c.effective_target(), crate::TARGET_TRIPLE);
256
257 let mut overridden = cfg();
258 overridden.target_triple = Some("aarch64-apple-darwin".to_string());
259 assert_eq!(overridden.effective_target(), "aarch64-apple-darwin");
260 }
261
262 #[test]
263 fn paths_honour_the_data_dir_override() {
264 let root = PathBuf::from("some").join("dir");
265 let c = cfg().with_data_dir(&root);
266 let p = c.paths().expect("override 时不该碰 HOME");
267
268 assert_eq!(p.root, root);
269 assert_eq!(p.plugins, root.join("plugins"));
270 assert_eq!(p.build, root.join("build"));
271 assert_eq!(p.lock_file, root.join(".lock"));
272 assert_eq!(p.index_file, root.join("plugins").join(".plugins.json"));
273 }
274
275 #[test]
276 fn plugin_paths_sit_under_the_plugins_dir() {
277 let root = PathBuf::from("some").join("dir");
278 let c = cfg().with_data_dir(&root);
279 let p = c.paths().unwrap();
280
281 assert_eq!(
282 p.plugin_dir("myapp-plugin-foo"),
283 root.join("plugins").join("myapp-plugin-foo")
284 );
285 assert_eq!(
286 p.build_dir("myapp-plugin-foo"),
287 root.join("build").join("myapp-plugin-foo")
288 );
289 assert_eq!(
290 p.manifest_path("myapp-plugin-foo", "myapp-plugin.toml"),
291 root.join("plugins")
292 .join("myapp-plugin-foo")
293 .join("myapp-plugin.toml")
294 );
295 }
296
297 #[test]
298 fn with_lock_timeout_replaces_the_default() {
299 let c = cfg().with_lock_timeout(Duration::from_millis(5));
300 assert_eq!(c.lock_timeout, Duration::from_millis(5));
301 }
302}