From edb907941bf3003f1639e570a3f7dad92d3def46 Mon Sep 17 00:00:00 2001 From: Jia Chao Date: Fri, 28 Jun 2024 10:41:16 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=AD=90=E5=91=BD=E4=BB=A4?= =?UTF-8?q?=20convert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jia Chao --- Cargo.toml | 2 +- src/lib.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index cf56a65..d20c860 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,4 +8,4 @@ edition = "2021" [dependencies] clap = { version = "4.0", features = ["derive"] } 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" } diff --git a/src/lib.rs b/src/lib.rs index 6189d8e..52a3995 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,11 @@ +use std::fs; +use std::io::Write; +use std::path::Path; + use cvrf_xmlparser::{ CVRF, - SaInfo as CUSA, + // SaInfo 即为 CUSA + // SaInfo, }; pub mod cli; @@ -14,5 +19,55 @@ pub type Result = std::result::Result; pub fn cumain() -> Result<()> { 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(()) }