OXYGENHUB

Coverage / crates/hub/src/repos/view.rs 92.1%

963 of 1046 lines run, 169 of 341 functions · run #498 on main · run missed

1
//! Page-ready views of a repository, computed from `oxy-core` alone (hub
2
//! spec §1.4). Nothing here knows about HTTP or templates; every function
3
//! takes an open `Repo` and returns plain data.
4
5
use super::{RepoError, StateCache};
6
use oxy_core::hash::{ChangeHash, KeyId};
7
use oxy_core::objects::{Change, NodeKind};
8
use oxy_core::repo::{BlameLine, FileDiff, Repo, SignatureStatus};
9
use oxy_core::state::{FileContent, Snapshot};
10
use oxy_core::tree::TreeConflict;
11
use std::collections::{BTreeMap, BTreeSet, HashMap};
12
13
type Result<T> = std::result::Result<T, RepoError>;
14
150×
fn fail(msg: impl Into<String>) -> RepoError {
160×
    RepoError::Oxy(oxy_core::repo::RepoError::Msg(msg.into()))
170×
}
18
19
// ------------------------------------------------------------------ refs
20
21
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22
pub enum RefKind {
23
    Bookmark,
24
    Tag,
25
    Change,
26
}
27
28
/// What a `{ref}` path segment resolved to.
29
#[derive(Clone, Debug)]
30
pub struct RefTarget {
31
    /// The name as given (bookmark, tag) or the full hash.
32
    pub label: String,
33
    pub kind: RefKind,
34
    pub heads: Vec<ChangeHash>,
35
}
36
37
/// Most heads a state address or a "before this change" link carries.
38
pub const MAX_STATE_HEADS: usize = 32;
39
40
impl RefTarget {
41
    /// The label for a ref bar: the name, or `# abc123…` for a change,
42
    /// with `+N` for the further heads of a state.
4343×
    pub fn short_label(&self) -> String {
4443×
        match self.kind {
45
            RefKind::Change => {
465×
                let mut parts = self.label.split('+');
475×
                let first: String = parts.next().unwrap_or("").chars().take(12).collect();
485×
                match parts.count() {
492×
                    0 => first,
503×
                    n => format!("{first} +{n}"),
51
                }
52
            }
5338×
            _ => self.label.clone(),
54
        }
5543×
    }
56
57
    /// The `{ref}` that names this target's state for good: its heads
58
    /// joined with `+` (hub spec §6.6). None for an empty state.
5917×
    pub fn permalink(&self) -> Option<String> {
6017×
        state_spec(&self.heads)
6117×
    }
62
}
63
64
/// Heads as a state address, sorted so one state has one address.
6532×
pub fn state_spec(heads: &[ChangeHash]) -> Option<String> {
6632×
    if heads.is_empty() || heads.len() > MAX_STATE_HEADS {
676×
        return None;
6826×
    }
6955×
    let mut hex: Vec<String> = heads.iter().map(|h| h.to_hex()).collect();
7026×
    hex.sort();
7126×
    hex.dedup();
7226×
    Some(hex.join("+"))
7332×
}
74
75
/// Resolve a bookmark name, a tag name, a change hash prefix, or a state
76
/// (full hashes joined with `+`).
77207×
pub fn resolve(repo: &Repo, cache: &StateCache, spec: &str) -> Result<RefTarget> {
78207×
    if spec.contains('+') {
793×
        let parts: Vec<&str> = spec.split('+').collect();
803×
        if parts.len() > MAX_STATE_HEADS {
810×
            return Err(fail(format!("a state address has at most {MAX_STATE_HEADS} heads")));
823×
        }
833×
        let mut heads = Vec::with_capacity(parts.len());
8410×
        for p in parts {
8510×
            match ChangeHash::from_hex(p) {
8610×
                Some(h) if p.len() == 64 && repo.store().has(&h) => heads.push(h),
870×
                _ => return Err(fail(format!("{p:?} is not a change of this repository"))),
88
            }
89
        }
903×
        heads.sort();
913×
        heads.dedup();
923×
        let label = state_spec(&heads).unwrap_or_default();
933×
        return Ok(RefTarget { label, kind: RefKind::Change, heads });
94204×
    }
95204×
    let view = repo.view()?;
96204×
    if let Some(heads) = view.bookmarks.get(spec).map(|st| repo.store().get_state(st).map(|s| s.heads)).transpose()? {
97197×
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Bookmark, heads });
987×
    }
997×
    if let Some(heads) = repo.tag_heads(spec)? {
1002×
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Tag, heads });
1015×
    }
1025×
    let hash = resolve_change(repo, cache, spec)?;
1035×
    Ok(RefTarget { label: hash.to_hex(), kind: RefKind::Change, heads: vec![hash] })
104207×
}
105
106
/// A change by full hash or unique hex prefix, searched over every
107
/// bookmark's state.
10821×
pub fn resolve_change(repo: &Repo, cache: &StateCache, spec: &str) -> Result<ChangeHash> {
10921×
    let spec = spec.trim_start_matches('#');
1101234×
    if spec.len() < 4 || !spec.chars().all(|c| c.is_ascii_hexdigit()) {
1110×
        return Err(fail(format!("{spec:?} is not a change")));
11221×
    }
11321×
    if let Some(h) = ChangeHash::from_hex(spec) {
11419×
        if repo.store().has(&h) {
11519×
            return Ok(h);
1160×
        }
1172×
    }
1182×
    let heads = all_heads(repo)?;
1192×
    let loaded = cache.load(repo, &heads)?;
1204×
    let matches: Vec<ChangeHash> = loaded.state.changes().map(|(h, _)| *h).filter(|h| h.starts_with_hex(spec)).collect();
1212×
    match matches.len() {
1222×
        1 => Ok(matches[0]),
1230×
        0 => Err(fail(format!("no change matches {spec:?}"))),
1240×
        _ => Err(fail(format!("{spec:?} is ambiguous"))),
125
    }
12621×
}
127
128
/// The heads of every bookmark, deduplicated.
12923×
pub fn all_heads(repo: &Repo) -> Result<Vec<ChangeHash>> {
13023×
    let mut set = BTreeSet::new();
13143×
    for b in repo.bookmarks()? {
13243×
        set.extend(b.heads);
13343×
    }
13423×
    Ok(set.into_iter().collect())
13523×
}
136
137
// ---------------------------------------------------------------- authors
138
139
#[derive(Clone, Debug, PartialEq, Eq)]
140
pub struct AuthorView {
141
    pub name: String,
142
    pub email: String,
143
    pub key: String,
144
    /// True when the key is not an identity the store knows.
145
    pub unknown: bool,
146
    /// The hub account the key is linked to, filled by the web layer.
147
    pub account: Option<String>,
148
}
149
150450×
pub fn author(repo: &Repo, key: &KeyId, message: &str) -> AuthorView {
151450×
    if key.is_zero() {
152
        // Imported from Git: the trailer carries the author.
153151×
        let line = message.lines().rev().find_map(|l| l.strip_prefix("Git-Author: ")).unwrap_or("unknown");
154137×
        let (name, email) = match line.split_once('<') {
1550×
            Some((n, e)) => (n.trim().to_string(), e.trim_end_matches('>').trim().to_string()),
156137×
            None => (line.trim().to_string(), String::new()),
157
        };
158137×
        return AuthorView { name, email, key: String::new(), unknown: true, account: None };
159313×
    }
160313×
    match repo.store().get_identity(key) {
161312×
        Ok(id) => AuthorView { name: id.name, email: id.email, key: key.to_hex(), unknown: false, account: None },
1621×
        Err(_) => AuthorView { name: key.short(12), email: String::new(), key: key.to_hex(), unknown: true, account: None },
163
    }
164450×
}
165
166
// ---------------------------------------------------------------- changes
167
168
#[derive(Clone, Debug, PartialEq, Eq)]
169
pub enum SigView {
170
    Unsigned,
171
    Valid { key: String, name: String, sealed: bool, revoked: bool },
172
    Invalid(String),
173
}
174
175
impl SigView {
17674×
    pub fn glyph(&self) -> &'static str {
17774×
        match self {
17822×
            SigView::Unsigned => "○",
1790×
            SigView::Valid { revoked: true, .. } => "⊘",
1800×
            SigView::Valid { sealed: true, .. } => "◈",
18152×
            SigView::Valid { .. } => "✔",
1820×
            SigView::Invalid(_) => "✘",
183
        }
18474×
    }
