From 04b4262cdf4bbb4e2698d8ce51a261bf294a2da3 Mon Sep 17 00:00:00 2001 From: Robin Krahl Date: Sat, 5 Sep 2020 13:18:41 +0200 Subject: Add --output-format argument This patch adds the --output-format argument that makes it possible to select a format for the data that nitrocli prints to stdout. Currently, the only supported format is text output, i. e. a human-readable representation. TODO: man page, changelog --- src/output.rs | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) (limited to 'src/output.rs') diff --git a/src/output.rs b/src/output.rs index 77fb93b..7c85a82 100644 --- a/src/output.rs +++ b/src/output.rs @@ -7,19 +7,28 @@ use std::fmt; +use crate::args; use crate::Context; /// A trait for objects that can be printed as nitrocli’s output. pub trait Output { - /// Formats this object as a string that can be printed to the standard output. - fn format(&self) -> anyhow::Result; + /// Formats this object using the given output format. + fn format(&self, format: args::OutputFormat) -> anyhow::Result; - /// Prints this object to the output set in the given context. + /// Prints this object to the output set in the given context using the output format set in the + /// context configuration. /// /// The default implementation for this method prints the return value of `format` to /// `ctx.stdout`. fn print(&self, ctx: &mut Context<'_>) -> anyhow::Result<()> { - println!(ctx, "{}", self.format()?.trim_end()).map_err(From::from) + println!( + ctx, + "{}", + self + .format(ctx.config.output_format.unwrap_or(args::OutputFormat::Text))? + .trim_end() + ) + .map_err(From::from) } } @@ -54,8 +63,10 @@ impl Value { } impl Output for Value { - fn format(&self) -> anyhow::Result { - Ok(self.0.to_string()) + fn format(&self, format: args::OutputFormat) -> anyhow::Result { + match format { + args::OutputFormat::Text => Ok(self.0.to_string()), + } } } @@ -77,13 +88,17 @@ impl Table { } impl Output for Table { - fn format(&self) -> anyhow::Result { - if self.items.is_empty() { - Ok(self.empty_message.clone()) - } else { - let headers = T::headers().into_iter().map(ToOwned::to_owned).collect(); - let values = self.items.iter().map(TableItem::values); - Ok(print_table(headers, values)) + fn format(&self, format: args::OutputFormat) -> anyhow::Result { + match format { + args::OutputFormat::Text => { + if self.items.is_empty() { + Ok(self.empty_message.clone()) + } else { + let headers = T::headers().into_iter().map(ToOwned::to_owned).collect(); + let values = self.items.iter().map(TableItem::values); + Ok(print_table(headers, values)) + } + } } } } -- cgit v1.2.1