完成子命令 convert

Signed-off-by: Jia Chao <jiac13@chinaunicom.cn>
This commit is contained in:
Jia Chao 2024-06-28 10:41:16 +08:00
parent a6cdd8e39b
commit edb907941b
2 changed files with 57 additions and 2 deletions

View File

@ -8,4 +8,4 @@ edition = "2021"
[dependencies] [dependencies]
clap = { version = "4.0", features = ["derive"] } clap = { version = "4.0", features = ["derive"] }
cvrf-xmlparser = { git = "https://git.zhgsun.com:8089/jiachao2130/cvrf-xmlparser.git", version = "0.1.0" } cvrf-xmlparser = { git = "https://git.zhgsun.com:8089/jiachao2130/cvrf-xmlparser.git", version = "0.1.0" }
json = { version = "0.12" } serde_json = { version = "1.0" }

View File

@ -1,6 +1,11 @@
use std::fs;
use std::io::Write;
use std::path::Path;
use cvrf_xmlparser::{ use cvrf_xmlparser::{
CVRF, CVRF,
SaInfo as CUSA, // SaInfo 即为 CUSA
// SaInfo,
}; };
pub mod cli; pub mod cli;
@ -14,5 +19,55 @@ pub type Result<T> = std::result::Result<T, Error>;
pub fn cumain() -> Result<()> { pub fn cumain() -> Result<()> {
let cli = cli::parse(); let cli = cli::parse();
match cli.subcommand {
cli::CliSub::Convert(cli) => covert(&cli),
cli::CliSub::Db(cli) => sadb(&cli),
}
}
fn covert(cli: &cli::ConvertCli) -> Result<()> {
// 检查 input此为必须项
let input = Path::new(&cli.input);
if !input.is_file() {
return Err("输入的文件不是有效的文件路径!".into());
}
// 从 input 读取 cvrf并转换为 cusa
let mut cvrf = CVRF::new();
cvrf.load_xml(&cli.input)?;
let cusa = cvrf.sainfo();
let data = serde_json::to_string_pretty(&cusa)?;
// 是否将 cusa 输出至指定文件
if let Some(output) = &cli.output {
let output = Path::new(output);
// output 所在父路径须提前创建
let parent = output.parent().unwrap();
if !parent.exists() {
return Err("无法访问输出文件所在路径,请确认!".into());
}
// 写入文件
let mut json_file = fs::OpenOptions::new().read(true).write(true).create(true).open(output)?;
json_file.write(data.as_bytes())?;
json_file.flush()?;
// 在输出到文件模式下,默认不再标准输出打印 CUSA
if !cli.print {
return Ok(())
}
}
// 在标准输出打印 CUSA
println!("{}", data);
Ok(())
}
fn sadb(cli: &cli::SaDbCli) -> Result<()> {
let _ = cli;
Ok(()) Ok(())
} }