185
18674×
    pub fn class(&self) -> &'static str {
18774×
        match self {
18822×
            SigView::Unsigned => "sig-unsigned",
1890×
            SigView::Valid { revoked: true, .. } => "sig-revoked",
19052×
            SigView::Valid { .. } => "sig-valid",
1910×
            SigView::Invalid(_) => "sig-invalid",
192
        }
19374×
    }
194
19587×
    pub fn title(&self) -> String {
19687×
        match self {
19727×
            SigView::Unsigned => "unsigned".into(),
1980×
            SigView::Valid { name, sealed: true, revoked: false, .. } => format!("sealed by {name}"),
1990×
            SigView::Valid { name, revoked: true, .. } => format!("signed by {name}, key revoked"),
20060×
            SigView::Valid { name, .. } => format!("signed by {name}"),
2010×
            SigView::Invalid(why) => format!("INVALID: {why}"),
202
        }
20387×
    }
204
}
205
206400×
pub fn signature(repo: &Repo, hash: &ChangeHash) -> SigView {
207400×
    match repo.verify_change(hash) {
208182×
        Ok(SignatureStatus::Unsigned) => SigView::Unsigned,
209217×
        Ok(SignatureStatus::Valid { key, name, sealed, revoked, .. }) => SigView::Valid { key: key.to_hex(), name, sealed, revoked },
2100×
        Ok(SignatureStatus::Invalid(why)) => SigView::Invalid(why),
2111×
        Err(e) => SigView::Invalid(e.to_string()),
212
    }
213400×
}
214
215
/// Who signed for the author when it was not the author: a delegate, such
216
/// as an agent, named by its identity, with the delegation that let it
217
/// (Oxygen's agent workflows doc §6).
218
#[derive(Clone, Debug, PartialEq, Eq)]
219
pub struct ViaView {
220
    pub name: String,
221
    pub email: String,
222
    pub key: String,
223
    pub short: String,
224
    /// The delegation's scope as written, `changes` for an agent.
225
    pub scope: String,
226
    pub expires_ms: Option<u64>,
227
    /// The signing key was revoked, or the delegation is no longer in the
228
    /// author's identity: the change deserves a second look.
229
    pub revoked: bool,
230
}
231
232
impl ViaView {
233
    /// The delegation, as the change page's `via` row says it.
2344×
    pub fn delegation(&self) -> String {
2354×
        if self.revoked {
2360×
            return "delegation revoked".into();
2374×
        }
2384×
        match self.expires_ms {
2390×
            Some(e) => format!("delegate for {}, until {}", self.scope, when_utc(e)),
2404×
            None => format!("delegate for {}", self.scope),
241
        }
2424×
    }
243
244
    /// What hovering the badge says.
24529×
    pub fn title(&self) -> String {
24629×
        let until = match self.expires_ms {
2470×
            Some(e) => format!(", until {}", when_utc(e)),
24829×
            None => String::new(),
249
        };
25029×
        if self.revoked {
2510×
            format!("signed by {} as a delegate of the author; that delegation has since been revoked", self.name)
252
        } else {
25329×
            format!("signed by {} as a delegate of the author ({}{until}), key {}", self.name, self.scope, self.short)
254
        }
25529×
    }
256
}
257
258
/// `2026-10-04 20:12Z` for a wall time in milliseconds.
2590×
fn when_utc(ms: u64) -> String {
2600×
    time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000)
2610×
        .ok()
2620×
        .and_then(|t| t.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]Z")).ok())
2630×
        .unwrap_or_else(|| ms.to_string())
2640×
}
265
266
/// The delegate that signed `hash` for the author, when one did.
267393×
pub fn via(repo: &Repo, author: &KeyId, sig: &SigView) -> Option<ViaView> {
268393×
    let SigView::Valid { key, name, revoked, .. } = sig else { return None };
269211×
    if author.is_zero() || *key == author.to_hex() {
270107×
        return None;
271104×
    }
272104×
    let signer = KeyId::from_hex(key)?;
273104×
    let entry = repo.store().get_identity(author).ok().and_then(|a| a.delegate(&signer).copied());
274104×
    let email = repo.store().get_identity(&signer).map(|i| i.email).unwrap_or_default();
275
    Some(ViaView {
276104×
        name: name.clone(),
277104×
        email,
278104×
        key: key.clone(),
279104×
        short: signer.short(12),
280104×
        scope: entry.map(|d| d.scope.to_string()).unwrap_or_else(|| "changes".into()),
281104×
        expires_ms: entry.and_then(|d| d.expires),
282104×
        revoked: *revoked || entry.is_none(),
283
    })
284393×
}
285
286
/// One change as history rows and change pages show it.
287
#[derive(Clone, Debug)]
288
pub struct ChangeView {
289
    pub hash: String,
290
    pub short: String,
291
    pub title: String,
292
    pub body: String,
293
    pub author: AuthorView,
294
    pub when_ms: u64,
295
    pub deps: Vec<String>,
296
    pub head: bool,
297
    pub resolution: bool,
298
    pub signature: SigView,
299
    /// Signed for the author by a delegate (an agent), when it was.
300
    pub via: Option<ViaView>,
301
    /// Bookmarks and tags whose state has this change as a head.
302
    pub labels: Vec<Label>,
303
}
304
305
#[derive(Clone, Debug, PartialEq, Eq)]
306
pub struct Label {
307
    pub name: String,
308
    pub kind: RefKind,
309
}
310
311393×
pub fn split_message(message: &str) -> (String, String) {
312393×
    let mut lines = message.lines();
313393×
    let title = lines.next().unwrap_or("").trim().to_string();
314393×
    let body = lines.collect::<Vec<_>>().join("\n").trim().to_string();
315393×
    (title, body)
316393×
}
317
318
/// Every bookmark and tag head, for labelling rows.
319352×
pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> {
320352×
    let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new();
321929×
    for b in repo.bookmarks()? {
3222258×
        for h in b.heads {
3232258×
            out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark });
3242258×
        }
325
    }
326352×
    for t in repo.tags()? {
32732×
        for h in t.heads {
32832×
            out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag });
32932×
        }
330
    }
331352×
    Ok(out)
