codex_cli/rate_limits/
ansi.rs1use std::io::{self, IsTerminal};
2
3const CURRENT_PROFILE_FG: &str = "\x1b[38;2;199;146;234m";
4
5pub fn should_color() -> bool {
6 if std::env::var_os("NO_COLOR").is_some() {
7 return false;
8 }
9 io::stdout().is_terminal()
10}
11
12pub fn format_name_cell(
13 raw: &str,
14 width: usize,
15 is_current: bool,
16 color_enabled: Option<bool>,
17) -> String {
18 let padded = format!("{:<width$}", raw, width = width);
19
20 let enabled = color_enabled.unwrap_or_else(should_color);
21 if !enabled || !is_current {
22 return padded;
23 }
24
25 format!("{CURRENT_PROFILE_FG}{padded}{}", reset())
26}
27
28pub fn format_percent_cell(raw: &str, width: usize, color_enabled: Option<bool>) -> String {
29 let mut trimmed = raw.to_string();
30 let raw_len = trimmed.chars().count();
31 if raw_len > width {
32 trimmed = trimmed.chars().take(width).collect();
33 }
34 let padded = format!("{:>width$}", trimmed, width = width);
35
36 let enabled = color_enabled.unwrap_or_else(should_color);
37 if !enabled {
38 return padded;
39 }
40
41 let percent = match extract_percent(raw) {
42 Some(value) => value,
43 None => return padded,
44 };
45 let color = match fg_for_percent(percent) {
46 Some(value) => value,
47 None => return padded,
48 };
49
50 format!("{color}{padded}{}", reset())
51}
52
53pub fn format_percent_token(raw: &str, color_enabled: Option<bool>) -> String {
54 let width = raw.chars().count();
55 if width == 0 {
56 return String::new();
57 }
58 format_percent_cell(raw, width, color_enabled)
59}
60
61fn extract_percent(raw: &str) -> Option<i32> {
62 let mut part = raw.rsplit(':').next()?.to_string();
63 part = part
64 .trim()
65 .trim_end_matches('%')
66 .replace(char::is_whitespace, "");
67 part.parse::<i32>().ok()
68}
69
70fn fg_for_percent(percent: i32) -> Option<String> {
71 if percent <= 0 {
72 Some(fg_truecolor(99, 119, 119))
73 } else if percent >= 80 {
74 Some(fg_truecolor(127, 219, 202))
75 } else if percent >= 60 {
76 Some(fg_truecolor(173, 219, 103))
77 } else if percent >= 40 {
78 Some(fg_truecolor(236, 196, 141))
79 } else if percent >= 20 {
80 Some(fg_truecolor(247, 140, 108))
81 } else {
82 Some(fg_truecolor(240, 113, 120))
83 }
84}
85
86fn fg_truecolor(r: u8, g: u8, b: u8) -> String {
87 format!("\x1b[38;2;{r};{g};{b}m")
88}
89
90fn reset() -> &'static str {
91 "\x1b[0m"
92}