Skip to content

Commit

Permalink
feat: add JSON printer in xlinectl
Browse files Browse the repository at this point in the history
Signed-off-by: bsbds <[email protected]>
  • Loading branch information
bsbds committed Oct 18, 2023
1 parent d6fa954 commit 342d83f
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
6 changes: 4 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions xlinectl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ async-trait = "0.1.68"
clap = { version = "4.3.2", features = ["derive", "string"] }
itertools = "0.10.5"
regex = "1.8.4"
serde = { version = "1.0.137", features = ["derive"] }
serde_json = "1.0.107"
shlex = "1.1.0"
thiserror = "1.0.37"
tokio = { version = "1", features = ["rt"] }
Expand Down
3 changes: 2 additions & 1 deletion xlinectl/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ fn cli() -> Command {
.arg(arg!(--printer_type <TYPE> "The format of the result that will be printed")
.global(true)
.help_heading(GLOBAL_HEADING)
.value_parser(["SIMPLE", "FIELD"])
.value_parser(["SIMPLE", "FIELD", "JSON"])
.default_value("SIMPLE"))

.subcommand(get::command())
Expand Down Expand Up @@ -267,6 +267,7 @@ async fn main() -> Result<()> {
{
"SIMPLE" => PrinterType::Simple,
"FIELD" => PrinterType::Field,
"JSON" => PrinterType::Json,
_ => unreachable!("already checked by clap"),
};
set_printer_type(printer_type);
Expand Down
13 changes: 12 additions & 1 deletion xlinectl/src/utils/printer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::sync::OnceLock;

use serde::Serialize;
use xlineapi::{
AuthDisableResponse, AuthEnableResponse, AuthRoleAddResponse, AuthRoleDeleteResponse,
AuthRoleGetResponse, AuthRoleGrantPermissionResponse, AuthRoleListResponse,
Expand All @@ -21,6 +22,8 @@ pub(crate) enum PrinterType {
Simple,
/// Filed printer, which print every fields of the result
Field,
/// JSON printer, which print in JSON format
Json,
}

/// Set the type of the printer
Expand All @@ -29,11 +32,18 @@ pub(crate) fn set_printer_type(printer_type: PrinterType) {
}

/// The printer implementation trait
pub(crate) trait Printer {
pub(crate) trait Printer: Serialize {
/// Print the simplified result
fn simple(&self);
/// Print every fields of the result
fn field(&self);
/// Print the result in JSON format
fn json(&self) {
println!(
"{}",
serde_json::to_string_pretty(self).expect("failed to serialize result")
);
}
/// Print according to the config set
fn print(&self) {
match *PRINTER_TYPE
Expand All @@ -42,6 +52,7 @@ pub(crate) trait Printer {
{
PrinterType::Simple => self.simple(),
PrinterType::Field => self.field(),
PrinterType::Json => self.json(),
}
}
}
Expand Down

0 comments on commit 342d83f

Please sign in to comment.