332352×
}
333
334225×
pub fn change_view_pub(
335225×
    repo: &Repo,
336225×
    hash: &ChangeHash,
337225×
    meta: &oxy_core::state::ChangeMeta,
338225×
    head: bool,
339225×
    labels: &HashMap<ChangeHash, Vec<Label>>,
340225×
) -> ChangeView {
341225×
    change_view(repo, hash, meta, head, labels)
342225×
}
343
344393×
fn change_view(
345393×
    repo: &Repo,
346393×
    hash: &ChangeHash,
347393×
    meta: &oxy_core::state::ChangeMeta,
348393×
    head: bool,
349393×
    labels: &HashMap<ChangeHash, Vec<Label>>,
350393×
) -> ChangeView {
351393×
    let (title, body) = split_message(&meta.message);
352393×
    let signature = signature(repo, hash);
353393×
    let via = via(repo, &meta.author, &signature);
354
    ChangeView {
355393×
        hash: hash.to_hex(),
356393×
        short: hash.short(12),
357393×
        title,
358393×
        body,
359393×
        author: author(repo, &meta.author, &meta.message),
360393×
        when_ms: meta.hlc.wall_ms,
361393×
        deps: meta.deps.iter().map(|d| d.to_hex()).collect(),
362393×
        head,
363393×
        resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution,
364393×
        signature,
365393×
        via,
366393×
        labels: labels.get(hash).cloned().unwrap_or_default(),
367
    }
368393×
}
369
370
// ---------------------------------------------------------------- history
371
372
#[derive(Clone, Debug)]
373
pub struct History {
374
    pub target: RefTarget,
375
    pub entries: Vec<ChangeView>,
376
    pub total: usize,
377
    pub offset: usize,
378
    pub has_more: bool,
379
    pub path: Option<String>,
380
}
381
382
/// A window of the history of a state, newest first.
38321×
pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> {
38421×
    let loaded = cache.load(repo, &target.heads)?;
38521×
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
38621×
    let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path {
3877×
        Some(p) => {
3887×
            let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) };
3897×
            loaded
3907×
                .state
3917×
                .changes()
39214×
                .filter(|(h, _)| {
393
                    // The skeleton says which nodes a change touches, without its text.
39414×
                    repo.store()
39514×
                        .get_change_lazy(h)
39614×
                        .map(|(c, _)| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node))
39714×
                        .unwrap_or(false)
39814×
                })
3998×
                .map(|(h, m)| (*h, m.clone()))
4007×
                .collect()
401
        }
40252×
        None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(),
403
    };
404114×
    entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0)));
40521×
    let total = entries.len();
40621×
    let labels = head_labels(repo)?;
40721×
    let window: Vec<ChangeView> =
40860×
        entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect();
40921×
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) })
41021×
}
411
412
/// A window of the changes a revset selects (Oxygen's
413
/// docs/revset_query_language.md §3), newest first, under a budget
414
/// stricter than the command line's so a query cannot load the server.
415
/// `target` is the reference the request named, for labels and heads.
4164×
pub fn history_revset(repo: &Repo, cache: &StateCache, target: RefTarget, revset: &str, offset: usize, limit: usize) -> Result<History> {
4174×
    let loaded = cache.load(repo, &target.heads)?;
4184×
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
4194×
    let selected = repo.revset_with_budget(revset, std::time::Duration::from_secs(2))?;
4202×
    let total = selected.hashes.len();
4212×
    let labels = head_labels(repo)?;
4222×
    let window: Vec<ChangeView> = selected
4232×
        .hashes
4242×
        .iter()
4252×
        .skip(offset)
4262×
        .take(limit)
4272×
        .filter_map(|h| selected.metas.get(h).map(|m| change_view(repo, h, m, head_set.contains(h), &labels)))
4282×
        .collect();
4292×
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: None })
4304×
}
431
432
// ----------------------------------------------------------------- change
433
434
#[derive(Clone, Debug)]
435
pub struct ChangeDetail {
436
    pub view: ChangeView,
437
    pub dependents: Vec<ChangeView>,
438
    pub deps: Vec<ChangeView>,
439
    pub files: Vec<FileDiff>,
440
    /// Base content of each modified file, for context lines.
441
    pub bases: BTreeMap<String, Vec<u8>>,
442
    pub in_bookmarks: Vec<String>,
443
    pub in_tags: Vec<String>,
444
    pub atoms: usize,
445
    pub tree_ops: usize,
446
}
447
44817×
pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> {
44917×
    let c: Change = repo.store().get_change(hash)?;
45017×
    let labels = head_labels(repo)?;
45117×
    let heads = all_heads(repo)?;
45217×
    let loaded = cache.load(repo, &heads)?;
45317×
    let state = &loaded.state;
45417×
    let is_head = state.heads().contains(hash);
45517×
    let meta = oxy_core::state::ChangeMeta::of(&c);
45617×
    let view = change_view(repo, hash, &meta, is_head, &labels);
45717×
    let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect();
45817×
    let mut dependents: Vec<ChangeView> = state
45917×
        .changes()
46059×
        .filter(|(_, m)| m.deps.contains(hash))
46117×
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels))
46217×
        .collect();
46317×
    dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
46417×
    let base = cache.load(repo, &c.deps)?;
46517×
    let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot);
46617×
    let base_snapshot = &base.snapshot;
46717×
    let mut bases = BTreeMap::new();
46818×
    for f in &files {
46918×
        let old = f.from.as_deref().unwrap_or(&f.path);
47018×
        if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) {
4719×
            bases.insert(f.path.clone(), bytes.clone());
4729×
        }
473
    }
47417×
    let mut in_bookmarks = Vec::new();
47534×
    for b in repo.bookmarks()? {
47634×
        if cache.summary(repo, &b.heads)?.changes.contains(hash) {
47717×
            in_bookmarks.push(b.name);
47817×
        }
479
    }
48017×
    let mut in_tags = Vec::new();
48117×
    for t in repo.tags()? {
4822×
        if cache.summary(repo, &t.heads)?.changes.contains(hash) {
4832×
            in_tags.push(t.name);
4842×
        }
485
    }
48617×
    Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() })
48717×
}
488
489
// ------------------------------------------------------------------- tree
490
491
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
492
pub enum EntryKind {
493
    Dir,
494
    File,
495
    Symlink,
496
    Subrepo,
497
}
498
499
#[derive(Clone, Debug)]
500
pub struct Entry {
501
    pub name: String,
502
    pub path: String,
503
    pub kind: EntryKind,
504
    pub exec: bool,
505
    pub size: Option<u64>,
506
    pub conflicted: bool,
507
}
508
509
#[derive(Clone, Debug)]
510
pub struct Tree {
511
    pub target: RefTarget,
512
    pub path: String,
513
    pub entries: Vec<Entry>,
514
    /// `(name, path)` from the root down to this directory.
515
    pub crumbs: Vec<(String, String)>,
516
    pub readme: Option<Readme>,
517
}
518
519
#[derive(Clone, Debug)]
520
pub struct Readme {
521
    pub path: String,
522
    pub text: String,
523
}
524
52581×
pub fn crumbs(path: &str) -> Vec<(String, String)> {
52681×
    let mut out = Vec::new();
52781×
    let mut so_far = String::new();
52887×
    for part in path.split('/').filter(|p| !p.is_empty()) {
52935×
        if !so_far.is_empty() {
5306×
            so_far.push('/');
53129×
        }
53235×
        so_far.push_str(part);
53335×
        out.push((part.to_string(), so_far.clone()));
534
    }
53581×
    out
53681×
}
537
53861×
fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry {
53961×
    let kind = match f.kind {
54020×
        NodeKind::Dir => EntryKind::Dir,
54141×
        NodeKind::File => EntryKind::File,
5420×
        NodeKind::Symlink => EntryKind::Symlink,
5430×
        NodeKind::Subrepo => EntryKind::Subrepo,
544
    };
54561×
    let size = match &f.content {
54641×
        FileContent::Text { bytes, .. } => Some(bytes.len() as u64),
54720×
        _ => None,
548
    };
54961×
    Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() }
