OXYGENHUB
# 2bf22305bc48 oxygen / src / cli / format.rs
4.1 KiB · Rust · last changed oxy log draws a graph: lanes, bookmarks inline, unique ID prefixes (closes #50) 1 month ago source blame history raw
1
//! Shared presentation helpers.
2
3
use super::ui;
4
use anyhow::Result;
5
use oxy_core::hash::ChangeHash;
6
use oxy_core::objects::Change;
7
use oxy_core::repo::{Repo, SignatureStatus};
8
use oxy_core::state::ChangeMeta;
9
10
pub fn short_id(c: &Change) -> String {
11
    c.change_id.short(8)
12
}
13
14
/// `n head` / `n heads`.
15
pub fn plural(n: usize, word: &str) -> String {
16
    format!("{n} {word}{}", if n == 1 { "" } else { "s" })
17
}
18
19
/// Milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SSZ`.
20
pub fn when(ms: u64) -> String {
21
    let secs = (ms / 1000) as i64;
22
    let days = secs.div_euclid(86_400);
23
    let rem = secs.rem_euclid(86_400);
24
    // Civil-from-days (Howard Hinnant), UTC.
25
    let z = days + 719_468;
26
    let era = z.div_euclid(146_097);
27
    let doe = z - era * 146_097;
28
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
29
    let y = yoe + era * 400;
30
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
31
    let mp = (5 * doy + 2) / 153;
32
    let d = doy - (153 * mp + 2) / 5 + 1;
33
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
34
    let y = if m <= 2 { y + 1 } else { y };
35
    format!(
36
        "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z",
37
        rem / 3600,
38
        (rem % 3600) / 60,
39
        rem % 60
40
    )
41
}
42
43
/// One line describing how a change is authenticated.
44
pub fn signature_line(repo: &Repo, h: &ChangeHash) -> Result<String> {
45
    Ok(match repo.authenticate_change(h)? {
46
        SignatureStatus::Unsigned => "unsigned".to_string(),
47
        SignatureStatus::Valid {
48
            key,
49
            name,
50
            email,
51
            sealed,
52
            revoked,
53
        } => {
54
            format!(
55
                "{} by {name} <{email}> key {}{}",
56
                if sealed { "sealed" } else { "signed" },
57
                key.short(12),
58
                if revoked { " (KEY REVOKED)" } else { "" }
59
            )
60
        }
61
        SignatureStatus::Invalid(why) => format!("INVALID signature: {why}"),
62
    })
63
}
64
65
/// A compact, styled authentication marker for log lines, from the
66
/// change's metadata when the caller has it (so the change itself need not
67
/// be read).
68
pub fn signature_mark(repo: &Repo, h: &ChangeHash, known: Option<&ChangeMeta>) -> Result<String> {
69
    Ok(match repo.authenticate_change_known(h, known)? {
70
        SignatureStatus::Unsigned => ui::dim(format!("{} unsigned", ui::glyph("·", "-"))),
71
        SignatureStatus::Valid {
72
            sealed,
73
            revoked: true,
74
            ..
75
        } => ui::warn(format!(
76
            "{} {} (key revoked)",
77
            ui::glyph("⚠", "!"),
78
            if sealed { "sealed" } else { "signed" }
79
        )),
80
        SignatureStatus::Valid { sealed, .. } => ui::ok(format!(
81
            "{} {}",
82
            ui::glyph("✔", "v"),
83
            if sealed { "sealed" } else { "signed" }
84
        )),
85
        SignatureStatus::Invalid(why) => ui::err(format!("{} INVALID: {why}", ui::glyph("✖", "x"))),
86
    })
87
}
88
89
/// The author's display name: the identity's name, or a Git-Author trailer
90
/// for imported changes, or a shortened key.
91
pub fn author_name(repo: &Repo, c: &ChangeMeta) -> String {
92
    if !c.author.is_zero() {
93
        if let Ok(id) = repo.identity(&c.author) {
94
            return id.name;
95
        }
96
        return c.author.short(12);
97
    }
98
    c.message
99
        .lines()
100
        .rev()
101
        .find_map(|l| l.strip_prefix("Git-Author: "))
102
        .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
103
        .unwrap_or_else(|| "unknown".into())
104
}
105
106
/// The first line of a message, or a placeholder.
107
pub fn subject_of(message: &str) -> &str {
108
    match message.lines().next() {
109
        Some(l) if !l.trim().is_empty() => l,
110
        _ => "(no description)",
111
    }
112
}
113
114
pub fn deps_line(c: &Change) -> String {
115
    deps_of(&c.deps)
116
}
117
118
pub fn deps_of(deps: &[oxy_core::hash::ChangeHash]) -> String {
119
    deps.iter()
120
        .map(|d| format!("#{}", d.short(12)))
121
        .collect::<Vec<_>>()
122
        .join(" ")
123
}
124
125
#[cfg(test)]
126
mod tests {
127
    use super::*;
128
129
    #[test]
130
    fn dates() {
131
        assert_eq!(when(0), "1970-01-01 00:00:00Z");
132
        assert_eq!(when(1_700_000_000_000), "2023-11-14 22:13:20Z");
133
        assert_eq!(plural(1, "head"), "1 head");
134
        assert_eq!(plural(2, "head"), "2 heads");
135
    }
136
}