OXYGENHUB

Coverage / src/cli/format.rs 68.0%

85 of 125 lines run, 16 of 37 functions · run #366 on main · run missed

1
//! Shared presentation helpers.
2
3
use super::ui;
4
use anyhow::Result;
5
use oxy_core::hash::{ChangeHash, KeyId};
6
use oxy_core::objects::Change;
7
use oxy_core::repo::{Repo, SignatureStatus};
8
use oxy_core::state::ChangeMeta;
9
102×
pub fn short_id(c: &Change) -> String {
112×
    c.change_id.short(8)
122×
}
13
14
/// `n head` / `n heads`.
1576×
pub fn plural(n: usize, word: &str) -> String {
1676×
    format!("{n} {word}{}", if n == 1 { "" } else { "s" })
1776×
}
18
19
/// Milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SSZ`.
207×
pub fn when(ms: u64) -> String {
217×
    let secs = (ms / 1000) as i64;
227×
    let days = secs.div_euclid(86_400);
237×
    let rem = secs.rem_euclid(86_400);
24
    // Civil-from-days (Howard Hinnant), UTC.
257×
    let z = days + 719_468;
267×
    let era = z.div_euclid(146_097);
277×
    let doe = z - era * 146_097;
287×
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
297×
    let y = yoe + era * 400;
307×
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
317×
    let mp = (5 * doy + 2) / 153;
327×
    let d = doy - (153 * mp + 2) / 5 + 1;
337×
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
347×
    let y = if m <= 2 { y + 1 } else { y };
357×
    format!(
36
        "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z",
377×
        rem / 3600,
387×
        (rem % 3600) / 60,
397×
        rem % 60
40
    )
417×
}
42
43
/// One line describing how a change is authenticated.
442×
pub fn signature_line(repo: &Repo, h: &ChangeHash) -> Result<String> {
452×
    Ok(match repo.authenticate_change(h)? {
461×
        SignatureStatus::Unsigned => "unsigned".to_string(),
47
        SignatureStatus::Valid {
481×
            key,
491×
            name,
501×
            email,
511×
            sealed,
521×
            revoked,
53
        } => {
541×
            format!(
55
                "{} by {name} <{email}> key {}{}",
561×
                if sealed { "sealed" } else { "signed" },
571×
                key.short(12),
581×
                if revoked { " (KEY REVOKED)" } else { "" }
59
            )
60
        }
610×
        SignatureStatus::Invalid(why) => format!("INVALID signature: {why}"),
62
    })
632×
}
64
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…`
800×
    pub fn line(&self) -> String {
810×
        let delegation = match (&self.scope, self.revoked) {
820×
            (_, true) => ui::err("delegation revoked"),
830×
            (Some(scope), false) => ui::dim(format!(
84
                "delegate for {scope}{}",
850×
                self.expires
860×
                    .map(|e| format!(", until {}", when(e)))
870×
                    .unwrap_or_default()
88
            )),
890×
            (None, false) => ui::warn("not a delegate of the author now"),
90
        };
910×
        format!(
92
            "{} {} <{}> · {} · key {}",
930×
            ui::glyph("↳", "->"),
940×
            ui::author(&self.name),
95
            self.email,
96
            delegation,
970×
            ui::hash(self.key.short(12))
98
        )
990×
    }
100
}
101
102
/// The delegate that signed for `author`, when one did. `None` when the
103
/// author signed, or nothing valid did.
10423×
pub fn via(repo: &Repo, status: &SignatureStatus, author: &KeyId) -> Option<Via> {
1056×
    match status {
106
        SignatureStatus::Valid {
1076×
            key,
1086×
            name,
1096×
            email,
1106×
            revoked,
111
            ..
1126×
        } if !author.is_zero() && key != author => {
1130×
            let entry = repo
1140×
                .identity(author)
1150×
                .ok()
1160×
                .and_then(|a| a.delegate(key).copied());
117
            // A short-lived key acting under the author's grant (§14.7)
118
            // is no delegate, and not a revoked one either.
1190×
            let certified = entry.is_none() && repo.certified_subject(key).is_some();
120
            Some(Via {
1210×
                name: name.clone(),
1220×
                email: email.clone(),
1230×
                key: *key,
1240×
                scope: entry.map(|d| d.scope.to_string()),
1250×
                expires: entry.and_then(|d| d.expires),
1260×
                revoked: *revoked || (entry.is_none() && !certified),
127
            })
128
        }
12923×
        _ => None,
130
    }
13123×
}
132
133
/// A compact, styled authentication marker for log lines, from a status
134
/// already in hand (the caller also reads who signed, see [`via`]).
1353×
pub fn signature_mark_of(status: &SignatureStatus) -> String {
1363×
    match status {
1373×
        SignatureStatus::Unsigned => ui::dim(format!("{} unsigned", ui::glyph("·", "-"))),
138
        SignatureStatus::Valid {
1390×
            sealed,
140
            revoked: true,
141
            ..
1420×
        } => ui::warn(format!(
143
            "{} {} (key revoked)",
1440×
            ui::glyph("⚠", "!"),
1450×
            if *sealed { "sealed" } else { "signed" }
146
        )),
1470×
        SignatureStatus::Valid { sealed, .. } => ui::ok(format!(
148
            "{} {}",
1490×
            ui::glyph("✔", "v"),
1500×
            if *sealed { "sealed" } else { "signed" }
151
        )),
1520×
        SignatureStatus::Invalid(why) => ui::err(format!("{} INVALID: {why}", ui::glyph("✖", "x"))),
153
    }
1543×
}
155
156
/// The author's display name: the identity's name, or a Git-Author trailer
157
/// for imported changes, or a shortened key.
15824×
pub fn author_name(repo: &Repo, c: &ChangeMeta) -> String {
15924×
    if !c.author.is_zero() {
1607×
        if let Ok(id) = repo.identity(&c.author) {
1617×
            return id.name;
1620×
        }
1630×
        return c.author.short(12);
16417×
    }
16517×
    c.message
16617×
        .lines()
16717×
        .rev()
16819×
        .find_map(|l| l.strip_prefix("Git-Author: "))
16917×
        .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
17017×
        .unwrap_or_else(|| "unknown".into())
17124×
}
172
173
/// The first line of a message, or a placeholder.
17462×
pub fn subject_of(message: &str) -> &str {
17562×
    match message.lines().next() {
17662×
        Some(l) if !l.trim().is_empty() => l,
1770×
        _ => "(no description)",
178
    }
17962×
}
180
1812×
pub fn deps_line(c: &Change) -> String {
1822×
    deps_of(&c.deps)
1832×
}
184
1852×
pub fn deps_of(deps: &[oxy_core::hash::ChangeHash]) -> String {
1862×
    deps.iter()
1872×
        .map(|d| format!("#{}", d.short(12)))
1882×
        .collect::<Vec<_>>()
1892×
        .join(" ")
1902×
}
191
192
#[cfg(test)]
193
mod tests {
194
    use super::*;
195
196
    #[test]
1971×
    fn dates() {
1981×
        assert_eq!(when(0), "1970-01-01 00:00:00Z");
1991×
        assert_eq!(when(1_700_000_000_000), "2023-11-14 22:13:20Z");
2001×
        assert_eq!(plural(1, "head"), "1 head");
2011×
        assert_eq!(plural(2, "head"), "2 heads");
2021×
    }
203
}