55061×
}
551
552
/// The entries directly under `dir` (`""` for the root).
5534×
pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> {
5544×
    let loaded = cache.load(repo, &target.heads)?;
5554×
    tree_of(repo, target, &loaded.snapshot, dir)
5564×
}
557
55855×
pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> {
55955×
    let dir = dir.trim_matches('/');
56055×
    if !dir.is_empty() {
5613×
        match snapshot.files.get(dir) {
5622×
            Some(f) if f.kind == NodeKind::Dir => {}
5631×
            _ => return Err(RepoError::NotFound),
564
        }
56552×
    }
56654×
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
56754×
    let mut entries: Vec<Entry> = snapshot
56854×
        .files
56954×
        .iter()
57089×
        .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/'))
57161×
        .map(|(p, f)| entry_of(p, &p[prefix.len()..], f))
57254×
        .collect();
57354×
    entries.sort_by(|a, b| {
57439×
        (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
57539×
    });
57654×
    let readme = entries
57754×
        .iter()
57858×
        .find(|e| {
57958×
            e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown")
58058×
        })
58154×
        .and_then(|e| match &snapshot.files.get(&e.path)?.content {
58213×
            FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }),
5830×
            _ => None,
58413×
        });
58554×
    Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme })
58655×
}
587
588
// ------------------------------------------------------------------- file
589
590
#[derive(Clone, Debug)]
591
pub enum FileBody {
592
    Text(String),
593
    Binary,
594
    TooLarge,
595
}
596
597
/// One row of the file page's tree sidebar (hub spec §6.6).
598
#[derive(Clone, Debug, PartialEq, Eq)]
599
pub struct SideEntry {
600
    pub name: String,
601
    pub path: String,
602
    pub depth: usize,
603
    pub dir: bool,
604
    /// A directory on the way to the file (expanded), or the file itself.
605
    pub on_path: bool,
606
    /// A "more" row standing for the rest of a long directory.
607
    pub more: bool,
608
}
609
610
/// Entries listed per directory in the sidebar before a "more" row.
611
const SIDEBAR_PER_DIR: usize = 200;
612
613
/// The tree down to `path`: each directory on the way expanded, in tree
614
/// order (directories first, then case-insensitive names).
61527×
pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> {
61665×
    sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path)
61727×
}
618
619
/// `sidebar` over any path map, given which values are directories.
62029×
pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> {
62129×
    let mut out = Vec::new();
62229×
    sidebar_dir(files, is_dir, "", path, 0, &mut out);
62329×
    out
62429×
}
625
62638×
fn sidebar_dir<V>(
62738×
    files: &BTreeMap<String, V>,
62838×
    is_dir: impl Fn(&V) -> bool + Copy,
62938×
    dir: &str,
63038×
    target: &str,
63138×
    depth: usize,
63238×
    out: &mut Vec<SideEntry>,
63338×
) {
63438×
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
63538×
    let mut children: Vec<(&str, bool)> = files
63638×
        .range(prefix.clone()..)
637608×
        .take_while(|(p, _)| p.starts_with(&prefix))
638607×
        .filter(|(p, _)| !p[prefix.len()..].contains('/'))
639324×
        .map(|(p, f)| (p.as_str(), is_dir(f)))
64038×
        .collect();
641294×
    children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));
64238×
    let total = children.len();
643324×
    for (i, (p, dir_entry)) in children.into_iter().enumerate() {
644324×
        let on_path = target == p || target.starts_with(&format!("{p}/"));
645
        // Past the limit, keep only the entry on the way to the file.
646324×
        if i >= SIDEBAR_PER_DIR && !on_path {
64749×
            continue;
648275×
        }
649275×
        out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false });
650275×
        if dir_entry && on_path && p != target {
6519×
            sidebar_dir(files, is_dir, p, target, depth + 1, out);
652266×
        }
653
    }
65438×
    if total > SIDEBAR_PER_DIR {
6551×
        out.push(SideEntry {
6561×
            name: format!("{} more", total - SIDEBAR_PER_DIR),
6571×
            path: dir.to_string(),
6581×
            depth,
6591×
            dir: true,
6601×
            on_path: false,
6611×
            more: true,
6621×
        });
66337×
    }
66438×
}
665
666
#[derive(Clone, Debug)]
667
pub struct FileView {
668
    pub target: RefTarget,
669
    pub path: String,
670
    pub name: String,
671
    pub crumbs: Vec<(String, String)>,
672
    pub kind: EntryKind,
673
    pub exec: bool,
674
    pub size: u64,
675
    pub body: FileBody,
676
    pub conflicted: bool,
677
    /// Raw bytes, for the `?plain=1` response and images.
678
    pub bytes: Vec<u8>,
679
    pub last_change: Option<ChangeView>,
680
    pub sidebar: Vec<SideEntry>,
681
}
682
68329×
pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> {
68429×
    let loaded = cache.load(repo, &target.heads)?;
68529×
    let snapshot = &loaded.snapshot;
68629×
    let path = path.trim_matches('/');
68729×
    let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) };
68827×
    let (kind, bytes) = match (&f.kind, &f.content) {
6890×
        (NodeKind::Dir, _) => return Err(RepoError::NotFound),
6900×
        (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()),
6910×
        (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()),
69224×
        (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()),
6933×
        (_, FileContent::Opaque { blobs }) => {
6943×
            let bytes = match blobs.first() {
6953×
                Some(b) => repo.read_blob(b)?,
6960×
                None => Vec::new(),
697
            };
6983×
            (EntryKind::File, bytes)
699
        }
7000×
        (_, FileContent::Dir) => return Err(RepoError::NotFound),
701
    };
70227×
    let size = bytes.len() as u64;
70327×
    let body = if size > render_limit {
7040×
        FileBody::TooLarge
70527×
    } else if is_binary(&bytes) {
7063×
        FileBody::Binary
707
    } else {
70824×
        FileBody::Text(String::from_utf8_lossy(&bytes).into_owned())
709
    };
71027×
    let labels = head_labels(repo)?;
71127×
    let last_change = last_change_of(repo, &loaded.state, &target.heads, path)
71227×
        .and_then(|h| loaded.state.get(&h).map(|meta| change_view(repo, &h, meta, loaded.state.heads().contains(&h), &labels)));
71327×
    let name = path.rsplit('/').next().unwrap_or(path).to_string();
71427×
    Ok(FileView {
71527×
        target,
71627×
        path: path.to_string(),
71727×
        name,
71827×
        crumbs: crumbs(path),
71927×
        kind,
72027×
        exec: f.mode.exec,
72127×
        size,
72227×
        body,
72327×
        conflicted: f.is_conflicted(),
72427×
        bytes,
72527×
        last_change,
72627×
        sidebar: sidebar(snapshot, path),
72727×
    })
