Skip to main content

max / makenotwork

11.9 KB · 343 lines History Blame Raw
1 //! Turning the ten value kinds into something on screen.
2 //!
3 //! This module is the entire reason producers are forbidden from formatting
4 //! their own values. Every `progress` in the UI gets the same bar, every
5 //! `instant` the same relative phrasing, every `ident` the same truncation —
6 //! and consistency survives a new producer written a year from now by someone
7 //! who never read this file, because the producer never gets a say.
8 //!
9 //! Everything here is a pure function. `instant` takes `now` as an argument
10 //! rather than reading the clock, which is what keeps the whole render
11 //! snapshot-testable.
12
13 use chrono::{DateTime, Utc};
14 use ops_status::{Status, Value};
15 use ratatui::style::{Color, Modifier, Style};
16
17 /// The one place a status becomes a color.
18 pub(crate) fn status_style(status: Status) -> Style {
19 match status {
20 Status::Ok => Style::default().fg(Color::Green),
21 // Cyan: adjacent to green rather than to the alarm colors, because a
22 // build waiting on its upload is finished work, not broken work.
23 Status::Undistributed => Style::default().fg(Color::Cyan),
24 Status::Degraded => Style::default().fg(Color::Yellow),
25 Status::Failed => Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
26 Status::Pending => Style::default().fg(Color::Blue),
27 // Magenta, not gray: an unreachable source is not a quiet absence, it
28 // is the loudest thing a viewer can fail to tell you.
29 Status::Unknown => Style::default().fg(Color::Magenta),
30 }
31 }
32
33 /// A short, fixed-width-ish marker so columns line up.
34 pub(crate) fn status_mark(status: Status) -> &'static str {
35 match status {
36 Status::Ok => "ok",
37 Status::Undistributed => "dist",
38 Status::Degraded => "degr",
39 Status::Failed => "FAIL",
40 Status::Pending => "pend",
41 Status::Unknown => "????",
42 }
43 }
44
45 /// Render one value. `width` is the budget for things that elide.
46 pub(crate) fn render(value: &Value, now: DateTime<Utc>, width: usize) -> String {
47 match value {
48 Value::Text { value } => value.clone(),
49 Value::Ident { value, abbrev_to } => abbreviate(value, abbrev_to.unwrap_or(12)),
50 Value::Version { value } => value.clone(),
51 Value::Instant { value } => relative(*value, now),
52 Value::Duration { seconds } => duration(*seconds),
53 Value::Progress { value, max, unit } => progress(*value, *max, unit.as_deref(), width),
54 Value::Quantity { value, unit } => quantity(*value, unit.as_deref()),
55 Value::State { value } => status_mark(*value).to_string(),
56 Value::Link { url, text } => text.clone().unwrap_or_else(|| url.clone()),
57 Value::Path { value } => middle_elide(value, width.max(12)),
58 }
59 }
60
61 /// The style a value carries on its own, if any.
62 pub(crate) fn style(value: &Value) -> Style {
63 match value {
64 Value::State { value } => status_style(*value),
65 Value::Ident { .. } | Value::Path { .. } => Style::default().fg(Color::Cyan),
66 Value::Link { .. } => Style::default()
67 .fg(Color::Cyan)
68 .add_modifier(Modifier::UNDERLINED),
69 _ => Style::default(),
70 }
71 }
72
73 /// Truncate an identifier at a character boundary.
74 ///
75 /// Char-wise rather than byte-wise: a digest is ASCII, but nothing in the
76 /// contract promises that, and slicing a multi-byte value at a byte index
77 /// panics.
78 pub(crate) fn abbreviate(value: &str, to: usize) -> String {
79 if value.chars().count() <= to {
80 return value.to_string();
81 }
82 value.chars().take(to).collect()
83 }
84
85 /// Elide the middle of a path, keeping both ends: the leading directories say
86 /// where you are and the basename says what it is. Truncating either end alone
87 /// throws away the half you needed.
88 pub(crate) fn middle_elide(value: &str, max: usize) -> String {
89 let chars: Vec<char> = value.chars().collect();
90 if chars.len() <= max {
91 return value.to_string();
92 }
93 if max <= 3 {
94 return "...".into();
95 }
96 let keep = max - 3;
97 let head = keep.div_ceil(2);
98 let tail = keep - head;
99 let mut out: String = chars[..head].iter().collect();
100 out.push_str("...");
101 out.extend(&chars[chars.len() - tail..]);
102 out
103 }
104
105 /// "3m ago", "in 2m", "just now".
106 pub(crate) fn relative(at: DateTime<Utc>, now: DateTime<Utc>) -> String {
107 let delta = now - at;
108 let secs = delta.num_seconds();
109 if secs.abs() < 5 {
110 return "just now".into();
111 }
112 let magnitude = duration(secs.abs());
113 if secs > 0 {
114 format!("{magnitude} ago")
115 } else {
116 format!("in {magnitude}")
117 }
118 }
119
120 /// Humanize a span. Two units at most: "2h 14m" is useful, "2h 14m 7s" is
121 /// noise at every scale where hours matter.
122 pub(crate) fn duration(seconds: i64) -> String {
123 let s = seconds.abs();
124 let (d, h, m, sec) = (s / 86_400, (s % 86_400) / 3600, (s % 3600) / 60, s % 60);
125 match (d, h, m) {
126 (0, 0, 0) => format!("{sec}s"),
127 (0, 0, _) => format!("{m}m {sec}s"),
128 (0, _, 0) => format!("{h}h"),
129 (0, _, _) => format!("{h}h {m}m"),
130 (_, 0, _) => format!("{d}d"),
131 (_, _, _) => format!("{d}d {h}h"),
132 }
133 }
134
135 /// A magnitude with its unit. The number is humanized; the unit is the
136 /// producer's, verbatim.
137 pub(crate) fn quantity(value: f64, unit: Option<&str>) -> String {
138 let n = humanize_number(value);
139 match unit {
140 Some(u) => format!("{n} {u}"),
141 None => n,
142 }
143 }
144
145 fn humanize_number(value: f64) -> String {
146 let abs = value.abs();
147 let (scaled, suffix) = if abs >= 1e9 {
148 (value / 1e9, "G")
149 } else if abs >= 1e6 {
150 (value / 1e6, "M")
151 } else if abs >= 1_000.0 {
152 (value / 1_000.0, "k")
153 } else {
154 (value, "")
155 };
156 let rendered = if scaled.fract().abs() < 0.05 {
157 format!("{scaled:.0}")
158 } else {
159 format!("{scaled:.1}")
160 };
161 format!("{rendered}{suffix}")
162 }
163
164 /// A progress bar plus its numbers, e.g. `[####------] 31/48 hour`.
165 pub(crate) fn progress(value: f64, max: f64, unit: Option<&str>, width: usize) -> String {
166 let numbers = match unit {
167 Some(u) => format!("{}/{} {u}", humanize_number(value), humanize_number(max)),
168 None => format!("{}/{}", humanize_number(value), humanize_number(max)),
169 };
170
171 // The bar is whatever is left after the numbers, floored at something still
172 // readable and capped so it does not sprawl across a wide terminal.
173 let bar_width = width.saturating_sub(numbers.len() + 3).clamp(4, 24);
174 let fraction = if max > 0.0 {
175 (value / max).clamp(0.0, 1.0)
176 } else {
177 0.0
178 };
179 let filled = (fraction * bar_width as f64).round() as usize;
180 let bar: String = "#".repeat(filled) + &"-".repeat(bar_width - filled);
181 format!("[{bar}] {numbers}")
182 }
183
184 /// How a progress value should be colored: complete is done, not merely far
185 /// along.
186 pub(crate) fn progress_style(value: f64, max: f64) -> Style {
187 if max > 0.0 && value >= max {
188 Style::default().fg(Color::Green)
189 } else {
190 Style::default().fg(Color::Blue)
191 }
192 }
193
194 #[cfg(test)]
195 mod tests {
196 use super::*;
197 use chrono::TimeDelta;
198
199 fn now() -> DateTime<Utc> {
200 "2026-07-21T18:00:00Z".parse().unwrap()
201 }
202
203 #[test]
204 fn durations_stop_at_two_units() {
205 assert_eq!(duration(45), "45s");
206 assert_eq!(duration(125), "2m 5s");
207 assert_eq!(duration(7200), "2h");
208 assert_eq!(duration(8040), "2h 14m");
209 assert_eq!(duration(172_800), "2d");
210 assert_eq!(duration(180_000), "2d 2h");
211 }
212
213 #[test]
214 fn relative_time_reads_in_both_directions() {
215 let base = now();
216 assert_eq!(relative(base, base), "just now");
217 assert_eq!(relative(base - TimeDelta::minutes(3), base), "3m 0s ago");
218 // A producer whose clock runs ahead must not render as a negative age.
219 assert_eq!(relative(base + TimeDelta::minutes(2), base), "in 2m 0s");
220 }
221
222 #[test]
223 fn identifiers_truncate_at_a_character_boundary() {
224 assert_eq!(abbreviate("a3f9c21b7e4d8056", 8), "a3f9c21b");
225 assert_eq!(abbreviate("short", 8), "short");
226 // Multi-byte: byte slicing here would panic.
227 assert_eq!(abbreviate("ααααββββ", 4), "αααα");
228 }
229
230 #[test]
231 fn paths_keep_both_ends() {
232 let path = "/srv/sando/releases/a3f9c21b7e4d8056/bin/makenotwork";
233 let out = middle_elide(path, 30);
234 assert_eq!(out.chars().count(), 30);
235 assert!(out.starts_with("/srv/sando"), "{out}");
236 assert!(out.ends_with("makenotwork"), "{out}");
237 assert!(out.contains("..."));
238 }
239
240 #[test]
241 fn a_short_path_is_left_alone() {
242 assert_eq!(middle_elide("/etc/sando", 30), "/etc/sando");
243 }
244
245 #[test]
246 fn quantities_humanize_the_number_and_keep_the_producers_unit() {
247 assert_eq!(quantity(43.5, Some("MB")), "43.5 MB");
248 assert_eq!(quantity(1_200.0, None), "1.2k");
249 assert_eq!(quantity(2_000_000.0, None), "2M");
250 assert_eq!(quantity(7.0, Some("node")), "7 node");
251 }
252
253 #[test]
254 fn progress_renders_a_bar_and_its_numbers() {
255 let out = progress(31.0, 48.0, Some("hour"), 40);
256 assert!(out.contains("31/48 hour"), "{out}");
257 assert!(out.starts_with('['), "{out}");
258 assert!(out.contains('#') && out.contains('-'), "{out}");
259 }
260
261 #[test]
262 fn progress_survives_nonsense_without_panicking() {
263 // A producer bug must not take the viewer down.
264 assert!(progress(5.0, 0.0, None, 40).contains("5/0"));
265 assert!(progress(-1.0, 10.0, None, 40).starts_with('['));
266 assert!(progress(99.0, 10.0, None, 40).starts_with('['));
267 // Width smaller than the numbers still yields a bar, not a panic.
268 assert!(progress(31.0, 48.0, Some("hour"), 1).starts_with('['));
269 }
270
271 #[test]
272 fn a_complete_bar_reads_as_done() {
273 assert_eq!(
274 progress_style(48.0, 48.0),
275 Style::default().fg(Color::Green)
276 );
277 assert_eq!(progress_style(31.0, 48.0), Style::default().fg(Color::Blue));
278 }
279
280 #[test]
281 fn every_kind_renders_to_something_non_empty() {
282 let values = vec![
283 Value::Text { value: "x".into() },
284 Value::Ident {
285 value: "a3f9c21b7e4d8056".into(),
286 abbrev_to: Some(8),
287 },
288 Value::Version {
289 value: "0.10.14".into(),
290 },
291 Value::Instant {
292 value: now() - TimeDelta::minutes(3),
293 },
294 Value::Duration { seconds: 3600 },
295 Value::Progress {
296 value: 31.0,
297 max: 48.0,
298 unit: Some("hour".into()),
299 },
300 Value::Quantity {
301 value: 43.5,
302 unit: Some("MB".into()),
303 },
304 Value::State {
305 value: Status::Degraded,
306 },
307 Value::Link {
308 url: "https://makenot.work".into(),
309 text: None,
310 },
311 Value::Path {
312 value: "/srv/sando".into(),
313 },
314 ];
315 for value in values {
316 let out = render(&value, now(), 40);
317 assert!(!out.is_empty(), "{} rendered empty", value.kind());
318 assert!(!out.contains('\n'), "{} rendered multi-line", value.kind());
319 }
320 }
321
322 #[test]
323 fn a_link_prefers_its_text_and_falls_back_to_the_url() {
324 let with = Value::Link {
325 url: "https://makenot.work".into(),
326 text: Some("site".into()),
327 };
328 assert_eq!(render(&with, now(), 40), "site");
329 let without = Value::Link {
330 url: "https://makenot.work".into(),
331 text: None,
332 };
333 assert_eq!(render(&without, now(), 40), "https://makenot.work");
334 }
335
336 #[test]
337 fn an_unknown_status_is_loud_not_gray() {
338 // A source nobody can reach must not read as a quiet absence.
339 assert_eq!(status_style(Status::Unknown).fg, Some(Color::Magenta));
340 assert_eq!(status_style(Status::Ok).fg, Some(Color::Green));
341 }
342 }
343