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