72829×
}
729
730
/// A file's name and bytes, and nothing else (for raw responses).
73113×
pub fn raw(repo: &Repo, cache: &StateCache, target: &RefTarget, path: &str) -> Result<(String, Vec<u8>)> {
73213×
    let loaded = cache.load(repo, &target.heads)?;
73313×
    let path = path.trim_matches('/');
73413×
    let Some(f) = loaded.snapshot.files.get(path) else { return Err(RepoError::NotFound) };
73513×
    let bytes = match (&f.kind, &f.content) {
7360×
        (NodeKind::Dir, _) | (_, FileContent::Dir) => return Err(RepoError::NotFound),
73711×
        (_, FileContent::Text { bytes, .. }) => bytes.clone(),
7382×
        (_, FileContent::Opaque { blobs }) => match blobs.first() {
7392×
            Some(b) => repo.read_blob(b)?,
7400×
            None => Vec::new(),
741
        },
742
    };
74313×
    Ok((path.rsplit('/').next().unwrap_or(path).to_string(), bytes))
74413×
}
745
746
/// Facts about a path in a state never change, so they are cached by the
747
/// state's heads and the path (hub spec §16.3).
74831×
fn state_path_key(tag: &[u8], heads: &[ChangeHash], path: &str) -> [u8; 32] {
74931×
    let mut sorted: Vec<&ChangeHash> = heads.iter().collect();
75031×
    sorted.sort();
75180×
    let joined: Vec<u8> = sorted.iter().flat_map(|h| h.to_hex().into_bytes()).collect();
75231×
    crate::render::cache::key(&[tag, &joined, path.as_bytes()])
75331×
}
754
755
struct Last(Option<ChangeHash>);
756
757
impl crate::render::cache::Weigh for Last {
75811×
    fn weight(&self) -> usize {
75911×
        64
76011×
    }
761
}
762
763
/// The newest change touching `path` in the state, from a cache of 4 MiB.
76427×
pub fn last_change_of(repo: &Repo, state: &oxy_core::state::State, heads: &[ChangeHash], path: &str) -> Option<ChangeHash> {
765
    static C: std::sync::OnceLock<crate::render::cache::Lru<Last>> = std::sync::OnceLock::new();
76627×
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(4 << 20));
76727×
    let key = state_path_key(b"last1", heads, path);
76827×
    cache.get_or(key, || Last(repo.log_for_path_of(state, path, Some(1)).ok().and_then(|l| l.into_iter().next()).map(|e| e.hash))).0
76927×
}
770
771
struct BlameLines(Vec<BlameLine>);
772
773
impl crate::render::cache::Weigh for BlameLines {
7744×
    fn weight(&self) -> usize {
77513×
        self.0.iter().map(|l| l.text.len() + l.author.len() + 128).sum::<usize>() + 32
7764×
    }
777
}
778
779
/// `Repo::blame_in`, cached by state and path (64 MiB).
7804×
fn blame_cached(repo: &Repo, cache_state: &StateCache, heads: &[ChangeHash], path: &str) -> Result<Vec<BlameLine>> {
781
    static C: std::sync::OnceLock<crate::render::cache::Lru<BlameLines>> = std::sync::OnceLock::new();
7824×
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(64 << 20));
7834×
    let key = state_path_key(b"blame1", heads, path);
7844×
    let mut failure = None;
7854×
    let lines = cache.get_or(key, || {
7864×
        match cache_state
7874×
            .load(repo, heads)
7884×
            .map_err(|e| oxy_core::repo::RepoError::Msg(e.to_string()))
7894×
            .and_then(|loaded| repo.blame_of(&loaded.state, &loaded.snapshot.tree, path))
790
        {
7914×
            Ok(l) => BlameLines(l),
7920×
            Err(e) => {
7930×
                failure = Some(e);
7940×
                BlameLines(Vec::new())
795
            }
796
        }
7974×
    });
7984×
    if let Some(e) = failure {
7990×
        return Err(RepoError::Oxy(e));
8004×
    }
8014×
    Ok(lines.0.clone())
8024×
}
803
804104×
pub fn is_binary(bytes: &[u8]) -> bool {
805104×
    let head = &bytes[..bytes.len().min(8192)];
806104×
    head.contains(&0)
807101×
        || std::str::from_utf8(head).is_err()
8080×
            && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20
809104×
}
810
811
/// Last change per entry of a directory, for tree rows (fetched lazily).
812
/// A directory's last change is the newest change touching anything
813
/// beneath it, as GitHub shows it.
8141×
pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> {
8151×
    let labels = head_labels(repo)?;
8161×
    let loaded = cache.load(repo, heads)?;
8171×
    let state = &loaded.state;
8181×
    let snapshot = &loaded.snapshot;
819
    // Newest change touching each node, from one pass over the log.
8201×
    let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new();
8212×
    for e in repo.log_of(state) {
8222×
        let Ok((c, _)) = repo.store().get_change_lazy(&e.hash) else { continue };
8232×
        let when = e.change.hlc.wall_ms;
82411×
        for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) {
82511×
            newest.entry(node).or_insert((e.hash, when));
82611×
        }
827
    }
8281×
    let mut out = Vec::new();
8292×
    for p in paths {
8302×
        let Some(f) = snapshot.files.get(p) else { continue };
8312×
        let best = if f.kind == NodeKind::Dir {
8321×
            let prefix = format!("{p}/");
8331×
            snapshot
8341×
                .files
8351×
                .iter()
8365×
                .filter(|(q, _)| q.starts_with(&prefix))
8371×
                .filter_map(|(_, g)| newest.get(&g.node))
8381×
                .chain(newest.get(&f.node))
8391×
                .max_by_key(|(_, when)| *when)
8401×
                .copied()
841
        } else {
8421×
            newest.get(&f.node).copied()
843
        };
8442×
        if let Some((hash, _)) = best {
8452×
            if let Some(m) = state.get(&hash) {
8462×
                out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels)));
8472×
            }
8480×
        }
849
    }
8501×
    Ok(out)
8511×
}
852
853
// ------------------------------------------------------------------ blame
854
855
#[derive(Clone, Debug)]
856
pub struct Blame {
857
    pub file: FileView,
858
    pub lines: Vec<BlameLine>,
859
    /// For each blamed change, the state address of its dependencies:
860
    /// the state its author built on (None without dependencies).
861
    pub before: HashMap<ChangeHash, Option<String>>,
862
}
863
8644×
pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> {
8654×
    let heads = target.heads.clone();
8664×
    let file = file(repo, cache, target, path, render_limit)?;
8674×
    let lines = blame_cached(repo, cache, &heads, path)?;
8684×
    let mut before = HashMap::new();
86913×
    for l in &lines {
87013×
        before.entry(l.hash).or_insert_with(|| repo.store().get_change_meta(&l.hash).ok().and_then(|c| state_spec(&c.deps)));
871
    }
8724×
    Ok(Blame { file, lines, before })
8734×
}
874
875
// -------------------------------------------------------------- overview
876
877
#[derive(Clone, Debug)]
878
pub struct BookmarkView {
879
    pub name: String,
880
    pub heads: Vec<String>,
881
    pub changes: usize,
882
    pub default: bool,
883
    pub conflicted: bool,
884
    pub latest_ms: u64,
885
}
886
887
#[derive(Clone, Debug)]
888
pub struct TagView {
889
    pub name: String,
890
    pub heads: Vec<String>,
891
    pub message: String,
892
    pub signer: Option<String>,
893
}
894
895
/// A tag withdrawn here (#301): the state it named, why, by whom and when.
896
#[derive(Clone, Debug)]
897
pub struct WithdrawnView {
898
    pub name: String,
899
    pub heads: Vec<String>,
900
    pub reason: String,
901
    pub signer: Option<String>,
902
    pub when_ms: i64,
903
}
904
905
#[derive(Clone, Debug)]
906
pub struct Overview {
907
    pub tree: Tree,
908
    pub changes: usize,
909
    pub heads: usize,
910
    pub bookmarks: Vec<BookmarkView>,
911
    pub tags: Vec<TagView>,
912
    pub latest: Option<ChangeView>,
913
    pub conflicted: bool,
914
    pub license: Option<String>,
915
    pub policy: PolicyBadge,
916
    pub contributors: Vec<Contributor>,
917
    pub languages: Vec<LanguageShare>,
918
}
919
920
impl Overview {
921
    /// The sidebar's bookmarks (#152): the default first, then the most
922
    /// recently moved, ten in all.
92351×
    pub fn recent_bookmarks(&self) -> Vec<&BookmarkView> {
92451×
        let mut list: Vec<&BookmarkView> = self.bookmarks.iter().collect();
92551×
        list.sort_by(|a, b| b.default.cmp(&a.default).then(b.latest_ms.cmp(&a.latest_ms)).then_with(|| a.name.cmp(&b.name)));
92651×
        list.truncate(10);
92751×
        list
92851×
    }
929
}
930
931
/// Someone who authored changes in a state (hub spec §6.4).
932
#[derive(Clone, Debug, PartialEq, Eq)]
933
pub struct Contributor {
934
    pub name: String,
935
    /// The identity key (hex), empty for authors imported from Git.
936
    pub key: String,
937
    pub changes: usize,
938
    /// The hub account the key is linked to, filled by the web layer.
939
    pub account: Option<String>,
940
    /// Of `changes`, how many a delegate signed for this author, by the
941
    /// delegate's name (an agent's work stays the author's, and is shown).
942
    pub via: Vec<(String, usize)>,
943
    /// The hub's own delegate key, filled by the web layer (#152).
944
    pub hub: bool,
945
}
946
947
/// One language's share of a state's code, by bytes.
948
#[derive(Clone, Debug, PartialEq)]
949
pub struct LanguageShare {
950
    pub name: String,
951
    pub bytes: u64,
952
    pub percent: f64,
953
    pub colour: String,
954
}
955
956
/// Authors of the changes of a state, most changes first. A change a
957
/// delegate signed counts for its author, and the delegate is named under
958
/// them: the signing key is read, not verified (the change rows do that).
95951×
pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> {
96051×
    let mut by: HashMap<String, Contributor> = HashMap::new();
96151×
    let mut names: HashMap<KeyId, String> = HashMap::new();
96255×
    for (hash, meta) in state.changes() {
96355×
        let a = author(repo, &meta.author, &meta.message);
96455×
        let id = if a.key.is_empty() { format!("git:{}", a.email.to_lowercase()) } else { a.key.clone() };
965
        // Unsigned changes with no Git author carry no name at all.
96655×
        let name =
96755×
            if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() };
96855×
        let entry = by.entry(id).or_insert_with(|| Contributor {
96931×
            name,
97031×
            key: a.key.clone(),
971
            changes: 0,
97231×
            account: None,
97331×
            via: Vec::new(),
974
            hub: false,
97531×
        });
97655×
        entry.changes += 1;
97755×
        if !meta.author.is_zero() {
97835×
            let signer = repo.store().signatures(hash).ok().and_then(|s| s.first().map(|s| s.key)).filter(|k| *k != meta.author);
97935×
            if let Some(k) = signer {
98011×
                let who =
98111×
                    names.entry(k).or_insert_with(|| repo.store().get_identity(&k).map(|i| i.name).unwrap_or_else(|_| k.short(12))).clone();
98211×
                match entry.via.iter_mut().find(|(n, _)| *n == who) {
9839×
                    Some((_, n)) => *n += 1,
9842×
                    None => entry.via.push((who, 1)),
985
                }
98624×
            }
98720×
        }
988
    }
98951×
    let mut out: Vec<Contributor> = by.into_values().collect();
99051×
    for c in &mut out {
99131×
        c.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
992
    }
99351×
    out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
99451×
    out
99551×
}
996
997
/// The language of a path for the languages bar: an extension table for
998
/// what syntect lacks, then syntect; `None` for prose, data, lock files and
999
/// vendored or generated paths, which Linguist leaves out too.
100065×
pub fn language_of(path: &str) -> Option<&'static str> {
100165×
    let lower = path.to_ascii_lowercase();
100265×
    let name = lower.rsplit('/').next().unwrap_or(&lower);
100365×
    let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"];
1004381×
    if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) {
10052×
        return None;
100663×
    }
100763×
    if name.ends_with(".lock")
100862×
        || name == "package-lock.json"
100962×
        || name.ends_with(".min.js")
101062×
        || name.ends_with(".min.css")
101162×
        || name.ends_with(".d.ts")
1012
    {
10131×
        return None;
101462×
    }
101562×
    let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
101662×
    let by_ext = match ext {
101762×
        "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"),
101861×
        "toml" => Some("TOML"),
101960×
        "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"),
102060×
        "kdl" => Some("KDL"),
102155×
        "sh" | "bash" | "zsh" => Some("Shell"),
102249×
        "h" => Some("C"),
102347×
        "hpp" | "hh" | "cc" | "cxx" => Some("C++"),
102447×
        "vue" => Some("Vue"),
102547×
        "svelte" => Some("Svelte"),
102647×
        "zig" => Some("Zig"),
102747×
        "nix" => Some("Nix"),
102847×
        "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None,
102915×
        _ => None,
1030
    };
103130×
    if by_ext.is_some() {
103215×
        return by_ext;
103315×
    }
103415×
    let lang = crate::render::highlight::language(path)?;
103512×
    Some(match lang {
103612×
        "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell",
103712×
        "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None,
103812×
        l => l,
1039
    })
104065×
}
1041
1042
/// Linguist's colours for common languages; a stable colour otherwise.
104323×
pub fn language_colour(name: &str) -> String {
104423×
    let known = match name {
104523×
        "Rust" => "#dea584",
104615×
        "Python" => "#3572a5",
104715×
        "Shell" => "#89e051",
104810×
        "Makefile" => "#427819",
104910×
        "C" => "#555555",
10507×
        "C++" => "#f34b7d",
10517×
        "C#" => "#178600",
10527×
        "Assembly" => "#6e4c13",
10537×
        "JavaScript" => "#f1e05a",
10547×
        "TypeScript" => "#3178c6",
10557×
        "HTML" => "#e34c26",
10567×
        "CSS" => "#663399",
10577×
        "Go" => "#00add8",
10587×
        "Java" => "#b07219",
10597×
        "TOML" => "#9c4221",
10607×
        "YAML" => "#cb171e",
10617×
        "SQL" => "#e38c00",
10627×
        "Lua" => "#000080",
10637×
        "Ruby" => "#701516",
10647×
        "PHP" => "#4f5d95",
10657×
        "Haskell" => "#5e5086",
10667×
        "KDL" => "#ffb3b3",
10672×
        "Dockerfile" => "#384d54",
10682×
        "Vue" => "#41b883",
10692×
        "Zig" => "#ec915c",
10702×
        "Nix" => "#7e7eff",
10712×
        _ => "",
1072
    };
107323×
    if !known.is_empty() {
107421×
        return known.to_string();
10752×
    }
10762×
    let h = blake3::hash(name.as_bytes());
10772×
    let b = h.as_bytes();
10782×
    format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2)
107923×
}
1080
1081
/// Languages of a state's files by bytes, largest first; under 1% folds into "Other".
108251×
pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> {
108351×
    let mut by: HashMap<&'static str, u64> = HashMap::new();
108478×
    for (path, f) in &snapshot.files {
108578×
        if let FileContent::Text { bytes, .. } = &f.content {
108656×
            if let Some(l) = language_of(path) {
108722×
                *by.entry(l).or_default() += bytes.len() as u64;
108834×
            }
108922×
        }
1090
    }
109151×
    let total: u64 = by.values().sum();
109251×
    if total == 0 {
109338×
        return vec![];
109413×
    }
109513×
    let mut list: Vec<(&str, u64)> = by.into_iter().collect();
109613×
    list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
109713×
    let mut out: Vec<LanguageShare> = Vec::new();
109813×
    let mut other = 0u64;
109920×
    for (name, bytes) in list {
110020×
        if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 {
11010×
            other += bytes;
110220×
        } else {
110320×
            out.push(LanguageShare {
110420×
                name: name.to_string(),
110520×
                bytes,
110620×
                percent: bytes as f64 * 100.0 / total as f64,
110720×
                colour: language_colour(name),
110820×
            });
110920×
        }
1110
    }
111113×
    if other > 0 {
11120×
        out.push(LanguageShare {
11130×
            name: "Other".into(),
11140×
            bytes: other,
11150×
            percent: other as f64 * 100.0 / total as f64,
11160×
            colour: "#8592ad".into(),
11170×
        });
111813×
    }
111913×
    out
112051×
}
1121
1122
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1123
pub enum PolicyBadge {
1124
    None,
1125
    Active,
1126
    Expired,
1127
}
1128
112966×
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
113066×
    let list = repo.bookmarks()?;
