1
0
mirror of https://github.com/jht5945/rust_util.git synced 2025-12-27 15:40:03 +08:00

add terminal check

This commit is contained in:
2019-11-23 21:09:42 +08:00
parent c969e39efe
commit 9c1bed76d1
3 changed files with 27 additions and 9 deletions

View File

@@ -5,5 +5,7 @@ authors = ["Hatter Jiang <jht5945@gmail.com>"]
edition = "2018" edition = "2018"
[dependencies] [dependencies]
libc = "0.2.65"
term = "0.5.2" term = "0.5.2"
term_size = "0.3.1" term_size = "0.3.1"
lazy_static = "1.3.0"

View File

@@ -1,3 +1,5 @@
#[macro_use]
extern crate lazy_static;
extern crate term; extern crate term;
use std::{ use std::{

View File

@@ -2,19 +2,33 @@ use std::{
io::{self, Write}, io::{self, Write},
}; };
lazy_static! {
pub static ref IS_ATTY: bool = is_atty();
}
pub enum MessageType { INFO, OK, WARN, ERROR, DEBUG, } 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<term::color::Color>, is_bold: bool, m: &str) { pub fn print_color(color: Option<term::color::Color>, is_bold: bool, m: &str) {
let mut t = term::stdout().unwrap(); let mut t = term::stdout().unwrap();
match color { match *IS_ATTY {
Some(c) => t.fg(c).unwrap(), true => {
None => (), match color {
} Some(c) => t.fg(c).unwrap(),
if is_bold { None => (),
t.attr(term::Attr::Bold).unwrap(); }
} if is_bold {
write!(t, "{}", m).unwrap(); t.attr(term::Attr::Bold).unwrap();
t.reset().unwrap(); }
write!(t, "{}", m).unwrap();
t.reset().unwrap();
},
false => write!(t, "{}", m).unwrap(),
};
} }
pub fn print_color_and_flush(color: Option<term::color::Color>, is_bold: bool, m: &str) { pub fn print_color_and_flush(color: Option<term::color::Color>, is_bold: bool, m: &str) {