forgeFRENBrowse the repositories

roneocratesroneo-clisrcstyle.rs

0518da6beb3fd562b82c5b5c2798b72e0d1591b2

At commit 0518da6

94 lines · 1.9 KiBRustRaw
  1. use std::io::IsTerminal;
  2. use std::sync::OnceLock;
  3. /// Zero-dependency ANSI terminal styler respecting `NO_COLOR` and TTY detection.
  4. #[derive(Debug, Clone, Copy)]
  5. pub struct Styled<'a> {
  6. text: &'a str,
  7. codes: &'static str,
  8. }
  9. fn color_enabled() -> bool {
  10. static ENABLED: OnceLock<bool> = OnceLock::new();
  11. *ENABLED.get_or_init(|| {
  12. std::env::var_os("NO_COLOR").is_none()
  13. && (std::io::stdout().is_terminal() || std::io::stderr().is_terminal())
  14. })
  15. }
  16. impl std::fmt::Display for Styled<'_> {
  17. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  18. if color_enabled() && !self.codes.is_empty() {
  19. write!(f, "\x1b[{}m{}\x1b[0m", self.codes, self.text)
  20. } else {
  21. f.write_str(self.text)
  22. }
  23. }
  24. }
  25. pub fn bold(text: &str) -> Styled<'_> {
  26. Styled { text, codes: "1" }
  27. }
  28. pub fn bold_underlined(text: &str) -> Styled<'_> {
  29. Styled { text, codes: "1;4" }
  30. }
  31. pub fn dim(text: &str) -> Styled<'_> {
  32. Styled { text, codes: "2" }
  33. }
  34. pub fn green(text: &str) -> Styled<'_> {
  35. Styled { text, codes: "32" }
  36. }
  37. pub fn green_bold(text: &str) -> Styled<'_> {
  38. Styled {
  39. text,
  40. codes: "1;32",
  41. }
  42. }
  43. pub fn red(text: &str) -> Styled<'_> {
  44. Styled { text, codes: "31" }
  45. }
  46. pub fn red_bold(text: &str) -> Styled<'_> {
  47. Styled {
  48. text,
  49. codes: "1;31",
  50. }
  51. }
  52. pub fn yellow(text: &str) -> Styled<'_> {
  53. Styled { text, codes: "33" }
  54. }
  55. pub fn yellow_bold(text: &str) -> Styled<'_> {
  56. Styled {
  57. text,
  58. codes: "1;33",
  59. }
  60. }
  61. pub fn cyan(text: &str) -> Styled<'_> {
  62. Styled { text, codes: "36" }
  63. }
  64. pub fn cyan_bold(text: &str) -> Styled<'_> {
  65. Styled {
  66. text,
  67. codes: "1;36",
  68. }
  69. }
  70. pub fn blue(text: &str) -> Styled<'_> {
  71. Styled { text, codes: "34" }
  72. }
  73. pub fn magenta_bold(text: &str) -> Styled<'_> {
  74. Styled {
  75. text,
  76. codes: "1;35",
  77. }
  78. }