forgeFRENBrowse the repositories

roneocratesroneo-coresrcplugin.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

643 lines · 21.3 KiBRustRaw
  1. use std::fs;
  2. use std::path::{Path, PathBuf};
  3. use std::sync::{Arc, Mutex, RwLock};
  4. use indexmap::IndexMap;
  5. use minijinja::value::{Kwargs, Rest, Serde, Value as MjValue};
  6. use minijinja::{
  7. Environment, Error as MjError, ErrorKind as MjErrorKind, State, UndefinedBehavior,
  8. };
  9. use serde::{Deserialize, Serialize};
  10. use serde_json::{Map as JsonMap, Value as JsonValue};
  11. use wasmi::{
  12. Config, Engine, Instance, Linker, Memory, Module, Store, StoreLimits, StoreLimitsBuilder,
  13. TypedFunc,
  14. };
  15. /// Maximum linear memory allowed per sandboxed WASM plugin instance (64 MiB).
  16. const WASM_MAX_MEMORY_BYTES: usize = 64 * 1024 * 1024;
  17. /// Maximum single IPC payload accepted back from a WASM guest (16 MiB).
  18. const WASM_MAX_PAYLOAD_BYTES: usize = 16 * 1024 * 1024;
  19. /// Fuel budget per guest call (~100M instructions; prevents infinite loops).
  20. const WASM_CALL_FUEL_BUDGET: u64 = 100_000_000;
  21. use crate::error::{Result, RoneoError};
  22. pub type TemplateFileReader = Arc<dyn Fn(&str) -> Option<String> + Send + Sync>;
  23. /// Host metadata passed to extensions during registration (works for both disk and in-memory `gix` trees).
  24. #[derive(Clone)]
  25. pub struct ExtensionInitContext {
  26. pub template_root: PathBuf,
  27. pub dst_path: PathBuf,
  28. pub file_reader: TemplateFileReader,
  29. }
  30. impl std::fmt::Debug for ExtensionInitContext {
  31. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  32. f.debug_struct("ExtensionInitContext")
  33. .field("template_root", &self.template_root)
  34. .field("dst_path", &self.dst_path)
  35. .finish_non_exhaustive()
  36. }
  37. }
  38. /// Native or WASM template extension (equivalent to Copier's Jinja `Extension` + `ContextHook`).
  39. pub trait Extension: Send + Sync {
  40. fn name(&self) -> &str;
  41. /// Register custom filters, global functions/values, tests, or environment tweaks on `MiniJinja`.
  42. fn register(&self, env: &mut Environment<'static>, init: &ExtensionInitContext) -> Result<()>;
  43. /// Transform or validate the template context (`phase` is `"prompt"` or `"render"`).
  44. fn hook_context(&self, phase: &str, ctx: &mut IndexMap<String, JsonValue>) -> Result<()> {
  45. let _ = (phase, ctx);
  46. Ok(())
  47. }
  48. }
  49. /// Collection of active extensions (native Rust and/or sandboxed WASM).
  50. #[derive(Clone, Default)]
  51. pub struct ExtensionRegistry {
  52. extensions: Vec<Arc<dyn Extension>>,
  53. }
  54. impl std::fmt::Debug for ExtensionRegistry {
  55. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  56. let names: Vec<&str> = self.extensions.iter().map(|e| e.name()).collect();
  57. f.debug_struct("ExtensionRegistry")
  58. .field("extensions", &names)
  59. .finish()
  60. }
  61. }
  62. impl ExtensionRegistry {
  63. pub fn new() -> Self {
  64. Self::default()
  65. }
  66. pub fn add(&mut self, ext: Arc<dyn Extension>) {
  67. self.extensions.push(ext);
  68. }
  69. pub fn add_wasm_file(&mut self, path: impl AsRef<Path>) -> Result<()> {
  70. let wasm_ext = WasmExtension::from_file(path.as_ref())?;
  71. self.extensions.push(Arc::new(wasm_ext));
  72. Ok(())
  73. }
  74. pub fn add_wasm_bytes(&mut self, bytes: &[u8]) -> Result<()> {
  75. let wasm_ext = WasmExtension::from_bytes(bytes)?;
  76. self.extensions.push(Arc::new(wasm_ext));
  77. Ok(())
  78. }
  79. pub fn is_empty(&self) -> bool {
  80. self.extensions.is_empty()
  81. }
  82. pub fn names(&self) -> Vec<&str> {
  83. self.extensions.iter().map(|e| e.name()).collect()
  84. }
  85. pub fn register_all(
  86. &self,
  87. env: &mut Environment<'static>,
  88. init: &ExtensionInitContext,
  89. ) -> Result<()> {
  90. for ext in &self.extensions {
  91. ext.register(env, init)?;
  92. }
  93. Ok(())
  94. }
  95. pub fn run_context_hooks(
  96. &self,
  97. phase: &str,
  98. ctx: &mut IndexMap<String, JsonValue>,
  99. ) -> Result<()> {
  100. for ext in &self.extensions {
  101. ext.hook_context(phase, ctx)?;
  102. }
  103. Ok(())
  104. }
  105. }
  106. // ---------------------------------------------------------------------------
  107. // Sandboxed WebAssembly plugin runtime (`wasmi`) with lock-free parallel pool
  108. // ---------------------------------------------------------------------------
  109. /// Manifest returned by a WASM plugin's `roneo_manifest()` export.
  110. #[derive(Debug, Clone, Default, Serialize, Deserialize)]
  111. pub struct WasmPluginManifest {
  112. pub name: String,
  113. #[serde(default)]
  114. pub strict_undefined: bool,
  115. #[serde(default)]
  116. pub globals: IndexMap<String, JsonValue>,
  117. #[serde(default)]
  118. pub filters: Vec<String>,
  119. #[serde(default)]
  120. pub functions: Vec<String>,
  121. #[serde(default)]
  122. pub tests: Vec<String>,
  123. #[serde(default)]
  124. pub has_context_hook: bool,
  125. /// Optional list of template context keys to forward on filter/function calls.
  126. #[serde(default)]
  127. pub context_keys: Vec<String>,
  128. /// Optional relative paths inside `template_root` that the host reads and
  129. /// passes to `roneo_init` (keeps the WASM guest 100% sandboxed with zero FS access).
  130. #[serde(default)]
  131. pub template_files: Vec<String>,
  132. }
  133. #[derive(Debug, Clone, Serialize)]
  134. struct WasmInitPayload {
  135. template_files: IndexMap<String, String>,
  136. recorded_answers: JsonValue,
  137. dst_path: String,
  138. template_root: String,
  139. }
  140. #[derive(Debug, Serialize)]
  141. struct WasmCallRequest<'a> {
  142. kind: &'a str,
  143. name: &'a str,
  144. args: Vec<JsonValue>,
  145. kwargs: JsonMap<String, JsonValue>,
  146. context: JsonMap<String, JsonValue>,
  147. phase: &'a str,
  148. }
  149. #[derive(Debug, Deserialize)]
  150. #[serde(rename_all = "lowercase")]
  151. enum WasmCallResponse {
  152. Ok(JsonValue),
  153. Err(String),
  154. }
  155. struct WasmRuntime {
  156. store: Store<StoreLimits>,
  157. memory: Memory,
  158. alloc: TypedFunc<u32, u32>,
  159. dealloc: Option<TypedFunc<(u32, u32), ()>>,
  160. call_fn: TypedFunc<(u32, u32), u64>,
  161. init_fn: Option<TypedFunc<(u32, u32), u64>>,
  162. initialized: bool,
  163. }
  164. impl WasmRuntime {
  165. fn instantiate_from_module(engine: &Engine, module: &Module) -> Result<(Self, Instance)> {
  166. let limits = StoreLimitsBuilder::new()
  167. .memory_size(WASM_MAX_MEMORY_BYTES)
  168. .build();
  169. let mut store = Store::new(engine, limits);
  170. store.limiter(|lim| lim);
  171. let _ = store.set_fuel(WASM_CALL_FUEL_BUDGET);
  172. let linker = Linker::<StoreLimits>::new(engine);
  173. let instance: Instance = linker
  174. .instantiate_and_start(&mut store, module)
  175. .map_err(|e| RoneoError::Plugin(format!("Failed to instantiate WASM module: {e}")))?;
  176. let memory = instance
  177. .get_memory(&store, "memory")
  178. .ok_or_else(|| RoneoError::Plugin("WASM plugin missing `memory` export".into()))?;
  179. let alloc = instance
  180. .get_typed_func::<u32, u32>(&store, "roneo_alloc")
  181. .map_err(|e| RoneoError::Plugin(format!("WASM plugin missing `roneo_alloc`: {e}")))?;
  182. let dealloc = instance
  183. .get_typed_func::<(u32, u32), ()>(&store, "roneo_dealloc")
  184. .ok();
  185. let call_fn = instance
  186. .get_typed_func::<(u32, u32), u64>(&store, "roneo_call")
  187. .map_err(|e| RoneoError::Plugin(format!("WASM plugin missing `roneo_call`: {e}")))?;
  188. let init_fn = instance
  189. .get_typed_func::<(u32, u32), u64>(&store, "roneo_init")
  190. .ok();
  191. Ok((
  192. Self {
  193. store,
  194. memory,
  195. alloc,
  196. dealloc,
  197. call_fn,
  198. init_fn,
  199. initialized: false,
  200. },
  201. instance,
  202. ))
  203. }
  204. fn read_manifest(&mut self, instance: Instance) -> Result<WasmPluginManifest> {
  205. let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET);
  206. let manifest_fn = instance
  207. .get_typed_func::<(), u64>(&self.store, "roneo_manifest")
  208. .map_err(|e| {
  209. RoneoError::Plugin(format!("WASM plugin missing `roneo_manifest`: {e}"))
  210. })?;
  211. let packed = manifest_fn
  212. .call(&mut self.store, ())
  213. .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_manifest` trapped: {e}")))?;
  214. let manifest_bytes = read_packed(&self.store, self.memory, packed)?;
  215. serde_json::from_slice(&manifest_bytes).map_err(|e| {
  216. RoneoError::Plugin(format!("Invalid JSON from WASM `roneo_manifest`: {e}"))
  217. })
  218. }
  219. fn write_guest(&mut self, bytes: &[u8]) -> Result<(u32, u32)> {
  220. let len = u32::try_from(bytes.len())
  221. .map_err(|_| RoneoError::Plugin("Payload exceeds 4 GiB WASM address space".into()))?;
  222. let ptr = self
  223. .alloc
  224. .call(&mut self.store, len)
  225. .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_alloc` failed: {e}")))?;
  226. self.memory
  227. .write(&mut self.store, ptr as usize, bytes)
  228. .map_err(|e| RoneoError::Plugin(format!("WASM memory write failed: {e}")))?;
  229. Ok((ptr, len))
  230. }
  231. fn free_guest(&mut self, ptr: u32, len: u32) {
  232. if let Some(dealloc) = self.dealloc {
  233. let _ = dealloc.call(&mut self.store, (ptr, len));
  234. }
  235. }
  236. fn send_init(&mut self, payload_bytes: &[u8]) -> Result<()> {
  237. let Some(init_fn) = self.init_fn else {
  238. self.initialized = true;
  239. return Ok(());
  240. };
  241. let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET);
  242. let (ptr, len) = self.write_guest(payload_bytes)?;
  243. let packed = init_fn
  244. .call(&mut self.store, (ptr, len))
  245. .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_init` trapped: {e}")))?;
  246. self.free_guest(ptr, len);
  247. if packed != 0 {
  248. let resp_bytes = read_packed(&self.store, self.memory, packed)?;
  249. let (out_ptr, out_len) = unpack_ptr_len(packed);
  250. self.free_guest(out_ptr, out_len);
  251. let resp: WasmCallResponse = serde_json::from_slice(&resp_bytes)?;
  252. if let WasmCallResponse::Err(msg) = resp {
  253. return Err(RoneoError::Plugin(msg));
  254. }
  255. }
  256. self.initialized = true;
  257. Ok(())
  258. }
  259. fn invoke(&mut self, req: &WasmCallRequest<'_>) -> Result<JsonValue> {
  260. let _ = self.store.set_fuel(WASM_CALL_FUEL_BUDGET);
  261. let bytes = serde_json::to_vec(req)?;
  262. let (ptr, len) = self.write_guest(&bytes)?;
  263. let packed = self
  264. .call_fn
  265. .call(&mut self.store, (ptr, len))
  266. .map_err(|e| RoneoError::Plugin(format!("WASM `roneo_call` trapped: {e}")))?;
  267. self.free_guest(ptr, len);
  268. let resp_bytes = read_packed(&self.store, self.memory, packed)?;
  269. let (out_ptr, out_len) = unpack_ptr_len(packed);
  270. self.free_guest(out_ptr, out_len);
  271. let resp: WasmCallResponse = serde_json::from_slice(&resp_bytes).map_err(|e| {
  272. RoneoError::Plugin(format!("Invalid JSON response from WASM plugin: {e}"))
  273. })?;
  274. match resp {
  275. WasmCallResponse::Ok(val) => Ok(val),
  276. WasmCallResponse::Err(msg) => Err(RoneoError::Plugin(msg)),
  277. }
  278. }
  279. }
  280. /// Thread-safe pool of initialized `WasmRuntime` instances so parallel `rayon` threads can
  281. /// execute WASM filters simultaneously with zero contention during guest execution.
  282. struct WasmPool {
  283. engine: Engine,
  284. module: Module,
  285. init_bytes: RwLock<Option<Vec<u8>>>,
  286. instances: Mutex<Vec<WasmRuntime>>,
  287. }
  288. impl WasmPool {
  289. fn new(wasm_bytes: &[u8]) -> Result<(Self, WasmPluginManifest)> {
  290. let mut cfg = Config::default();
  291. cfg.consume_fuel(true);
  292. let engine = Engine::new(&cfg);
  293. let module = Module::new(&engine, wasm_bytes)
  294. .map_err(|e| RoneoError::Plugin(format!("Invalid WASM module: {e}")))?;
  295. let (mut rt, instance) = WasmRuntime::instantiate_from_module(&engine, &module)?;
  296. let manifest = rt.read_manifest(instance)?;
  297. Ok((
  298. Self {
  299. engine,
  300. module,
  301. init_bytes: RwLock::new(None),
  302. instances: Mutex::new(vec![rt]),
  303. },
  304. manifest,
  305. ))
  306. }
  307. fn set_init_payload(&self, payload: &WasmInitPayload) -> Result<()> {
  308. let bytes = serde_json::to_vec(payload)?;
  309. {
  310. let mut guard = self
  311. .init_bytes
  312. .write()
  313. .map_err(|_| RoneoError::Plugin("WASM init lock poisoned".into()))?;
  314. *guard = Some(bytes.clone());
  315. }
  316. // Re-initialize any pooled instances already created.
  317. let mut pool = self
  318. .instances
  319. .lock()
  320. .map_err(|_| RoneoError::Plugin("WASM pool lock poisoned".into()))?;
  321. for rt in pool.iter_mut() {
  322. rt.send_init(&bytes)?;
  323. }
  324. Ok(())
  325. }
  326. fn call(&self, req: &WasmCallRequest<'_>) -> Result<JsonValue> {
  327. let mut rt = {
  328. let mut pool = self
  329. .instances
  330. .lock()
  331. .map_err(|_| RoneoError::Plugin("WASM pool lock poisoned".into()))?;
  332. pool.pop()
  333. };
  334. let mut runtime = if let Some(existing) = rt.take() {
  335. existing
  336. } else {
  337. let (mut fresh, _) = WasmRuntime::instantiate_from_module(&self.engine, &self.module)?;
  338. if let Ok(guard) = self.init_bytes.read()
  339. && let Some(bytes) = guard.as_deref()
  340. {
  341. fresh.send_init(bytes)?;
  342. }
  343. fresh
  344. };
  345. if !runtime.initialized
  346. && let Ok(guard) = self.init_bytes.read()
  347. && let Some(bytes) = guard.as_deref()
  348. {
  349. runtime.send_init(bytes)?;
  350. }
  351. let res = runtime.invoke(req);
  352. if let Ok(mut pool) = self.instances.lock() {
  353. pool.push(runtime);
  354. }
  355. res
  356. }
  357. }
  358. fn unpack_ptr_len(packed: u64) -> (u32, u32) {
  359. #[allow(clippy::cast_possible_truncation)]
  360. let ptr = (packed >> 32) as u32;
  361. #[allow(clippy::cast_possible_truncation)]
  362. let len = (packed & 0xFFFF_FFFF) as u32;
  363. (ptr, len)
  364. }
  365. fn read_packed(store: &Store<StoreLimits>, memory: Memory, packed: u64) -> Result<Vec<u8>> {
  366. let (ptr, len) = unpack_ptr_len(packed);
  367. let len_usize = len as usize;
  368. let ptr_usize = ptr as usize;
  369. if len_usize > WASM_MAX_PAYLOAD_BYTES {
  370. return Err(RoneoError::Plugin(format!(
  371. "WASM guest payload ({len_usize} bytes) exceeds maximum allowed ({WASM_MAX_PAYLOAD_BYTES} bytes)"
  372. )));
  373. }
  374. let mem_size = memory.data_size(store);
  375. if ptr_usize
  376. .checked_add(len_usize)
  377. .is_none_or(|end| end > mem_size)
  378. {
  379. return Err(RoneoError::Plugin(
  380. "WASM guest returned out-of-bounds memory slice".into(),
  381. ));
  382. }
  383. let mut buf = vec![0u8; len_usize];
  384. memory
  385. .read(store, ptr_usize, &mut buf)
  386. .map_err(|e| RoneoError::Plugin(format!("WASM memory read failed: {e}")))?;
  387. Ok(buf)
  388. }
  389. /// A sandboxed WebAssembly plugin loaded into `roneo-core` via `wasmi`.
  390. pub struct WasmExtension {
  391. manifest: WasmPluginManifest,
  392. pool: Arc<WasmPool>,
  393. }
  394. impl WasmExtension {
  395. pub fn from_file(path: &Path) -> Result<Self> {
  396. let bytes = fs::read(path).map_err(|e| RoneoError::io(path, e))?;
  397. Self::from_bytes(&bytes)
  398. }
  399. pub fn from_bytes(wasm_bytes: &[u8]) -> Result<Self> {
  400. let (pool, manifest) = WasmPool::new(wasm_bytes)?;
  401. Ok(Self {
  402. manifest,
  403. pool: Arc::new(pool),
  404. })
  405. }
  406. pub fn manifest(&self) -> &WasmPluginManifest {
  407. &self.manifest
  408. }
  409. }
  410. impl Extension for WasmExtension {
  411. fn name(&self) -> &str {
  412. &self.manifest.name
  413. }
  414. fn register(&self, env: &mut Environment<'static>, init: &ExtensionInitContext) -> Result<()> {
  415. if self.manifest.strict_undefined {
  416. env.set_undefined_behavior(UndefinedBehavior::Strict);
  417. }
  418. // Send sandboxed init payload (reading template_files via `file_reader` — zero disk I/O for GitTree!).
  419. let mut template_files = IndexMap::new();
  420. for rel in &self.manifest.template_files {
  421. if let Some(content) = (init.file_reader)(rel) {
  422. template_files.insert(rel.clone(), content);
  423. }
  424. }
  425. let recorded_answers = load_recorded_answers_json(&init.dst_path);
  426. let payload = WasmInitPayload {
  427. template_files,
  428. recorded_answers,
  429. dst_path: init.dst_path.to_string_lossy().into_owned(),
  430. template_root: init.template_root.to_string_lossy().into_owned(),
  431. };
  432. self.pool.set_init_payload(&payload)?;
  433. for (k, v) in &self.manifest.globals {
  434. env.add_global(k.clone(), MjValue::from(Serde(v)));
  435. }
  436. let ctx_keys = Arc::new(self.manifest.context_keys.clone());
  437. for filter_name in &self.manifest.filters {
  438. let pool = Arc::clone(&self.pool);
  439. let fname = filter_name.clone();
  440. let keys = Arc::clone(&ctx_keys);
  441. env.add_filter(
  442. filter_name.clone(),
  443. move |state: &State<'_, '_>,
  444. rest: Rest<MjValue>,
  445. kwargs: Kwargs|
  446. -> std::result::Result<MjValue, MjError> {
  447. invoke_wasm_callable(&pool, "filter", &fname, state, &rest.0, &kwargs, &keys)
  448. },
  449. );
  450. }
  451. for func_name in &self.manifest.functions {
  452. let pool = Arc::clone(&self.pool);
  453. let fname = func_name.clone();
  454. let keys = Arc::clone(&ctx_keys);
  455. env.add_function(
  456. func_name.clone(),
  457. move |state: &State<'_, '_>,
  458. rest: Rest<MjValue>,
  459. kwargs: Kwargs|
  460. -> std::result::Result<MjValue, MjError> {
  461. invoke_wasm_callable(&pool, "function", &fname, state, &rest.0, &kwargs, &keys)
  462. },
  463. );
  464. }
  465. for test_name in &self.manifest.tests {
  466. let pool = Arc::clone(&self.pool);
  467. let tname = test_name.clone();
  468. let keys = Arc::clone(&ctx_keys);
  469. env.add_test(
  470. test_name.clone(),
  471. move |state: &State<'_, '_>,
  472. rest: Rest<MjValue>,
  473. kwargs: Kwargs|
  474. -> std::result::Result<bool, MjError> {
  475. let val = invoke_wasm_callable(
  476. &pool, "test", &tname, state, &rest.0, &kwargs, &keys,
  477. )?;
  478. Ok(val.is_true())
  479. },
  480. );
  481. }
  482. Ok(())
  483. }
  484. fn hook_context(&self, phase: &str, ctx: &mut IndexMap<String, JsonValue>) -> Result<()> {
  485. if !self.manifest.has_context_hook {
  486. return Ok(());
  487. }
  488. let mut context = JsonMap::with_capacity(ctx.len());
  489. for (k, v) in ctx.iter() {
  490. context.insert(k.clone(), v.clone());
  491. }
  492. let req = WasmCallRequest {
  493. kind: "hook_context",
  494. name: "hook",
  495. args: Vec::new(),
  496. kwargs: JsonMap::new(),
  497. context,
  498. phase,
  499. };
  500. let result = self.pool.call(&req)?;
  501. if let JsonValue::Object(updates) = result {
  502. for (k, v) in updates {
  503. ctx.insert(k, v);
  504. }
  505. }
  506. Ok(())
  507. }
  508. }
  509. fn invoke_wasm_callable(
  510. pool: &Arc<WasmPool>,
  511. kind: &str,
  512. name: &str,
  513. state: &State<'_, '_>,
  514. raw_args: &[MjValue],
  515. raw_kwargs: &Kwargs,
  516. context_keys: &[String],
  517. ) -> std::result::Result<MjValue, MjError> {
  518. let args = raw_args
  519. .iter()
  520. .map(|val| {
  521. serde_json::to_value(val)
  522. .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))
  523. })
  524. .collect::<std::result::Result<Vec<_>, _>>()?;
  525. let mut kwargs = JsonMap::new();
  526. for key in raw_kwargs.args() {
  527. let val: MjValue = raw_kwargs.get(key)?;
  528. let jv = serde_json::to_value(&val)
  529. .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))?;
  530. kwargs.insert(key.to_string(), jv);
  531. }
  532. let context = extract_state_context(state, context_keys);
  533. let req = WasmCallRequest {
  534. kind,
  535. name,
  536. args,
  537. kwargs,
  538. context,
  539. phase: "render",
  540. };
  541. let val = pool
  542. .call(&req)
  543. .map_err(|e| MjError::new(MjErrorKind::InvalidOperation, e.to_string()))?;
  544. Ok(MjValue::from(Serde(&val)))
  545. }
  546. fn extract_state_context(
  547. state: &State<'_, '_>,
  548. context_keys: &[String],
  549. ) -> JsonMap<String, JsonValue> {
  550. let mut out = JsonMap::new();
  551. for key in context_keys {
  552. if let Some(v) = state.lookup(key)
  553. && !v.is_undefined()
  554. && let Ok(jv) = serde_json::to_value(&v)
  555. {
  556. out.insert(key.clone(), jv);
  557. }
  558. }
  559. out
  560. }
  561. /// Read existing `.copier-answers.yml` in `dst_path` to populate `recorded_answers` for plugins.
  562. pub fn load_recorded_answers_json(dst_path: &Path) -> JsonValue {
  563. let path = dst_path.join(".copier-answers.yml");
  564. if !path.is_file() {
  565. return JsonValue::Object(JsonMap::new());
  566. }
  567. let Ok(raw) = fs::read_to_string(&path) else {
  568. return JsonValue::Object(JsonMap::new());
  569. };
  570. match serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&raw) {
  571. Ok(y) => match serde_json::to_value(y) {
  572. Ok(JsonValue::Object(map)) if !map.is_empty() => JsonValue::Object(map),
  573. _ => serde_json::json!({ "_unreadable": true }),
  574. },
  575. Err(_) => serde_json::json!({ "_unreadable": true }),
  576. }
  577. }