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