From 9c1bed76d1408467ff09a97a2783848751de8ba0 Mon Sep 17 00:00:00 2001 From: Hatter Jiang Date: Sat, 23 Nov 2019 21:09:42 +0800 Subject: [PATCH] add terminal check --- Cargo.toml | 2 ++ src/lib.rs | 2 ++ src/util_msg.rs | 32 +++++++++++++++++++++++--------- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 82adfa5..d1bee00 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,5 +5,7 @@ authors = ["Hatter Jiang "] edition = "2018" [dependencies] +libc = "0.2.65" term = "0.5.2" term_size = "0.3.1" +lazy_static = "1.3.0" diff --git a/src/lib.rs b/src/lib.rs index 82e2885..a11b005 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +#[macro_use] +extern crate lazy_static; extern crate term; use std::{ diff --git a/src/util_msg.rs b/src/util_msg.rs index b94d9cd..136e0c9 100644 --- a/src/util_msg.rs +++ b/src/util_msg.rs @@ -2,19 +2,33 @@ use std::{ io::{self, Write}, }; +lazy_static! { + pub static ref IS_ATTY: bool = is_atty(); +} + pub enum MessageType { INFO, OK, WARN, ERROR, DEBUG, } +pub fn is_atty() -> bool{ + let isatty = unsafe { libc::isatty(libc::STDOUT_FILENO as i32) } != 0; + isatty +} + pub fn print_color(color: Option, is_bold: bool, m: &str) { let mut t = term::stdout().unwrap(); - match color { - Some(c) => t.fg(c).unwrap(), - None => (), - } - if is_bold { - t.attr(term::Attr::Bold).unwrap(); - } - write!(t, "{}", m).unwrap(); - t.reset().unwrap(); + match *IS_ATTY { + true => { + match color { + Some(c) => t.fg(c).unwrap(), + None => (), + } + if is_bold { + t.attr(term::Attr::Bold).unwrap(); + } + write!(t, "{}", m).unwrap(); + t.reset().unwrap(); + }, + false => write!(t, "{}", m).unwrap(), + }; } pub fn print_color_and_flush(color: Option, is_bold: bool, m: &str) {