Skip to main content

harn_cli/
format.rs

1//! Shared, lightweight formatting helpers for CLI commands.
2//!
3//! Multiple subcommands had grown private copies of the same RFC3339
4//! timestamp / human-friendly duration formatters; consolidating them
5//! here keeps formatting consistent across the user-facing surface.
6
7use std::path::Path;
8use std::time::Duration as StdDuration;
9
10use time::format_description::well_known::Rfc3339;
11use time::OffsetDateTime;
12
13/// Render a UTC instant as RFC3339, falling back to `Display` if formatting
14/// fails (which `time` only does on internally inconsistent components).
15pub(crate) fn format_timestamp_rfc3339(value: OffsetDateTime) -> String {
16    value.format(&Rfc3339).unwrap_or_else(|_| value.to_string())
17}
18
19/// Render a unix-epoch millisecond timestamp as RFC3339.
20pub(crate) fn format_unix_ms_rfc3339(ms: i64) -> String {
21    let seconds = ms.div_euclid(1000);
22    let value = OffsetDateTime::from_unix_timestamp(seconds).unwrap_or(OffsetDateTime::UNIX_EPOCH);
23    format_timestamp_rfc3339(value)
24}
25
26/// Render a `std::time::Duration` as a coarse "5s / 2m / 3h / 1d / 1w" suffix.
27///
28/// Rounds toward zero on the chosen unit so status output does not overstate
29/// elapsed time.
30pub(crate) fn format_duration_coarse(value: StdDuration) -> String {
31    if value.as_secs() == 0 {
32        return format!("{}ms", value.as_millis());
33    }
34    let seconds = value.as_secs();
35    if seconds < 60 {
36        return format!("{seconds}s");
37    }
38    if seconds < 60 * 60 {
39        return format!("{}m", seconds / 60);
40    }
41    if seconds < 60 * 60 * 24 {
42        return format!("{}h", seconds / (60 * 60));
43    }
44    if seconds < 60 * 60 * 24 * 7 {
45        return format!("{}d", seconds / (60 * 60 * 24));
46    }
47    if seconds.is_multiple_of(60 * 60 * 24 * 7) {
48        return format!("{}w", seconds / (60 * 60 * 24 * 7));
49    }
50    format!("{}d", seconds / (60 * 60 * 24))
51}
52
53/// Render a millisecond duration with a single decimal point of precision
54/// for the ">= 1s" cases (used by portal output).
55pub(crate) fn format_duration_ms(duration_ms: u64) -> String {
56    if duration_ms >= 60_000 {
57        format!("{:.1}m", duration_ms as f64 / 60_000.0)
58    } else if duration_ms >= 1_000 {
59        format!("{:.1}s", duration_ms as f64 / 1_000.0)
60    } else {
61        format!("{duration_ms}ms")
62    }
63}
64
65/// Escape the `|` characters in `value` so it can sit inside a single Markdown
66/// table cell without prematurely ending the column. Several report commands
67/// (eval summaries, provider matrices, diagnostics catalogs) build Markdown
68/// tables and had each grown a private copy of this; keep the escaping uniform.
69pub(crate) fn escape_md(value: &str) -> String {
70    value.replace('|', "\\|")
71}
72
73/// Escape `&`, `<`, `>`, `"`, and `'` for embedding text in HTML or XML
74/// output. Uses `&#39;` for the apostrophe because it is valid in both
75/// (`&apos;` is XML-only). The eval-prompt report, MCP landing page, OAuth
76/// callback page, and JUnit report writer had each grown a private copy.
77pub(crate) fn escape_html(value: &str) -> String {
78    let mut out = String::with_capacity(value.len());
79    for ch in value.chars() {
80        match ch {
81            '&' => out.push_str("&amp;"),
82            '<' => out.push_str("&lt;"),
83            '>' => out.push_str("&gt;"),
84            '"' => out.push_str("&quot;"),
85            '\'' => out.push_str("&#39;"),
86            _ => out.push(ch),
87        }
88    }
89    out
90}
91
92/// Escape a string for a TOML basic (double-quoted) string: backslash,
93/// double quote, and the control characters TOML forbids raw in basic
94/// strings. `harn rules` and `harn connector` scaffolding had divergent
95/// copies — the connector one skipped control characters, so a value with a
96/// newline produced invalid TOML.
97pub(crate) fn escape_toml_basic_string(value: &str) -> String {
98    let mut out = String::with_capacity(value.len());
99    for ch in value.chars() {
100        match ch {
101            '"' => out.push_str("\\\""),
102            '\\' => out.push_str("\\\\"),
103            '\n' => out.push_str("\\n"),
104            '\t' => out.push_str("\\t"),
105            '\r' => out.push_str("\\r"),
106            // Remaining C0 control chars (and DEL) must be escaped in TOML
107            // basic strings.
108            c if (c as u32) < 0x20 || c == '\u{7f}' => {
109                out.push_str(&format!("\\u{:04X}", c as u32));
110            }
111            _ => out.push(ch),
112        }
113    }
114    out
115}
116
117/// Render a full TOML basic string literal.
118pub(crate) fn toml_basic_string_literal(value: &str) -> String {
119    format!("\"{}\"", escape_toml_basic_string(value))
120}
121
122/// Normalize path separators in machine-readable output. Harn package and
123/// bundle artifacts use slash-separated logical paths even on Windows.
124pub(crate) fn slash_separators(value: &str) -> String {
125    value.replace('\\', "/")
126}
127
128/// Render a path with slash separators for deterministic JSON/report output.
129pub(crate) fn slash_path(path: &Path) -> String {
130    slash_separators(&path.to_string_lossy())
131}
132
133/// True when a string starts with Windows drive syntax such as `C:\`, `C:/`,
134/// or drive-relative `C:foo`. URL parsers otherwise treat these as scheme `c`.
135pub(crate) fn looks_like_windows_drive_path(value: &str) -> bool {
136    let bytes = value.as_bytes();
137    bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':'
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    #[test]
145    fn timestamp_uses_rfc3339() {
146        let value = OffsetDateTime::UNIX_EPOCH;
147        assert_eq!(format_timestamp_rfc3339(value), "1970-01-01T00:00:00Z");
148    }
149
150    #[test]
151    fn escape_html_handles_all_five_specials() {
152        assert_eq!(
153            escape_html(r#"<a href="x">&'b'</a>"#),
154            "&lt;a href=&quot;x&quot;&gt;&amp;&#39;b&#39;&lt;/a&gt;"
155        );
156    }
157
158    #[test]
159    fn escape_toml_basic_string_escapes_control_characters() {
160        assert_eq!(
161            escape_toml_basic_string("a\"b\\c\nd\te\rf"),
162            "a\\\"b\\\\c\\nd\\te\\rf"
163        );
164        // Other C0 controls (the case the old connector copy missed
165        // entirely) become \uXXXX escapes.
166        assert_eq!(escape_toml_basic_string("bell\u{7}"), "bell\\u0007");
167    }
168
169    #[test]
170    fn toml_basic_string_literal_round_trips_windows_paths() {
171        let raw = r"C:\Users\RUNNER~1\AppData\Local\Temp\.tmpJHS6sR\coding-pack";
172        let parsed: toml::Value =
173            toml::from_str(&format!("path = {}\n", toml_basic_string_literal(raw))).unwrap();
174        assert_eq!(parsed.get("path").and_then(toml::Value::as_str), Some(raw));
175    }
176
177    #[test]
178    fn slash_path_normalizes_windows_separators() {
179        assert_eq!(
180            slash_separators(r"C:\tmp\pkg\lib.harn"),
181            "C:/tmp/pkg/lib.harn"
182        );
183    }
184
185    #[test]
186    fn detects_windows_drive_paths_without_url_parser() {
187        assert!(looks_like_windows_drive_path(r"C:\tmp\registry.toml"));
188        assert!(looks_like_windows_drive_path("D:/tmp/registry.toml"));
189        assert!(looks_like_windows_drive_path("E:relative"));
190        assert!(!looks_like_windows_drive_path(
191            "https://example.com/index.toml"
192        ));
193        assert!(!looks_like_windows_drive_path("/tmp/index.toml"));
194    }
195
196    #[test]
197    fn unix_ms_rounds_to_seconds() {
198        assert_eq!(format_unix_ms_rfc3339(0), "1970-01-01T00:00:00Z");
199        assert_eq!(format_unix_ms_rfc3339(1500), "1970-01-01T00:00:01Z");
200        // Negative ms before the epoch should not panic.
201        assert_eq!(format_unix_ms_rfc3339(-1), "1969-12-31T23:59:59Z");
202    }
203
204    #[test]
205    fn coarse_duration_picks_a_unit() {
206        assert_eq!(format_duration_coarse(StdDuration::from_millis(0)), "0ms");
207        assert_eq!(format_duration_coarse(StdDuration::from_secs(5)), "5s");
208        assert_eq!(format_duration_coarse(StdDuration::from_mins(2)), "2m");
209        assert_eq!(format_duration_coarse(StdDuration::from_hours(2)), "2h");
210        assert_eq!(format_duration_coarse(StdDuration::from_hours(72)), "3d");
211        assert_eq!(format_duration_coarse(StdDuration::from_hours(336)), "2w");
212    }
213
214    #[test]
215    fn ms_duration_uses_one_decimal_above_a_second() {
216        assert_eq!(format_duration_ms(500), "500ms");
217        assert_eq!(format_duration_ms(1_500), "1.5s");
218        assert_eq!(format_duration_ms(90_000), "1.5m");
219    }
220
221    #[test]
222    fn escape_md_escapes_only_pipes() {
223        assert_eq!(escape_md("a|b|c"), "a\\|b\\|c");
224        assert_eq!(escape_md("no pipes here"), "no pipes here");
225        assert_eq!(escape_md(""), "");
226    }
227}