use std::path::{Path, PathBuf};
use crate::Plugin;
use crate::StringFileSet;
#[derive(Debug)]
pub struct LocalizedPluginContext {
plugin: Plugin,
string_files: StringFileSet,
language: String,
}
impl LocalizedPluginContext {
pub fn load(path: PathBuf, language: &str) -> Result<Self, Box<dyn std::error::Error>> {
let mut plugin = Plugin::load(path.clone())?;
if !plugin.is_localized() {
eprintln!(
"警告: 插件 {} 未设置 LOCALIZED 标志,可能不包含 STRING 文件",
plugin.get_name()
);
}
let string_files = Self::load_string_files(&path, &plugin, language)?;
plugin.set_string_files(string_files.clone());
Ok(Self {
plugin,
string_files,
language: language.to_string(),
})
}
pub fn new_with_plugin(
mut plugin: Plugin,
plugin_path: PathBuf,
language: &str,
) -> Result<Self, Box<dyn std::error::Error>> {
if !plugin.is_localized() {
eprintln!(
"警告: 插件 {} 未设置 LOCALIZED 标志,可能不包含 STRING 文件",
plugin.get_name()
);
}
let string_files = Self::load_string_files(&plugin_path, &plugin, language)?;
plugin.set_string_files(string_files.clone());
Ok(Self {
plugin,
string_files,
language: language.to_string(),
})
}
fn load_string_files(
path: &Path,
_plugin: &Plugin,
language: &str,
) -> Result<StringFileSet, Box<dyn std::error::Error>> {
let plugin_name = path
.file_stem()
.and_then(|s| s.to_str())
.ok_or("无法获取插件名称")?;
StringFileSet::load_auto_for_plugin(path, plugin_name, language)
}
pub fn plugin(&self) -> &Plugin {
&self.plugin
}
pub fn plugin_mut(&mut self) -> &mut Plugin {
&mut self.plugin
}
pub fn string_files(&self) -> &StringFileSet {
&self.string_files
}
pub fn string_files_mut(&mut self) -> &mut StringFileSet {
&mut self.string_files
}
pub fn language(&self) -> &str {
&self.language
}
pub fn into_parts(self) -> (Plugin, StringFileSet, String) {
(self.plugin, self.string_files, self.language)
}
pub fn save_string_files(
&self,
output_dir: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
let string_dir = output_dir.join("strings");
std::fs::create_dir_all(&string_dir)?;
self.string_files.write_all(&string_dir)
}
pub fn summary(&self) -> String {
format!(
"本地化插件: {}, 语言: {}, STRING 文件数: {}",
self.plugin.get_name(),
self.language,
self.string_files.files.len()
)
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_localized_context_creation() {
}
}