From 4ee7008070560b16fd7f10745c67a0a1d38d83e4 Mon Sep 17 00:00:00 2001 From: chris west Date: Fri, 7 Aug 2020 18:32:56 -0700 Subject: [PATCH] --no-color to hide colors in log messages --- README.md | 1 + src/color.rs | 25 +++++++++++++++++++++++-- src/main.rs | 2 ++ 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0d500ea..de09ce0 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,7 @@ of Gopher! -h, --host HOST Hostname for links. [Default: {host}] -p, --port PORT Port for links. [Default: {port}] -b, --bind ADDRESS Socket address to bind to. [Default: {bind}] + --no-color Don't show colors in log messages. Other flags: diff --git a/src/color.rs b/src/color.rs index 4a5b0a4..4acd046 100644 --- a/src/color.rs +++ b/src/color.rs @@ -5,7 +5,24 @@ //! println!("{}Error: {}{}", color::Red, "Something broke.", color::Reset); //! ``` -use std::fmt; +use std::{ + fmt, + sync::atomic::{AtomicBool, Ordering as AtomicOrdering}, +}; + +/// Whether to show colors or not. +/// Defaults to true. +static SHOW_COLORS: AtomicBool = AtomicBool::new(true); + +/// Hide colors. +pub fn hide_colors() { + SHOW_COLORS.swap(false, AtomicOrdering::Relaxed); +} + +/// Are we showing colors are not? +pub fn showing_colors() -> bool { + SHOW_COLORS.load(AtomicOrdering::Relaxed) +} macro_rules! color { ($t:ident, $code:expr) => { @@ -13,7 +30,11 @@ macro_rules! color { pub struct $t; impl fmt::Display for $t { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "\x1b[{}m", $code) + if showing_colors() { + write!(f, "\x1b[{}m", $code) + } else { + write!(f, "") + } } } }; diff --git a/src/main.rs b/src/main.rs index e38731c..ee78500 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ fn main() { match arg.as_ref() { "--version" | "-v" | "-version" => return print_version(), "--help" | "-help" => return print_help(), + "--no-color" | "-no-color" => phd::color::hide_colors(), "--render" | "-render" | "-r" => { if let Some(path) = args.next() { render = path; @@ -94,6 +95,7 @@ Options: -h, --host HOST Hostname for links. [Default: {host}] -p, --port PORT Port for links. [Default: {port}] -b, --bind ADDRESS Socket address to bind to. [Default: {bind}] + --no-color Don't show colors in log messages. Other flags: