OXYGENHUB

Coverage / src/cli/format.rs 67.9%

95 of 140 lines run, 18 of 41 functions · run #427 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`.
1597×
pub fn plural(n: usize, word: &str) -> String {
1697×
    format!("{n} {word}{}", if n == 1 { "" } else { "s" })
1797×
}
18
19
/// Milliseconds since the Unix epoch as `YYYY-MM-DD HH:MM:SSZ`.
208×
pub fn when(ms: u64) -> String {
218×
    let secs = (ms / 1000) as i64;
228×
    let days = secs.div_euclid(86_400);
238×
    let rem = secs.rem_euclid(86_400);
24
    // Civil-from-days (Howard Hinnant), UTC.
258×
    let z = days + 719_468;
268×
    let era = z.div_euclid(146_097);
278×
    let doe = z - era * 146_097;
288×
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
298×
    let y = yoe + era * 400;
308×
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
318×
    let mp = (5 * doy + 2) / 153;
328×
    let d = doy - (153 * mp + 2) / 5 + 1;
338×
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
348×
    let y = if m <= 2 { y + 1 } else { y };
358×
    format!(
36
        "{y:04}-{m:02}-{d:02} {:02}:{:02}:{:02}Z",
378×
        rem / 3600,
388×
        (rem % 3600) / 60,
398×
        rem % 60
40
    )
418×
}
42
43
/// One line describing how a change is authenticated.
442×
pub fn signature_line(repo: &Repo, h: &ChangeHash) -> Result<String> {
452×
    let status = repo.authenticate_change(h)?;
462×
    let awaiting = repo
472×
        .store()
482×
        .get_change(h)
492×
        .is_ok_and(|c| awaits_seal(repo, &status, &c.author));
501×
    Ok(match status {
510×
        SignatureStatus::Unsigned if awaiting => {
520×
            "awaiting seal (the next push seals it under the agent's grant)".to_string()
53
        }
541×
        SignatureStatus::Unsigned => "unsigned".to_string(),
55
        SignatureStatus::Valid {
561×
            key,
571×
            name,
581×
            email,
591×
            sealed,
601×
            revoked,
61
        } => {
621×
            format!(
63
                "{} by {name} <{email}> key {}{}",
641×
                if sealed { "sealed" } else { "signed" },
651×
                key.short(12),
661×
                if revoked { " (KEY REVOKED)" } else { "" }
67
            )
68
        }
690×
        SignatureStatus::Invalid(why) => format!("INVALID signature: {why}"),
70
    })
712×
}
72
73
/// Who signed for the author when it was not the author: a delegate such
74
/// as an agent (`author.signer`), with the delegation that let it.
75
#[derive(Clone, Debug)]
76
pub struct Via {
77
    pub name: String,
78
    pub email: String,
79
    pub key: KeyId,
80
    /// The delegation as the author's identity lists it, if it still does.
81
    pub scope: Option<String>,
82
    pub expires: Option<u64>,
83
    pub revoked: bool,
84
}
85
86
impl Via {
87
    /// `↳ Antigravity <[email protected]> · delegate for changes, until … · key 3195…`
880×
    pub fn line(&self) -> String {
890×
        let delegation = match (&self.scope, self.revoked) {
900×
            (_, true) => ui::err("delegation revoked"),
910×
            (Some(scope), false) => ui::dim(format!(
92
                "delegate for {scope}{}",
930×
                self.expires
940×
                    .map(|e| format!(", until {}", when(e)))
950×
                    .unwrap_or_default()
96
            )),
970×
            (None, false) => ui::warn("not a delegate of the author now"),
98
        };
990×
        format!(
100
            "{} {} <{}> · {} · key {}",
1010×
            ui::glyph("↳", "->"),
1020×
            ui::author(&self.name),
103
            self.email,
104
            delegation,
1050×
            ui::hash(self.key.short(12))
106
        )
1070×
    }
108
}
109
110
/// The delegate that signed for `author`, when one did. `None` when the
111
/// author signed, or nothing valid did.
11227×
pub fn via(repo: &Repo, status: &SignatureStatus, author: &KeyId) -> Option<Via> {
1138×
    match status {
114
        SignatureStatus::Valid {
1158×
            key,
1168×
            name,
1178×
            email,
1188×
            revoked,
119
            ..
1208×
        } if !author.is_zero() && key != author => {
1210×
            let entry = repo
1220×
                .identity(author)
1230×
                .ok()
1240×
                .and_then(|a| a.delegate(key).copied());
125
            // A short-lived key acting under the author's grant (§14.7)
126
            // is no delegate, and not a revoked one either.
1270×
            let certified = entry.is_none() && repo.certified_subject(key).is_some();
128
            Some(Via {
1290×
                name: name.clone(),
1300×
                email: email.clone(),
1310×
                key: *key,
1320×
                scope: entry.map(|d| d.scope.to_string()),
1330×
                expires: entry.and_then(|d| d.expires),
1340×
                revoked: *revoked || (entry.is_none() && !certified),
135
            })
136
        }
13727×
        _ => None,
138
    }
13927×
}
140
141
/// Whether an unsigned change is one the next push will seal: this
142
/// checkout signs keyless (an agent under a grant) and the change is its
143
/// configured author's (oxygen#165). Read cold, "unsigned" looks like an
144
/// error; it is not one until the push.
1455×
pub fn awaits_seal(repo: &Repo, status: &SignatureStatus, author: &oxy_core::hash::KeyId) -> bool {
1465×
    matches!(status, SignatureStatus::Unsigned)
1474×
        && repo.config.signer_keyless
1480×
        && repo.config.author_key == Some(*author)
1495×
}
150
151
/// A compact, styled authentication marker for log lines, from a status
152
/// already in hand (the caller also reads who signed, see [`via`]);
153
/// `awaiting` from [`awaits_seal`].
1543×
pub fn signature_mark_of(status: &SignatureStatus, awaiting: bool) -> String {
1553×
    match status {
1560×
        SignatureStatus::Unsigned if awaiting => {
1570×
            ui::dim(format!("{} awaiting seal", ui::glyph("◌", "o")))
158
        }
1593×
        SignatureStatus::Unsigned => ui::dim(format!("{} unsigned", ui::glyph("·", "-"))),
160
        SignatureStatus::Valid {
1610×
            sealed,
162
            revoked: true,
163
            ..
1640×
        } => ui::warn(format!(
165
            "{} {} (key revoked)",
1660×
            ui::glyph("⚠", "!"),
1670×
            if *sealed { "sealed" } else { "signed" }
168
        )),
1690×
        SignatureStatus::Valid { sealed, .. } => ui::ok(format!(
170
            "{} {}",
1710×
            ui::glyph("✔", "v"),
1720×
            if *sealed { "sealed" } else { "signed" }
173
        )),
1740×
        SignatureStatus::Invalid(why) => ui::err(format!("{} INVALID: {why}", ui::glyph("✖", "x"))),
175
    }
1763×
}
177
178
/// The author's display name: the identity's name, or a Git-Author trailer
179
/// for imported changes, or a shortened key.
18028×
pub fn author_name(repo: &Repo, c: &ChangeMeta) -> String {
18128×
    if !c.author.is_zero() {
18211×
        if let Ok(id) = repo.identity(&c.author) {
18311×
            return id.name;
1840×
        }
1850×
        return c.author.short(12);
18617×
    }
18717×
    c.message
18817×
        .lines()
18917×
        .rev()
19019×
        .find_map(|l| l.strip_prefix("Git-Author: "))
19117×
        .map(|a| a.split('<').next().unwrap_or(a).trim().to_string())
19217×
        .unwrap_or_else(|| "unknown".into())
19328×
}
194
195
/// The first line of a message, or a placeholder.
19682×
pub fn subject_of(message: &str) -> &str {
19782×
    match message.lines().next() {
19882×
        Some(l) if !l.trim().is_empty() => l,
1990×
        _ => "(no description)",
200
    }
20182×
}
202
2032×
pub fn deps_line(c: &Change) -> String {
2042×
    deps_of(&c.deps)
2052×
}
206
2072×
pub fn deps_of(deps: &[oxy_core::hash::ChangeHash]) -> String {
2082×
    deps.iter()
2092×
        .map(|d| format!("#{}", d.short(12)))
2102×
        .collect::<Vec<_>>()
2112×
        .join(" ")
2122×
}
213
214
#[cfg(test)]
215
mod tests {
216
    use super::*;
217
218
    #[test]
2191×
    fn dates() {
2201×
        assert_eq!(when(0), "1970-01-01 00:00:00Z");
2211×
        assert_eq!(when(1_700_000_000_000), "2023-11-14 22:13:20Z");
2221×
        assert_eq!(plural(1, "head"), "1 head");
2231×
        assert_eq!(plural(2, "head"), "2 heads");
2241×
    }
225
}