113186×
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
113266×
    let mut out = Vec::new();
113386×
    for (b, s) in list.iter().zip(briefs) {
113486×
        out.push(BookmarkView {
113586×
            name: b.name.clone(),
113692×
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
113786×
            changes: s.changes,
113886×
            default: b.name == default,
113986×
            conflicted: s.conflicted,
114086×
            latest_ms: s.latest_ms,
1141
        });
1142
    }
114366×
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
114466×
    Ok(out)
114566×
}
1146
114783×
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
114883×
    let mut out: Vec<TagView> = repo
114983×
        .tags()?
115083×
        .into_iter()
115183×
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
115283×
        .collect();
115383×
    out.sort_by(|a, b| b.name.cmp(&a.name));
115483×
    Ok(out)
115583×
}
1156
1157
/// The tags withdrawn here, newest first.
11589×
pub fn withdrawn_tags(repo: &Repo) -> Result<Vec<WithdrawnView>> {
11599×
    let mut out: Vec<WithdrawnView> = repo
11609×
        .remote_refs()?
1161
        .withdrawn
11629×
        .into_iter()
11639×
        .filter_map(|t| {
11644×
            let sa = t.attestation?;
11654×
            let oxy_core::attest::AttestBody::Untag { reason, .. } = &sa.attest.body else { return None };
1166
            Some(WithdrawnView {
11674×
                name: t.name,
11684×
                heads: t.heads.iter().map(|h| h.to_hex()).collect(),
11694×
                reason: reason.clone(),
11704×
                signer: sa.sigs.first().and_then(|s| repo.store().get_identity(&s.key).ok()).map(|i| i.name),
11714×
                when_ms: sa.attest.hlc.wall_ms as i64,
1172
            })
11734×
        })
11749×
        .collect();
11759×
    out.sort_by_key(|w| std::cmp::Reverse(w.when_ms));
11769×
    Ok(out)
11779×
}
1178
117951×
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
118051×
    match repo.current_policy() {
11811×
        Ok(Some((_, sp))) => {
11821×
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
11830×
                PolicyBadge::Expired
1184
            } else {
11851×
                PolicyBadge::Active
1186
            }
1187
        }
118850×
        _ => PolicyBadge::None,
1189
    }
119051×
}
1191
1192
/// The overview of `shown` (a bookmark or tag; the default bookmark
1193
/// unless the viewer chose another, oxygenhub#191).
119451×
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str, shown: &str) -> Result<Overview> {
119551×
    let target = match resolve(repo, cache, shown) {
119651×
        Ok(t) => t,
11970×
        Err(_) => RefTarget { label: shown.into(), kind: RefKind::Bookmark, heads: vec![] },
1198
    };
119951×
    let heads = target.heads.len();
1200
    // One load of the default state serves the counts, the latest change
1201
    // and the tree (hub spec §16.3).
120251×
    let loaded = cache.load(repo, &target.heads)?;
120351×
    let state = &loaded.state;
120451×
    let snapshot = &loaded.snapshot;
120551×
    let changes = state.len();
120651×
    let conflicted = snapshot.is_conflicted();
120751×
    let labels = head_labels(repo)?;
120851×
    let latest = state
120951×
        .changes()
121051×
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
121151×
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
121251×
    let tree = tree_of(repo, target, snapshot, "")?;
121351×
    let license = tree
121451×
        .entries
121551×
        .iter()
121658×
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
121751×
        .map(|e| e.path.clone());
1218
    Ok(Overview {
121951×
        tree,
122051×
        changes,
122151×
        heads,
122251×
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
122351×
        tags: tags(repo)?,
122451×
        latest,
122551×
        conflicted,
122651×
        license,
122751×
        policy: policy_badge(repo),
122851×
        contributors: contributors(repo, state),
122951×
        languages: languages(snapshot),
1230
    })
123151×
}
1232
1233
// -------------------------------------------------------------- compare
1234
1235
#[derive(Clone, Debug)]
1236
pub struct Compare {
1237
    pub base: RefTarget,
1238
    pub head: RefTarget,
1239
    /// Changes in `head`'s state not in `base`'s.
1240
    pub added: Vec<ChangeView>,
1241
    /// Changes in `base`'s state not in `head`'s.
1242
    pub missing: usize,
1243
    pub files: Vec<FileDiff>,
1244
    pub bases: BTreeMap<String, Vec<u8>>,
1245
}
1246
12475×
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
12485×
    let base_loaded = cache.load(repo, &base.heads)?;
12495×
    let head_loaded = cache.load(repo, &head.heads)?;
12505×
    let base_state = &base_loaded.state;
12515×
    let head_state = &head_loaded.state;
12525×
    let labels = head_labels(repo)?;
12535×
    let mut added: Vec<ChangeView> = head_state
12545×
        .changes()
12559×
        .filter(|(h, _)| !base_state.contains(h))
12565×
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
12575×
        .collect();
12585×
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
12596×
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
12605×
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
12615×
    Ok(Compare { base, head, added, missing, files, bases })
12625×
}
1263
1264
// ------------------------------------------------------------ conflicts
1265
1266
#[derive(Clone, Debug)]
1267
pub struct ConflictView {
1268
    pub bookmark: String,
1269
    pub path: String,
1270
    pub kind: String,
1271
    /// The file rendered with `oxy` conflict markers, when a text file.
1272
    pub marked: Option<String>,
1273
    pub contributors: Vec<ChangeView>,
1274
}
1275
12768×
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
12778×
    let list = repo.bookmarks()?;
127848×
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
12798×
    let mut out = Vec::new();
128048×
    for (b, brief) in list.iter().zip(briefs) {
1281
        // Only a conflicted state is loaded whole.
128248×
        if !brief.conflicted {
128345×
            continue;
12843×
        }
12853×
        let loaded = cache.load(repo, &b.heads)?;
12863×
        out.extend(conflicts_in(repo, &loaded, &b.name));
1287
    }
12888×
    Ok(out)
12898×
}
1290
1291
/// The conflicts of one loaded state, labelled with `bookmark`.
129215×
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
129315×
    let labels = head_labels(repo).unwrap_or_default();
129415×
    let mut out = Vec::new();
1295
    {
129615×
        let b_name = bookmark.to_string();
129715×
        let state = &loaded.state;
129815×
        let snapshot = &loaded.snapshot;
129915×
        for c in &snapshot.tree.conflicts {
13004×
            let (path, kind) = describe_tree_conflict(snapshot, c);
13014×
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
13024×
        }
130367×
        for (path, f) in &snapshot.files {
130467×
            if !f.is_conflicted() {
130556×
                continue;
130611×
            }
130711×
            let (kind, marked, contributors) = match &f.content {
1308
                FileContent::Text { .. } => {
13097×
                    let (bytes, _) = state.render_file(&f.node);
13107×
                    let regions = state.conflict_regions(&f.node);
13117×
                    let contributors: Vec<ChangeView> = regions
13127×
                        .contributors
13137×
                        .iter()
131414×
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
13157×
                        .collect();
13167×
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
1317
                }
13184×
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
13190×
                FileContent::Dir => continue,
1320
            };
132111×
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
1322
        }
1323
    }
