rust cli: Support showing in JSON format

Add support of `show --json` argument.

Signed-off-by: Gris Ge <fge@redhat.com>
This commit is contained in:
Gris Ge 2022-01-18 09:53:16 +08:00
parent e3b931ebb1
commit a5b1e59cb6
3 changed files with 23 additions and 2 deletions

View File

@ -15,3 +15,4 @@ clap = "2.33"
serde = { version = "1.0", features = ["derive"] }
env_logger = "0.9.0"
log = "0.4.14"
serde_json = "1.0.75"

View File

@ -41,3 +41,11 @@ impl From<clap::Error> for CliError {
}
}
}
impl From<serde_json::Error> for CliError {
fn from(e: serde_json::Error) -> Self {
Self {
msg: format!("serde_json::Error {}", e),
}
}
}

View File

@ -42,7 +42,13 @@ fn main() {
.short("k")
.long("kernel")
.takes_value(false)
.help("Show kernel network state only"),
.help("Show kernel network state only")
)
.arg(
clap::Arg::with_name("JSON")
.long("json")
.takes_value(false)
.help("Show state in json format"),
),
)
.subcommand(
@ -280,7 +286,13 @@ fn show(matches: &clap::ArgMatches) -> Result<String, CliError> {
new_net_state.append_interface_data(iface.clone())
}
}
serde_yaml::to_string(&new_net_state)?
if matches.is_present("JSON") {
serde_json::to_string_pretty(&new_net_state)?
} else {
serde_yaml::to_string(&new_net_state)?
}
} else if matches.is_present("JSON") {
serde_json::to_string_pretty(&sort_netstate(net_state)?)?
} else {
serde_yaml::to_string(&sort_netstate(net_state)?)?
})