OXYGENHUB
# 8e80c64d55eb oxygen / src / cli / format.rs
4.1 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 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.
70
pub fn signature_mark(repo: &Repo, h: &ChangeHash) -> Result<String> {
71
    Ok(match repo.authenticate_change(h)? {
72
        SignatureStatus::Unsigned => ui::dim(format!("{} unsigned", ui::glyph("·", "-"))),
73
        SignatureStatus::Valid {
74
            sealed,
75
            revoked: true,
76
            ..
77
        } => ui::warn(format!(
78
            "{} {} (key revoked)",
79
            ui::glyph("⚠", "!"),
80
            if sealed { "sealed" } else { "signed" }
81
        )),
82
        SignatureStatus::Valid { sealed, .. } => ui::ok(format!(
83
            "{} {}",
84
            ui::glyph("✔", "v"),
85
            if sealed { "sealed" } else { "signed" }
86
        )),
87
        SignatureStatus::Invalid(why) => ui::err(format!("{} INVALID: {why}", ui::glyph("✖", "x"))),
88
    })
89
}
90
91
/// The author's display name: the identity's name, or a Git-Author trailer
92
/// for imported changes, or a shortened key.
93
pub fn author_name(repo: &Repo, c: &ChangeMeta) -> String {
94
    if !c.author.is_zero() {
95
        if let Ok(id) = repo.identity(&c.author) {
96
            return id.name;
97
        }
98
        return c.author.short(12);
99
    }
100
    c.message
101
        .lines()
102
        .rev()
103
        .find_map(|l| l.strip_prefix("Git-Author: "))
104
        .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
105
        .unwrap_or_else(|| "unknown".into())
106
}
107
108
/// The first line of a message, or a placeholder.
109
pub fn subject_of(message: &str) -> &str {
110
    match message.lines().next() {
111
        Some(l) if !l.trim().is_empty() => l,
112
        _ => "(no description)",
113
    }
114
}
115
116
pub fn deps_line(c: &Change) -> String {
117
    deps_of(&c.deps)
118
}
119
120
pub fn deps_of(deps: &[oxy_core::hash::ChangeHash]) -> String {
121
    deps.iter()
122
        .map(|d| format!("#{}", d.short(12)))
123
        .collect::<Vec<_>>()
124
        .join(" ")
125
}
126
127
#[cfg(test)]
128
mod tests {
129
    use super::*;
130
131
    #[test]
132
    fn dates() {
133
        assert_eq!(when(0), "1970-01-01 00:00:00Z");
134
        assert_eq!(when(1_700_000_000_000), "2023-11-14 22:13:20Z");
135
        assert_eq!(plural(1, "head"), "1 head");
136
        assert_eq!(plural(2, "head"), "2 heads");
137
    }
138
}