use crate::error::CoolError;
use crate::module::mod::ModuleManager;
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
pub type MenuImportResult = HashMap<String, Value>;
pub struct MenuImporter {
pub run_path: PathBuf,
pub module_manager: ModuleManager,
pub lock_dir: PathBuf,
}
impl MenuImporter {
pub fn new(run_path: impl Into<PathBuf>, module_manager: ModuleManager) -> Self {
let run_path = run_path.into();
let lock_dir = run_path.join("..").join("lock").join("menu");
Self {
run_path,
module_manager,
lock_dir,
}
}
pub fn import_all(&self) -> Result<MenuImportResult, CoolError> {
let mut data = HashMap::new();
if !self.lock_dir.exists() {
fs::create_dir_all(&self.lock_dir)?;
}
for module in self.module_manager.modules() {
let module_path = self.run_path.join("modules").join(&module.name);
let menu_path = module_path.join("menu.json");
let lock_path = self.lock_dir.join(format!("{}.menu.lock", module.name));
if !menu_path.exists() {
continue;
}
if lock_path.exists() {
continue;
}
let menu_str = fs::read_to_string(&menu_path)?;
let menu_json: Value = serde_json::from_str(&menu_str)
.map_err(|e| CoolError::comm(format!("菜单解析失败: {} -> {}", menu_path.display(), e)))?;
data.insert(module.name.clone(), menu_json);
fs::write(lock_path, b"success")?;
}
Ok(data)
}
}