OXYGENHUB
# 7505194116e7 oxygen / src / cli / format.rs
6.1 KiB · Rust · last changed Who did the work: via AGENT in log and show, delegates by name 1 month ago source blame history raw
fce44ae9 Andy McCall ↶ 1
//! Shared presentation helpers.
2
94084087 Andy McCall ↶ 3
use super::ui;
fce44ae9 Andy McCall ↶ 4
use anyhow::Result;
5cde7882 Andy McCall ↶ 5
use oxy_core::hash::{ChangeHash, KeyId};
fce44ae9 Andy McCall ↶ 6
use oxy_core::objects::Change;
7
use oxy_core::repo::{Repo, SignatureStatus};
2863456a Andy McCall ↶ 8
use oxy_core::state::ChangeMeta;
fce44ae9 Andy McCall ↶ 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 };
75167672 Andy McCall 35
    format!(
36
        "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z",
37
        rem / 3600,
38
        (rem % 3600) / 60,
39
        rem % 60
40
    )
fce44ae9 Andy McCall ↶ 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(),
75167672 Andy McCall 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
            )
fce44ae9 Andy McCall ↶ 60
        }
61
        SignatureStatus::Invalid(why) => format!("INVALID signature: {why}"),
62
    })
63
}
64
5cde7882 Andy McCall ↶ 65
/// Who signed for the author when it was not the author: a delegate such
66
/// as an agent (`author.signer`), with the delegation that let it.
67
#[derive(Clone, Debug)]
68
pub struct Via {
69
    pub name: String,
70
    pub email: String,
71
    pub key: KeyId,
72
    /// The delegation as the author's identity lists it, if it still does.
73
    pub scope: Option<String>,
74
    pub expires: Option<u64>,
75
    pub revoked: bool,
76
}
77
78
impl Via {
79
    /// `↳ Antigravity <[email protected]> · delegate for changes, until … · key 3195…`
80
    pub fn line(&self) -> String {
81
        let delegation = match (&self.scope, self.revoked) {
82
            (_, true) => ui::err("delegation revoked"),
83
            (Some(scope), false) => ui::dim(format!(
84
                "delegate for {scope}{}",
85
                self.expires
86
                    .map(|e| format!(", until {}", when(e)))
87
                    .unwrap_or_default()
88
            )),
89
            (None, false) => ui::warn("not a delegate of the author now"),
90
        };
91
        format!(
92
            "{} {} <{}> · {} · key {}",
93
            ui::glyph("↳", "->"),
94
            ui::author(&self.name),
95
            self.email,
96
            delegation,
97
            ui::hash(self.key.short(12))
98
        )
99
    }
100
}
101
102
/// The delegate that signed for `author`, when one did. `None` when the
103
/// author signed, or nothing valid did.
104
pub fn via(repo: &Repo, status: &SignatureStatus, author: &KeyId) -> Option<Via> {
105
    match status {
106
        SignatureStatus::Valid {
107
            key,
108
            name,
109
            email,
110
            revoked,
111
            ..
112
        } if !author.is_zero() && key != author => {
113
            let entry = repo
114
                .identity(author)
115
                .ok()
116
                .and_then(|a| a.delegate(key).copied());
117
            Some(Via {
118
                name: name.clone(),
119
                email: email.clone(),
120
                key: *key,
121
                scope: entry.map(|d| d.scope.to_string()),
122
                expires: entry.and_then(|d| d.expires),
123
                revoked: *revoked || entry.is_none(),
124
            })
125
        }
126
        _ => None,
127
    }
128
}
129
130
/// A compact, styled authentication marker for log lines, from a status
131
/// already in hand (the caller also reads who signed, see [`via`]).
132
pub fn signature_mark_of(status: &SignatureStatus) -> String {
133
    match status {
94084087 Andy McCall ↶ 134
        SignatureStatus::Unsigned => ui::dim(format!("{} unsigned", ui::glyph("·", "-"))),
75167672 Andy McCall 135
        SignatureStatus::Valid {
136
            sealed,
137
            revoked: true,
138
            ..
139
        } => ui::warn(format!(
140
            "{} {} (key revoked)",
141
            ui::glyph("⚠", "!"),
5cde7882 Andy McCall ↶ 142
            if *sealed { "sealed" } else { "signed" }
75167672 Andy McCall 143
        )),
144
        SignatureStatus::Valid { sealed, .. } => ui::ok(format!(
145
            "{} {}",
146
            ui::glyph("✔", "v"),
5cde7882 Andy McCall ↶ 147
            if *sealed { "sealed" } else { "signed" }
75167672 Andy McCall 148
        )),
94084087 Andy McCall ↶ 149
        SignatureStatus::Invalid(why) => ui::err(format!("{} INVALID: {why}", ui::glyph("✖", "x"))),
5cde7882 Andy McCall ↶ 150
    }
94084087 Andy McCall ↶ 151
}
152
153
/// The author's display name: the identity's name, or a Git-Author trailer
154
/// for imported changes, or a shortened key.
155
pub fn author_name(repo: &Repo, c: &ChangeMeta) -> String {
156
    if !c.author.is_zero() {
157
        if let Ok(id) = repo.identity(&c.author) {
158
            return id.name;
159
        }
160
        return c.author.short(12);
161
    }
162
    c.message
163
        .lines()
164
        .rev()
165
        .find_map(|l| l.strip_prefix("Git-Author: "))
166
        .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
167
        .unwrap_or_else(|| "unknown".into())
168
}
169
170
/// The first line of a message, or a placeholder.
171
pub fn subject_of(message: &str) -> &str {
172
    match message.lines().next() {
173
        Some(l) if !l.trim().is_empty() => l,
174
        _ => "(no description)",
175
    }
176
}
177
fce44ae9 Andy McCall ↶ 178
pub fn deps_line(c: &Change) -> String {
2863456a Andy McCall ↶ 179
    deps_of(&c.deps)
180
}
181
182
pub fn deps_of(deps: &[oxy_core::hash::ChangeHash]) -> String {
75167672 Andy McCall 183
    deps.iter()
184
        .map(|d| format!("#{}", d.short(12)))
185
        .collect::<Vec<_>>()
186
        .join(" ")
fce44ae9 Andy McCall ↶ 187
}
188
189
#[cfg(test)]
190
mod tests {
191
    use super::*;
192
193
    #[test]
194
    fn dates() {
195
        assert_eq!(when(0), "1970-01-01 00:00:00Z");
196
        assert_eq!(when(1_700_000_000_000), "2023-11-14 22:13:20Z");
197
        assert_eq!(plural(1, "head"), "1 head");
198
        assert_eq!(plural(2, "head"), "2 heads");
199
    }
200
}