- use std::io::IsTerminal;
- use std::sync::OnceLock;
- /// Zero-dependency ANSI terminal styler respecting `NO_COLOR` and TTY detection.
- #[derive(Debug, Clone, Copy)]
- pub struct Styled<'a> {
- text: &'a str,
- codes: &'static str,
- }
- fn color_enabled() -> bool {
- static ENABLED: OnceLock<bool> = OnceLock::new();
- *ENABLED.get_or_init(|| {
- std::env::var_os("NO_COLOR").is_none()
- && (std::io::stdout().is_terminal() || std::io::stderr().is_terminal())
- })
- }
- impl std::fmt::Display for Styled<'_> {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- if color_enabled() && !self.codes.is_empty() {
- write!(f, "\x1b[{}m{}\x1b[0m", self.codes, self.text)
- } else {
- f.write_str(self.text)
- }
- }
- }
- pub fn bold(text: &str) -> Styled<'_> {
- Styled { text, codes: "1" }
- }
- pub fn bold_underlined(text: &str) -> Styled<'_> {
- Styled { text, codes: "1;4" }
- }
- pub fn dim(text: &str) -> Styled<'_> {
- Styled { text, codes: "2" }
- }
- pub fn green(text: &str) -> Styled<'_> {
- Styled { text, codes: "32" }
- }
- pub fn green_bold(text: &str) -> Styled<'_> {
- Styled {
- text,
- codes: "1;32",
- }
- }
- pub fn red(text: &str) -> Styled<'_> {
- Styled { text, codes: "31" }
- }
- pub fn red_bold(text: &str) -> Styled<'_> {
- Styled {
- text,
- codes: "1;31",
- }
- }
- pub fn yellow(text: &str) -> Styled<'_> {
- Styled { text, codes: "33" }
- }
- pub fn yellow_bold(text: &str) -> Styled<'_> {
- Styled {
- text,
- codes: "1;33",
- }
- }
- pub fn cyan(text: &str) -> Styled<'_> {
- Styled { text, codes: "36" }
- }
- pub fn cyan_bold(text: &str) -> Styled<'_> {
- Styled {
- text,
- codes: "1;36",
- }
- }
- pub fn blue(text: &str) -> Styled<'_> {
- Styled { text, codes: "34" }
- }
- pub fn magenta_bold(text: &str) -> Styled<'_> {
- Styled {
- text,
- codes: "1;35",
- }
- }