make use of termcolor crate to disable colors (#236)

* table: replace custom color by termcolor

* table: deactivate colors if not tty

* table: rename printable to print, add more comments

* table: make use of writters, fix tests

* doc: update changelog

* doc: add page to wiki
This commit is contained in:
Clément DOUIN
2021-10-24 00:17:12 +02:00
committed by GitHub
parent 09d3de5e6f
commit 192445d7e4
11 changed files with 303 additions and 247 deletions
+3
View File
@@ -7,3 +7,6 @@ pub use output_utils::*;
pub mod output_service;
pub use output_service::*;
pub mod print;
pub use print::*;
+18 -3
View File
@@ -1,10 +1,14 @@
use anyhow::{anyhow, Error, Result};
use atty::Stream;
use log::debug;
use serde::Serialize;
use std::{
convert::{TryFrom, TryInto},
fmt,
};
use termcolor::{ColorChoice, StandardStream};
use crate::output::Print;
#[derive(Debug, PartialEq)]
pub enum OutputFmt {
@@ -58,7 +62,7 @@ impl<T: Serialize> OutputJson<T> {
}
pub trait OutputServiceInterface {
fn print<T: Serialize + fmt::Display>(&self, data: T) -> Result<()>;
fn print<T: Serialize + Print>(&self, data: T) -> Result<()>;
fn is_json(&self) -> bool;
}
@@ -70,10 +74,21 @@ pub struct OutputService {
impl OutputServiceInterface for OutputService {
/// Print the provided item out according to the formatting setting when you created this
/// struct.
fn print<T: Serialize + fmt::Display>(&self, data: T) -> Result<()> {
fn print<T: Serialize + Print>(&self, data: T) -> Result<()> {
match self.fmt {
OutputFmt::Plain => {
println!("{}", data)
data.print(&mut StandardStream::stdout(if atty::isnt(Stream::Stdin) {
// Colors should be deactivated if the terminal is not a tty.
ColorChoice::Never
} else {
// Otherwise let's `termcolor` decide by inspecting the environment. From the [doc]:
// - If `NO_COLOR` is set to any value, then colors will be suppressed.
// - If `TERM` is set to dumb, then colors will be suppressed.
// - In non-Windows environments, if `TERM` is not set, then colors will be suppressed.
//
// [doc]: https://github.com/BurntSushi/termcolor#automatic-color-selection
ColorChoice::Auto
}))?;
}
OutputFmt::Json => {
print!("{}", serde_json::to_string(&OutputJson::new(data))?)
+28
View File
@@ -0,0 +1,28 @@
use anyhow::{Context, Result};
use std::io;
use termcolor::{StandardStream, WriteColor};
pub trait WriteWithColor: io::Write + WriteColor {}
impl WriteWithColor for StandardStream {}
pub trait Print {
fn print<W: WriteWithColor>(&self, writter: &mut W) -> Result<()>;
fn println<W: WriteWithColor>(&self, writter: &mut W) -> Result<()> {
println!();
self.print(writter)
}
}
impl Print for &str {
fn print<W: WriteWithColor>(&self, writter: &mut W) -> Result<()> {
write!(writter, "{}", self).context(format!(r#"cannot print string "{}""#, self))
}
}
impl Print for String {
fn print<W: WriteWithColor>(&self, writter: &mut W) -> Result<()> {
self.as_str().print(writter)
}
}