Skip to main content

code_ranker_plugin_api/
log.rs

1//! Shared stderr progress/timing log.
2//!
3//! This lives in the foundation crate so every component — CLI stages and the
4//! sub-commands plugins shell out to (`git`, `cargo metadata`, `rustc`) — emits
5//! one consistent line format. All output goes to **stderr** (machine output and
6//! artifacts go to stdout/files), prefixed with a local `HH:MM:SS.mmm` stamp.
7//! Durations are printed to **millisecond precision** (`0.231s`).
8
9use chrono::Local;
10use std::time::{Duration, Instant};
11
12/// Local wall-clock stamp, `HH:MM:SS.mmm`.
13pub fn stamp() -> String {
14    Local::now().format("%H:%M:%S%.3f").to_string()
15}
16
17/// Format a duration as seconds with millisecond precision, e.g. `0.231s`,
18/// `29.900s`. The single authority for how timings render across the tool.
19pub fn secs(dur: Duration) -> String {
20    format!("{:.3}s", dur.as_secs_f64())
21}
22
23/// Emit one stamped line to stderr: `[HH:MM:SS.mmm] <msg>`.
24pub fn line(msg: &str) {
25    eprintln!("[{}] {}", stamp(), msg);
26}
27
28/// Log a completed internal sub-command (an external tool code-ranker shelled out
29/// to) with its duration: `[HH:MM:SS.mmm] ↳ <label> — 0.231s`. The `↳` marks it
30/// as a nested step under the current stage.
31pub fn subcmd(label: &str, dur: Duration) {
32    line(&format!("↳ {label} — {}", secs(dur)));
33}
34
35/// Time `f`, log it as a sub-command (see [`subcmd`]), and return its value.
36/// Wrap every `git` / `cargo` / `rustc` invocation in this so the cost of each
37/// external call is visible — these dominate the wall clock on a cold cache.
38pub fn timed<T>(label: &str, f: impl FnOnce() -> T) -> T {
39    let start = Instant::now();
40    let out = f();
41    subcmd(label, start.elapsed());
42    out
43}