clap/src/fmt.rs

74 lines
2.2 KiB
Rust
Raw Normal View History

use std::fmt;
#[cfg(all(feature = "color", not(target_os = "windows")))]
2015-10-28 14:23:59 +00:00
use ansi_term::Colour::{Green, Red, Yellow};
#[cfg(all(feature = "color", not(target_os = "windows")))]
use ansi_term::ANSIString;
/// Defines styles for different types of error messages. Defaults to Error=Red, Warning=Yellow,
/// and Good=Green
#[derive(Debug)]
2016-05-02 16:48:47 +00:00
#[doc(hidden)]
pub enum Format<T> {
/// Defines the style used for errors, defaults to Red
2015-09-07 01:07:46 +00:00
Error(T),
/// Defines the style used for warnings, defaults to Yellow
2015-09-07 01:07:46 +00:00
Warning(T),
/// Defines the style used for good values, defaults to Green
2015-09-07 01:07:46 +00:00
Good(T),
}
#[cfg(all(feature = "color", not(target_os = "windows")))]
impl<T: AsRef<str>> Format<T> {
fn format(&self) -> ANSIString {
match *self {
Format::Error(ref e) => Red.bold().paint(e.as_ref()),
Format::Warning(ref e) => Yellow.paint(e.as_ref()),
Format::Good(ref e) => Green.paint(e.as_ref()),
}
}
}
#[cfg(all(feature = "color", not(target_os = "windows")))]
impl<T: AsRef<str>> fmt::Display for Format<T> {
2015-10-28 14:23:59 +00:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.format())
}
}
#[cfg(any(not(feature = "color"), target_os = "windows"))]
impl<T: fmt::Display> Format<T> {
fn format(&self) -> &T {
match *self {
Format::Error(ref e) => e,
Format::Warning(ref e) => e,
Format::Good(ref e) => e,
}
}
}
#[cfg(any(not(feature = "color"), target_os = "windows"))]
impl<T: fmt::Display> fmt::Display for Format<T> {
2015-10-28 14:23:59 +00:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.format())
}
}
2015-09-04 15:38:48 +00:00
#[cfg(all(test, feature = "color", not(target_os = "windows")))]
2015-09-04 15:38:48 +00:00
mod test {
use super::Format;
2015-10-28 14:23:59 +00:00
use ansi_term::Colour::{Green, Red, Yellow};
2015-09-04 15:38:48 +00:00
#[test]
fn colored_output() {
let err = Format::Error("error");
2015-10-28 14:23:59 +00:00
assert_eq!(&*format!("{}", err),
&*format!("{}", Red.bold().paint("error")));
2015-09-04 15:38:48 +00:00
let good = Format::Good("good");
assert_eq!(&*format!("{}", good), &*format!("{}", Green.paint("good")));
let warn = Format::Warning("warn");
assert_eq!(&*format!("{}", warn), &*format!("{}", Yellow.paint("warn")));
}
2015-09-07 01:07:46 +00:00
}