132415×
    out
132515×
}
1326
13274×
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
13284×
    let by_node = snapshot.tree.by_node();
13294×
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
13304×
    match c {
13314×
        TreeConflict::Name { name, nodes, parent } => {
13324×
            let path = if parent.is_root() { name.clone() } else { format!("{}/{name}", path_of(parent)) };
13334×
            (path, format!("name: {} entries want this name", nodes.len()))
1334
        }
13350×
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
13360×
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
13370×
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
13380×
        other => (String::new(), format!("{other:?}")),
1339
    }
13404×
}
1341
1342
// ------------------------------------------------------------------ trust
1343
1344
#[derive(Clone, Debug)]
1345
pub struct KeyView {
1346
    pub key: String,
1347
    pub short: String,
1348
    pub name: String,
1349
    pub email: String,
1350
}
1351
1352
#[derive(Clone, Debug)]
1353
pub struct RuleView {
1354
    pub pattern: String,
1355
    pub keys: Vec<KeyView>,
1356
    pub threshold: u32,
1357
    pub require: String,
1358
    pub allow_conflicts: bool,
1359
}
1360
1361
#[derive(Clone, Debug)]
1362
pub struct PolicyView {
1363
    pub serial: u64,
1364
    pub expires_ms: u64,
1365
    pub expired: bool,
1366
    pub roots: Vec<KeyView>,
1367
    pub root_threshold: u32,
1368
    pub rules: Vec<RuleView>,
1369
    pub revoked: Vec<KeyView>,
1370
    pub signatures: usize,
1371
    pub history: usize,
1372
}
1373
1374
#[derive(Clone, Debug, Default)]
1375
pub struct Verification {
1376
    pub total: usize,
1377
    pub signed: usize,
1378
    pub sealed: usize,
1379
    pub unsigned: usize,
1380
    pub revoked: usize,
1381
    pub invalid: Vec<(String, String)>,
1382
}
1383
1384
#[derive(Clone, Debug)]
1385
pub struct Trust {
1386
    pub policy: Option<PolicyView>,
1387
    pub verification: Verification,
1388
    pub hub_key: String,
1389
    pub hub_delegated_by: Vec<KeyView>,
1390
}
1391
13922×
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
13934×
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
13942×
    match found {
13952×
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
13960×
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
1397
    }
13982×
}
1399
14004×
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
14014×
    let heads = all_heads(repo)?;
14024×
    let loaded = cache.load(repo, &heads)?;
14034×
    let state = &loaded.state;
14044×
    let mut v = Verification::default();
14057×
    for (h, _) in state.changes() {
14067×
        v.total += 1;
14077×
        match signature(repo, h) {
14081×
            SigView::Unsigned => v.unsigned += 1,
14096×
            SigView::Valid { sealed, revoked, .. } => {
14106×
                if revoked {
14110×
                    v.revoked += 1;
14126×
                }
14136×
                if sealed {
14140×
                    v.sealed += 1
1415
                } else {
14166×
                    v.signed += 1
1417
                }
1418
            }
14190×
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1420
        }
1421
    }
14224×
    Ok(v)
14234×
}
1424
14253×
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
14263×
    let policy = match repo.current_policy()? {
14271×
        Some((_, sp)) => {
14281×
            let p = &sp.policy;
14291×
            let ids = &p.identities;
14301×
            let require = |r: &oxy_core::policy::Require| match r {
14310×
                oxy_core::policy::Require::Signed => "signed",
14320×
                oxy_core::policy::Require::Sealed => "sealed",
14331×
                oxy_core::policy::Require::Any => "any",
14341×
            };
1435
            Some(PolicyView {
14361×
                serial: p.serial,
14371×
                expires_ms: p.expires,
14381×
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
14391×
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
14401×
                root_threshold: p.root_threshold,
14411×
                rules: p
14421×
                    .rules
14431×
                    .iter()
14441×
                    .map(|r| RuleView {
14451×
                        pattern: r.pattern.clone(),
14461×
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
14471×
                        threshold: r.threshold,
14481×
                        require: require(&r.require).into(),
14491×
                        allow_conflicts: r.allow_conflicts,
14501×
                    })
14511×
                    .collect(),
14521×
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
14531×
                signatures: sp.sigs.len(),
14541×
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1455
            })
1456
        }
14572×
        None => None,
1458
    };
1459
    // Who has delegated to the hub: every identity in the policy or store
1460
    // that lists the hub key.
14613×
    let mut delegated = Vec::new();
14623×
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
14632×
        for i in &p.identities {
14642×
            if i.delegate(hub_key).is_some() {
14651×
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
14661×
            }
1467
        }
14682×
    }
14693×
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
14703×
}
1471
1472
#[cfg(test)]
1473
mod language_tests {
1474
    use super::*;
1475
1476
    #[test]
14771×
    fn languages_are_detected_and_prose_is_left_out() {
14781×
        assert_eq!(language_of("src/main.rs"), Some("Rust"));
14791×
        assert_eq!(language_of("boot/start.s"), Some("Assembly"));
14801×
        assert_eq!(language_of("build.sh"), Some("Shell"));
14811×
        assert_eq!(language_of("Makefile"), Some("Makefile"));
14821×
        assert_eq!(language_of("Cargo.toml"), Some("TOML"));
14831×
        assert_eq!(language_of("README.md"), None);
14841×
        assert_eq!(language_of("Cargo.lock"), None);
14851×
        assert_eq!(language_of("web/node_modules/x/index.js"), None);
14861×
        assert_eq!(language_of("vendor/lib.c"), None);
14871×
        assert_eq!(language_colour("Rust"), "#dea584");
14881×
        assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable");
14891×
    }
1490
}
1491
1492
#[cfg(test)]
1493
mod tests {
1494
    use super::*;
1495
14962×
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
14972×
        let mut m = BTreeMap::new();
1498256×
        for p in paths {
1499256×
            let mut end = 0;
1500256×
            let parts: Vec<&str> = p.split('/').collect();
1501512×
            for (i, part) in parts.iter().enumerate() {
1502512×
                end += part.len();
1503512×
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1504512×
                end += 1;
1505512×
            }
1506
        }
15072×
        m
15082×
    }
1509
1510
    #[test]
15111×
    fn sidebar_expands_the_path_only() {
15121×
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
15131×
        let rows: Vec<(String, usize, bool, bool)> =
15148×
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
15151×
        let want = [
15161×
            ("docs", 0, true, false),
15171×
            ("src", 0, true, true),
15181×
            ("src/lib", 1, true, true),
15191×
            ("src/lib/a.rs", 2, false, false),
15201×
            ("src/lib/b.rs", 2, false, true),
15211×
            ("src/main.rs", 1, false, false),
15221×
            ("README.md", 0, false, false),
15231×
            ("Zeta.txt", 0, false, false),
15241×
        ];
15258×
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
15261×
    }
1527
1528
    #[test]
15291×
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1530250×
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
15311×
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
15321×
        let files = tree(&refs);
15331×
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1534203×
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
15351×
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
15361×
        assert!(listed.last().unwrap().on_path);
15371×
        let more = rows.iter().find(|e| e.more).unwrap();
15381×
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
15391×
    }
1540
1541
    #[test]
15421×
    fn state_addresses_are_sorted_and_bounded() {
15431×
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
15441×
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
15451×
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
15461×
        assert_eq!(state_spec(&[]), None);
15471×
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
15481×
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
15491×
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
15501×
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
15511×
    }
1552
}