OXYGENHUB
# f87a74fffc87 oxygenhub / crates / hub / src / repos / view.rs
56.8 KiB · Rust · last changed Create and withdraw tags on the website (closes #295, closes #301) 12 days ago source blame history raw
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
15
fn fail(msg: impl Into<String>) -> RepoError {
16
    RepoError::Oxy(oxy_core::repo::RepoError::Msg(msg.into()))
17
}
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.
43
    pub fn short_label(&self) -> String {
44
        match self.kind {
45
            RefKind::Change => {
46
                let mut parts = self.label.split('+');
47
                let first: String = parts.next().unwrap_or("").chars().take(12).collect();
48
                match parts.count() {
49
                    0 => first,
50
                    n => format!("{first} +{n}"),
51
                }
52
            }
53
            _ => self.label.clone(),
54
        }
55
    }
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.
59
    pub fn permalink(&self) -> Option<String> {
60
        state_spec(&self.heads)
61
    }
62
}
63
64
/// Heads as a state address, sorted so one state has one address.
65
pub fn state_spec(heads: &[ChangeHash]) -> Option<String> {
66
    if heads.is_empty() || heads.len() > MAX_STATE_HEADS {
67
        return None;
68
    }
69
    let mut hex: Vec<String> = heads.iter().map(|h| h.to_hex()).collect();
70
    hex.sort();
71
    hex.dedup();
72
    Some(hex.join("+"))
73
}
74
75
/// Resolve a bookmark name, a tag name, a change hash prefix, or a state
76
/// (full hashes joined with `+`).
77
pub fn resolve(repo: &Repo, cache: &StateCache, spec: &str) -> Result<RefTarget> {
78
    if spec.contains('+') {
79
        let parts: Vec<&str> = spec.split('+').collect();
80
        if parts.len() > MAX_STATE_HEADS {
81
            return Err(fail(format!("a state address has at most {MAX_STATE_HEADS} heads")));
82
        }
83
        let mut heads = Vec::with_capacity(parts.len());
84
        for p in parts {
85
            match ChangeHash::from_hex(p) {
86
                Some(h) if p.len() == 64 && repo.store().has(&h) => heads.push(h),
87
                _ => return Err(fail(format!("{p:?} is not a change of this repository"))),
88
            }
89
        }
90
        heads.sort();
91
        heads.dedup();
92
        let label = state_spec(&heads).unwrap_or_default();
93
        return Ok(RefTarget { label, kind: RefKind::Change, heads });
94
    }
95
    let view = repo.view()?;
96
    if let Some(heads) = view.bookmarks.get(spec).map(|st| repo.store().get_state(st).map(|s| s.heads)).transpose()? {
97
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Bookmark, heads });
98
    }
99
    if let Some(heads) = repo.tag_heads(spec)? {
100
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Tag, heads });
101
    }
102
    let hash = resolve_change(repo, cache, spec)?;
103
    Ok(RefTarget { label: hash.to_hex(), kind: RefKind::Change, heads: vec![hash] })
104
}
105
106
/// A change by full hash or unique hex prefix, searched over every
107
/// bookmark's state.
108
pub fn resolve_change(repo: &Repo, cache: &StateCache, spec: &str) -> Result<ChangeHash> {
109
    let spec = spec.trim_start_matches('#');
110
    if spec.len() < 4 || !spec.chars().all(|c| c.is_ascii_hexdigit()) {
111
        return Err(fail(format!("{spec:?} is not a change")));
112
    }
113
    if let Some(h) = ChangeHash::from_hex(spec) {
114
        if repo.store().has(&h) {
115
            return Ok(h);
116
        }
117
    }
118
    let heads = all_heads(repo)?;
119
    let loaded = cache.load(repo, &heads)?;
120
    let matches: Vec<ChangeHash> = loaded.state.changes().map(|(h, _)| *h).filter(|h| h.starts_with_hex(spec)).collect();
121
    match matches.len() {
122
        1 => Ok(matches[0]),
123
        0 => Err(fail(format!("no change matches {spec:?}"))),
124
        _ => Err(fail(format!("{spec:?} is ambiguous"))),
125
    }
126
}
127
128
/// The heads of every bookmark, deduplicated.
129
pub fn all_heads(repo: &Repo) -> Result<Vec<ChangeHash>> {
130
    let mut set = BTreeSet::new();
131
    for b in repo.bookmarks()? {
132
        set.extend(b.heads);
133
    }
134
    Ok(set.into_iter().collect())
135
}
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
150
pub fn author(repo: &Repo, key: &KeyId, message: &str) -> AuthorView {
151
    if key.is_zero() {
152
        // Imported from Git: the trailer carries the author.
153
        let line = message.lines().rev().find_map(|l| l.strip_prefix("Git-Author: ")).unwrap_or("unknown");
154
        let (name, email) = match line.split_once('<') {
155
            Some((n, e)) => (n.trim().to_string(), e.trim_end_matches('>').trim().to_string()),
156
            None => (line.trim().to_string(), String::new()),
157
        };
158
        return AuthorView { name, email, key: String::new(), unknown: true, account: None };
159
    }
160
    match repo.store().get_identity(key) {
161
        Ok(id) => AuthorView { name: id.name, email: id.email, key: key.to_hex(), unknown: false, account: None },
162
        Err(_) => AuthorView { name: key.short(12), email: String::new(), key: key.to_hex(), unknown: true, account: None },
163
    }
164
}
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 {
176
    pub fn glyph(&self) -> &'static str {
177
        match self {
178
            SigView::Unsigned => "○",
179
            SigView::Valid { revoked: true, .. } => "⊘",
180
            SigView::Valid { sealed: true, .. } => "◈",
181
            SigView::Valid { .. } => "✔",
182
            SigView::Invalid(_) => "✘",
183
        }
184
    }
185
186
    pub fn class(&self) -> &'static str {
187
        match self {
188
            SigView::Unsigned => "sig-unsigned",
189
            SigView::Valid { revoked: true, .. } => "sig-revoked",
190
            SigView::Valid { .. } => "sig-valid",
191
            SigView::Invalid(_) => "sig-invalid",
192
        }
193
    }
194
195
    pub fn title(&self) -> String {
196
        match self {
197
            SigView::Unsigned => "unsigned".into(),
198
            SigView::Valid { name, sealed: true, revoked: false, .. } => format!("sealed by {name}"),
199
            SigView::Valid { name, revoked: true, .. } => format!("signed by {name}, key revoked"),
200
            SigView::Valid { name, .. } => format!("signed by {name}"),
201
            SigView::Invalid(why) => format!("INVALID: {why}"),
202
        }
203
    }
204
}
205
206
pub fn signature(repo: &Repo, hash: &ChangeHash) -> SigView {
207
    match repo.verify_change(hash) {
208
        Ok(SignatureStatus::Unsigned) => SigView::Unsigned,
209
        Ok(SignatureStatus::Valid { key, name, sealed, revoked, .. }) => SigView::Valid { key: key.to_hex(), name, sealed, revoked },
210
        Ok(SignatureStatus::Invalid(why)) => SigView::Invalid(why),
211
        Err(e) => SigView::Invalid(e.to_string()),
212
    }
213
}
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.
234
    pub fn delegation(&self) -> String {
235
        if self.revoked {
236
            return "delegation revoked".into();
237
        }
238
        match self.expires_ms {
239
            Some(e) => format!("delegate for {}, until {}", self.scope, when_utc(e)),
240
            None => format!("delegate for {}", self.scope),
241
        }
242
    }
243
244
    /// What hovering the badge says.
245
    pub fn title(&self) -> String {
246
        let until = match self.expires_ms {
247
            Some(e) => format!(", until {}", when_utc(e)),
248
            None => String::new(),
249
        };
250
        if self.revoked {
251
            format!("signed by {} as a delegate of the author; that delegation has since been revoked", self.name)
252
        } else {
253
            format!("signed by {} as a delegate of the author ({}{until}), key {}", self.name, self.scope, self.short)
254
        }
255
    }
256
}
257
258
/// `2026-10-04 20:12Z` for a wall time in milliseconds.
259
fn when_utc(ms: u64) -> String {
260
    time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000)
261
        .ok()
262
        .and_then(|t| t.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]Z")).ok())
263
        .unwrap_or_else(|| ms.to_string())
264
}
265
266
/// The delegate that signed `hash` for the author, when one did.
267
pub fn via(repo: &Repo, author: &KeyId, sig: &SigView) -> Option<ViaView> {
268
    let SigView::Valid { key, name, revoked, .. } = sig else { return None };
269
    if author.is_zero() || *key == author.to_hex() {
270
        return None;
271
    }
272
    let signer = KeyId::from_hex(key)?;
273
    let entry = repo.store().get_identity(author).ok().and_then(|a| a.delegate(&signer).copied());
274
    let email = repo.store().get_identity(&signer).map(|i| i.email).unwrap_or_default();
275
    Some(ViaView {
276
        name: name.clone(),
277
        email,
278
        key: key.clone(),
279
        short: signer.short(12),
280
        scope: entry.map(|d| d.scope.to_string()).unwrap_or_else(|| "changes".into()),
281
        expires_ms: entry.and_then(|d| d.expires),
282
        revoked: *revoked || entry.is_none(),
283
    })
284
}
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
311
pub fn split_message(message: &str) -> (String, String) {
312
    let mut lines = message.lines();
313
    let title = lines.next().unwrap_or("").trim().to_string();
314
    let body = lines.collect::<Vec<_>>().join("\n").trim().to_string();
315
    (title, body)
316
}
317
318
/// Every bookmark and tag head, for labelling rows.
319
pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> {
320
    let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new();
321
    for b in repo.bookmarks()? {
322
        for h in b.heads {
323
            out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark });
324
        }
325
    }
326
    for t in repo.tags()? {
327
        for h in t.heads {
328
            out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag });
329
        }
330
    }
331
    Ok(out)
332
}
333
334
pub fn change_view_pub(
335
    repo: &Repo,
336
    hash: &ChangeHash,
337
    meta: &oxy_core::state::ChangeMeta,
338
    head: bool,
339
    labels: &HashMap<ChangeHash, Vec<Label>>,
340
) -> ChangeView {
341
    change_view(repo, hash, meta, head, labels)
342
}
343
344
fn change_view(
345
    repo: &Repo,
346
    hash: &ChangeHash,
347
    meta: &oxy_core::state::ChangeMeta,
348
    head: bool,
349
    labels: &HashMap<ChangeHash, Vec<Label>>,
350
) -> ChangeView {
351
    let (title, body) = split_message(&meta.message);
352
    let signature = signature(repo, hash);
353
    let via = via(repo, &meta.author, &signature);
354
    ChangeView {
355
        hash: hash.to_hex(),
356
        short: hash.short(12),
357
        title,
358
        body,
359
        author: author(repo, &meta.author, &meta.message),
360
        when_ms: meta.hlc.wall_ms,
361
        deps: meta.deps.iter().map(|d| d.to_hex()).collect(),
362
        head,
363
        resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution,
364
        signature,
365
        via,
366
        labels: labels.get(hash).cloned().unwrap_or_default(),
367
    }
368
}
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.
383
pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> {
384
    let loaded = cache.load(repo, &target.heads)?;
385
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
386
    let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path {
387
        Some(p) => {
388
            let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) };
389
            loaded
390
                .state
391
                .changes()
392
                .filter(|(h, _)| {
393
                    // The skeleton says which nodes a change touches, without its text.
394
                    repo.store()
395
                        .get_change_lazy(h)
396
                        .map(|(c, _)| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node))
397
                        .unwrap_or(false)
398
                })
399
                .map(|(h, m)| (*h, m.clone()))
400
                .collect()
401
        }
402
        None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(),
403
    };
404
    entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0)));
405
    let total = entries.len();
406
    let labels = head_labels(repo)?;
407
    let window: Vec<ChangeView> =
408
        entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect();
409
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) })
410
}
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.
416
pub fn history_revset(repo: &Repo, cache: &StateCache, target: RefTarget, revset: &str, offset: usize, limit: usize) -> Result<History> {
417
    let loaded = cache.load(repo, &target.heads)?;
418
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
419
    let selected = repo.revset_with_budget(revset, std::time::Duration::from_secs(2))?;
420
    let total = selected.hashes.len();
421
    let labels = head_labels(repo)?;
422
    let window: Vec<ChangeView> = selected
423
        .hashes
424
        .iter()
425
        .skip(offset)
426
        .take(limit)
427
        .filter_map(|h| selected.metas.get(h).map(|m| change_view(repo, h, m, head_set.contains(h), &labels)))
428
        .collect();
429
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: None })
430
}
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
448
pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> {
449
    let c: Change = repo.store().get_change(hash)?;
450
    let labels = head_labels(repo)?;
451
    let heads = all_heads(repo)?;
452
    let loaded = cache.load(repo, &heads)?;
453
    let state = &loaded.state;
454
    let is_head = state.heads().contains(hash);
455
    let meta = oxy_core::state::ChangeMeta::of(&c);
456
    let view = change_view(repo, hash, &meta, is_head, &labels);
457
    let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect();
458
    let mut dependents: Vec<ChangeView> = state
459
        .changes()
460
        .filter(|(_, m)| m.deps.contains(hash))
461
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels))
462
        .collect();
463
    dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
464
    let base = cache.load(repo, &c.deps)?;
465
    let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot);
466
    let base_snapshot = &base.snapshot;
467
    let mut bases = BTreeMap::new();
468
    for f in &files {
469
        let old = f.from.as_deref().unwrap_or(&f.path);
470
        if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) {
471
            bases.insert(f.path.clone(), bytes.clone());
472
        }
473
    }
474
    let mut in_bookmarks = Vec::new();
475
    for b in repo.bookmarks()? {
476
        if cache.summary(repo, &b.heads)?.changes.contains(hash) {
477
            in_bookmarks.push(b.name);
478
        }
479
    }
480
    let mut in_tags = Vec::new();
481
    for t in repo.tags()? {
482
        if cache.summary(repo, &t.heads)?.changes.contains(hash) {
483
            in_tags.push(t.name);
484
        }
485
    }
486
    Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() })
487
}
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
525
pub fn crumbs(path: &str) -> Vec<(String, String)> {
526
    let mut out = Vec::new();
527
    let mut so_far = String::new();
528
    for part in path.split('/').filter(|p| !p.is_empty()) {
529
        if !so_far.is_empty() {
530
            so_far.push('/');
531
        }
532
        so_far.push_str(part);
533
        out.push((part.to_string(), so_far.clone()));
534
    }
535
    out
536
}
537
538
fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry {
539
    let kind = match f.kind {
540
        NodeKind::Dir => EntryKind::Dir,
541
        NodeKind::File => EntryKind::File,
542
        NodeKind::Symlink => EntryKind::Symlink,
543
        NodeKind::Subrepo => EntryKind::Subrepo,
544
    };
545
    let size = match &f.content {
546
        FileContent::Text { bytes, .. } => Some(bytes.len() as u64),
547
        _ => None,
548
    };
549
    Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() }
550
}
551
552
/// The entries directly under `dir` (`""` for the root).
553
pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> {
554
    let loaded = cache.load(repo, &target.heads)?;
555
    tree_of(repo, target, &loaded.snapshot, dir)
556
}
557
558
pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> {
559
    let dir = dir.trim_matches('/');
560
    if !dir.is_empty() {
561
        match snapshot.files.get(dir) {
562
            Some(f) if f.kind == NodeKind::Dir => {}
563
            _ => return Err(RepoError::NotFound),
564
        }
565
    }
566
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
567
    let mut entries: Vec<Entry> = snapshot
568
        .files
569
        .iter()
570
        .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/'))
571
        .map(|(p, f)| entry_of(p, &p[prefix.len()..], f))
572
        .collect();
573
    entries.sort_by(|a, b| {
574
        (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
575
    });
576
    let readme = entries
577
        .iter()
578
        .find(|e| {
579
            e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown")
580
        })
581
        .and_then(|e| match &snapshot.files.get(&e.path)?.content {
582
            FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }),
583
            _ => None,
584
        });
585
    Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme })
586
}
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).
615
pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> {
616
    sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path)
617
}
618
619
/// `sidebar` over any path map, given which values are directories.
620
pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> {
621
    let mut out = Vec::new();
622
    sidebar_dir(files, is_dir, "", path, 0, &mut out);
623
    out
624
}
625
626
fn sidebar_dir<V>(
627
    files: &BTreeMap<String, V>,
628
    is_dir: impl Fn(&V) -> bool + Copy,
629
    dir: &str,
630
    target: &str,
631
    depth: usize,
632
    out: &mut Vec<SideEntry>,
633
) {
634
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
635
    let mut children: Vec<(&str, bool)> = files
636
        .range(prefix.clone()..)
637
        .take_while(|(p, _)| p.starts_with(&prefix))
638
        .filter(|(p, _)| !p[prefix.len()..].contains('/'))
639
        .map(|(p, f)| (p.as_str(), is_dir(f)))
640
        .collect();
641
    children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));
642
    let total = children.len();
643
    for (i, (p, dir_entry)) in children.into_iter().enumerate() {
644
        let on_path = target == p || target.starts_with(&format!("{p}/"));
645
        // Past the limit, keep only the entry on the way to the file.
646
        if i >= SIDEBAR_PER_DIR && !on_path {
647
            continue;
648
        }
649
        out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false });
650
        if dir_entry && on_path && p != target {
651
            sidebar_dir(files, is_dir, p, target, depth + 1, out);
652
        }
653
    }
654
    if total > SIDEBAR_PER_DIR {
655
        out.push(SideEntry {
656
            name: format!("{} more", total - SIDEBAR_PER_DIR),
657
            path: dir.to_string(),
658
            depth,
659
            dir: true,
660
            on_path: false,
661
            more: true,
662
        });
663
    }
664
}
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
683
pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> {
684
    let loaded = cache.load(repo, &target.heads)?;
685
    let snapshot = &loaded.snapshot;
686
    let path = path.trim_matches('/');
687
    let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) };
688
    let (kind, bytes) = match (&f.kind, &f.content) {
689
        (NodeKind::Dir, _) => return Err(RepoError::NotFound),
690
        (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()),
691
        (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()),
692
        (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()),
693
        (_, FileContent::Opaque { blobs }) => {
694
            let bytes = match blobs.first() {
695
                Some(b) => repo.read_blob(b)?,
696
                None => Vec::new(),
697
            };
698
            (EntryKind::File, bytes)
699
        }
700
        (_, FileContent::Dir) => return Err(RepoError::NotFound),
701
    };
702
    let size = bytes.len() as u64;
703
    let body = if size > render_limit {
704
        FileBody::TooLarge
705
    } else if is_binary(&bytes) {
706
        FileBody::Binary
707
    } else {
708
        FileBody::Text(String::from_utf8_lossy(&bytes).into_owned())
709
    };
710
    let labels = head_labels(repo)?;
711
    let last_change = last_change_of(repo, &loaded.state, &target.heads, path)
712
        .and_then(|h| loaded.state.get(&h).map(|meta| change_view(repo, &h, meta, loaded.state.heads().contains(&h), &labels)));
713
    let name = path.rsplit('/').next().unwrap_or(path).to_string();
714
    Ok(FileView {
715
        target,
716
        path: path.to_string(),
717
        name,
718
        crumbs: crumbs(path),
719
        kind,
720
        exec: f.mode.exec,
721
        size,
722
        body,
723
        conflicted: f.is_conflicted(),
724
        bytes,
725
        last_change,
726
        sidebar: sidebar(snapshot, path),
727
    })
728
}
729
730
/// A file's name and bytes, and nothing else (for raw responses).
731
pub fn raw(repo: &Repo, cache: &StateCache, target: &RefTarget, path: &str) -> Result<(String, Vec<u8>)> {
732
    let loaded = cache.load(repo, &target.heads)?;
733
    let path = path.trim_matches('/');
734
    let Some(f) = loaded.snapshot.files.get(path) else { return Err(RepoError::NotFound) };
735
    let bytes = match (&f.kind, &f.content) {
736
        (NodeKind::Dir, _) | (_, FileContent::Dir) => return Err(RepoError::NotFound),
737
        (_, FileContent::Text { bytes, .. }) => bytes.clone(),
738
        (_, FileContent::Opaque { blobs }) => match blobs.first() {
739
            Some(b) => repo.read_blob(b)?,
740
            None => Vec::new(),
741
        },
742
    };
743
    Ok((path.rsplit('/').next().unwrap_or(path).to_string(), bytes))
744
}
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).
748
fn state_path_key(tag: &[u8], heads: &[ChangeHash], path: &str) -> [u8; 32] {
749
    let mut sorted: Vec<&ChangeHash> = heads.iter().collect();
750
    sorted.sort();
751
    let joined: Vec<u8> = sorted.iter().flat_map(|h| h.to_hex().into_bytes()).collect();
752
    crate::render::cache::key(&[tag, &joined, path.as_bytes()])
753
}
754
755
struct Last(Option<ChangeHash>);
756
757
impl crate::render::cache::Weigh for Last {
758
    fn weight(&self) -> usize {
759
        64
760
    }
761
}
762
763
/// The newest change touching `path` in the state, from a cache of 4 MiB.
764
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();
766
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(4 << 20));
767
    let key = state_path_key(b"last1", heads, path);
768
    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
769
}
770
771
struct BlameLines(Vec<BlameLine>);
772
773
impl crate::render::cache::Weigh for BlameLines {
774
    fn weight(&self) -> usize {
775
        self.0.iter().map(|l| l.text.len() + l.author.len() + 128).sum::<usize>() + 32
776
    }
777
}
778
779
/// `Repo::blame_in`, cached by state and path (64 MiB).
780
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();
782
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(64 << 20));
783
    let key = state_path_key(b"blame1", heads, path);
784
    let mut failure = None;
785
    let lines = cache.get_or(key, || {
786
        match cache_state
787
            .load(repo, heads)
788
            .map_err(|e| oxy_core::repo::RepoError::Msg(e.to_string()))
789
            .and_then(|loaded| repo.blame_of(&loaded.state, &loaded.snapshot.tree, path))
790
        {
791
            Ok(l) => BlameLines(l),
792
            Err(e) => {
793
                failure = Some(e);
794
                BlameLines(Vec::new())
795
            }
796
        }
797
    });
798
    if let Some(e) = failure {
799
        return Err(RepoError::Oxy(e));
800
    }
801
    Ok(lines.0.clone())
802
}
803
804
pub fn is_binary(bytes: &[u8]) -> bool {
805
    let head = &bytes[..bytes.len().min(8192)];
806
    head.contains(&0)
807
        || std::str::from_utf8(head).is_err()
808
            && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20
809
}
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.
814
pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> {
815
    let labels = head_labels(repo)?;
816
    let loaded = cache.load(repo, heads)?;
817
    let state = &loaded.state;
818
    let snapshot = &loaded.snapshot;
819
    // Newest change touching each node, from one pass over the log.
820
    let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new();
821
    for e in repo.log_of(state) {
822
        let Ok((c, _)) = repo.store().get_change_lazy(&e.hash) else { continue };
823
        let when = e.change.hlc.wall_ms;
824
        for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) {
825
            newest.entry(node).or_insert((e.hash, when));
826
        }
827
    }
828
    let mut out = Vec::new();
829
    for p in paths {
830
        let Some(f) = snapshot.files.get(p) else { continue };
831
        let best = if f.kind == NodeKind::Dir {
832
            let prefix = format!("{p}/");
833
            snapshot
834
                .files
835
                .iter()
836
                .filter(|(q, _)| q.starts_with(&prefix))
837
                .filter_map(|(_, g)| newest.get(&g.node))
838
                .chain(newest.get(&f.node))
839
                .max_by_key(|(_, when)| *when)
840
                .copied()
841
        } else {
842
            newest.get(&f.node).copied()
843
        };
844
        if let Some((hash, _)) = best {
845
            if let Some(m) = state.get(&hash) {
846
                out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels)));
847
            }
848
        }
849
    }
850
    Ok(out)
851
}
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
864
pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> {
865
    let heads = target.heads.clone();
866
    let file = file(repo, cache, target, path, render_limit)?;
867
    let lines = blame_cached(repo, cache, &heads, path)?;
868
    let mut before = HashMap::new();
869
    for l in &lines {
870
        before.entry(l.hash).or_insert_with(|| repo.store().get_change_meta(&l.hash).ok().and_then(|c| state_spec(&c.deps)));
871
    }
872
    Ok(Blame { file, lines, before })
873
}
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.
923
    pub fn recent_bookmarks(&self) -> Vec<&BookmarkView> {
924
        let mut list: Vec<&BookmarkView> = self.bookmarks.iter().collect();
925
        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)));
926
        list.truncate(10);
927
        list
928
    }
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).
959
pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> {
960
    let mut by: HashMap<String, Contributor> = HashMap::new();
961
    let mut names: HashMap<KeyId, String> = HashMap::new();
962
    for (hash, meta) in state.changes() {
963
        let a = author(repo, &meta.author, &meta.message);
964
        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.
966
        let name =
967
            if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() };
968
        let entry = by.entry(id).or_insert_with(|| Contributor {
969
            name,
970
            key: a.key.clone(),
971
            changes: 0,
972
            account: None,
973
            via: Vec::new(),
974
            hub: false,
975
        });
976
        entry.changes += 1;
977
        if !meta.author.is_zero() {
978
            let signer = repo.store().signatures(hash).ok().and_then(|s| s.first().map(|s| s.key)).filter(|k| *k != meta.author);
979
            if let Some(k) = signer {
980
                let who =
981
                    names.entry(k).or_insert_with(|| repo.store().get_identity(&k).map(|i| i.name).unwrap_or_else(|_| k.short(12))).clone();
982
                match entry.via.iter_mut().find(|(n, _)| *n == who) {
983
                    Some((_, n)) => *n += 1,
984
                    None => entry.via.push((who, 1)),
985
                }
986
            }
987
        }
988
    }
989
    let mut out: Vec<Contributor> = by.into_values().collect();
990
    for c in &mut out {
991
        c.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
992
    }
993
    out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
994
    out
995
}
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.
1000
pub fn language_of(path: &str) -> Option<&'static str> {
1001
    let lower = path.to_ascii_lowercase();
1002
    let name = lower.rsplit('/').next().unwrap_or(&lower);
1003
    let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"];
1004
    if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) {
1005
        return None;
1006
    }
1007
    if name.ends_with(".lock")
1008
        || name == "package-lock.json"
1009
        || name.ends_with(".min.js")
1010
        || name.ends_with(".min.css")
1011
        || name.ends_with(".d.ts")
1012
    {
1013
        return None;
1014
    }
1015
    let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
1016
    let by_ext = match ext {
1017
        "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"),
1018
        "toml" => Some("TOML"),
1019
        "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"),
1020
        "kdl" => Some("KDL"),
1021
        "sh" | "bash" | "zsh" => Some("Shell"),
1022
        "h" => Some("C"),
1023
        "hpp" | "hh" | "cc" | "cxx" => Some("C++"),
1024
        "vue" => Some("Vue"),
1025
        "svelte" => Some("Svelte"),
1026
        "zig" => Some("Zig"),
1027
        "nix" => Some("Nix"),
1028
        "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None,
1029
        _ => None,
1030
    };
1031
    if by_ext.is_some() {
1032
        return by_ext;
1033
    }
1034
    let lang = crate::render::highlight::language(path)?;
1035
    Some(match lang {
1036
        "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell",
1037
        "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None,
1038
        l => l,
1039
    })
1040
}
1041
1042
/// Linguist's colours for common languages; a stable colour otherwise.
1043
pub fn language_colour(name: &str) -> String {
1044
    let known = match name {
1045
        "Rust" => "#dea584",
1046
        "Python" => "#3572a5",
1047
        "Shell" => "#89e051",
1048
        "Makefile" => "#427819",
1049
        "C" => "#555555",
1050
        "C++" => "#f34b7d",
1051
        "C#" => "#178600",
1052
        "Assembly" => "#6e4c13",
1053
        "JavaScript" => "#f1e05a",
1054
        "TypeScript" => "#3178c6",
1055
        "HTML" => "#e34c26",
1056
        "CSS" => "#663399",
1057
        "Go" => "#00add8",
1058
        "Java" => "#b07219",
1059
        "TOML" => "#9c4221",
1060
        "YAML" => "#cb171e",
1061
        "SQL" => "#e38c00",
1062
        "Lua" => "#000080",
1063
        "Ruby" => "#701516",
1064
        "PHP" => "#4f5d95",
1065
        "Haskell" => "#5e5086",
1066
        "KDL" => "#ffb3b3",
1067
        "Dockerfile" => "#384d54",
1068
        "Vue" => "#41b883",
1069
        "Zig" => "#ec915c",
1070
        "Nix" => "#7e7eff",
1071
        _ => "",
1072
    };
1073
    if !known.is_empty() {
1074
        return known.to_string();
1075
    }
1076
    let h = blake3::hash(name.as_bytes());
1077
    let b = h.as_bytes();
1078
    format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2)
1079
}
1080
1081
/// Languages of a state's files by bytes, largest first; under 1% folds into "Other".
1082
pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> {
1083
    let mut by: HashMap<&'static str, u64> = HashMap::new();
1084
    for (path, f) in &snapshot.files {
1085
        if let FileContent::Text { bytes, .. } = &f.content {
1086
            if let Some(l) = language_of(path) {
1087
                *by.entry(l).or_default() += bytes.len() as u64;
1088
            }
1089
        }
1090
    }
1091
    let total: u64 = by.values().sum();
1092
    if total == 0 {
1093
        return vec![];
1094
    }
1095
    let mut list: Vec<(&str, u64)> = by.into_iter().collect();
1096
    list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
1097
    let mut out: Vec<LanguageShare> = Vec::new();
1098
    let mut other = 0u64;
1099
    for (name, bytes) in list {
1100
        if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 {
1101
            other += bytes;
1102
        } else {
1103
            out.push(LanguageShare {
1104
                name: name.to_string(),
1105
                bytes,
1106
                percent: bytes as f64 * 100.0 / total as f64,
1107
                colour: language_colour(name),
1108
            });
1109
        }
1110
    }
1111
    if other > 0 {
1112
        out.push(LanguageShare {
1113
            name: "Other".into(),
1114
            bytes: other,
1115
            percent: other as f64 * 100.0 / total as f64,
1116
            colour: "#8592ad".into(),
1117
        });
1118
    }
1119
    out
1120
}
1121
1122
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1123
pub enum PolicyBadge {
1124
    None,
1125
    Active,
1126
    Expired,
1127
}
1128
1129
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
1130
    let list = repo.bookmarks()?;
1131
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
1132
    let mut out = Vec::new();
1133
    for (b, s) in list.iter().zip(briefs) {
1134
        out.push(BookmarkView {
1135
            name: b.name.clone(),
1136
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
1137
            changes: s.changes,
1138
            default: b.name == default,
1139
            conflicted: s.conflicted,
1140
            latest_ms: s.latest_ms,
1141
        });
1142
    }
1143
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
1144
    Ok(out)
1145
}
1146
1147
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
1148
    let mut out: Vec<TagView> = repo
1149
        .tags()?
1150
        .into_iter()
1151
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
1152
        .collect();
1153
    out.sort_by(|a, b| b.name.cmp(&a.name));
1154
    Ok(out)
1155
}
1156
1157
/// The tags withdrawn here, newest first.
1158
pub fn withdrawn_tags(repo: &Repo) -> Result<Vec<WithdrawnView>> {
1159
    let mut out: Vec<WithdrawnView> = repo
1160
        .remote_refs()?
1161
        .withdrawn
1162
        .into_iter()
1163
        .filter_map(|t| {
1164
            let sa = t.attestation?;
1165
            let oxy_core::attest::AttestBody::Untag { reason, .. } = &sa.attest.body else { return None };
1166
            Some(WithdrawnView {
1167
                name: t.name,
1168
                heads: t.heads.iter().map(|h| h.to_hex()).collect(),
1169
                reason: reason.clone(),
1170
                signer: sa.sigs.first().and_then(|s| repo.store().get_identity(&s.key).ok()).map(|i| i.name),
1171
                when_ms: sa.attest.hlc.wall_ms as i64,
1172
            })
1173
        })
1174
        .collect();
1175
    out.sort_by_key(|w| std::cmp::Reverse(w.when_ms));
1176
    Ok(out)
1177
}
1178
1179
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
1180
    match repo.current_policy() {
1181
        Ok(Some((_, sp))) => {
1182
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
1183
                PolicyBadge::Expired
1184
            } else {
1185
                PolicyBadge::Active
1186
            }
1187
        }
1188
        _ => PolicyBadge::None,
1189
    }
1190
}
1191
1192
/// The overview of `shown` (a bookmark or tag; the default bookmark
1193
/// unless the viewer chose another, oxygenhub#191).
1194
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str, shown: &str) -> Result<Overview> {
1195
    let target = match resolve(repo, cache, shown) {
1196
        Ok(t) => t,
1197
        Err(_) => RefTarget { label: shown.into(), kind: RefKind::Bookmark, heads: vec![] },
1198
    };
1199
    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).
1202
    let loaded = cache.load(repo, &target.heads)?;
1203
    let state = &loaded.state;
1204
    let snapshot = &loaded.snapshot;
1205
    let changes = state.len();
1206
    let conflicted = snapshot.is_conflicted();
1207
    let labels = head_labels(repo)?;
1208
    let latest = state
1209
        .changes()
1210
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
1211
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
1212
    let tree = tree_of(repo, target, snapshot, "")?;
1213
    let license = tree
1214
        .entries
1215
        .iter()
1216
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
1217
        .map(|e| e.path.clone());
1218
    Ok(Overview {
1219
        tree,
1220
        changes,
1221
        heads,
1222
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
1223
        tags: tags(repo)?,
1224
        latest,
1225
        conflicted,
1226
        license,
1227
        policy: policy_badge(repo),
1228
        contributors: contributors(repo, state),
1229
        languages: languages(snapshot),
1230
    })
1231
}
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
1247
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
1248
    let base_loaded = cache.load(repo, &base.heads)?;
1249
    let head_loaded = cache.load(repo, &head.heads)?;
1250
    let base_state = &base_loaded.state;
1251
    let head_state = &head_loaded.state;
1252
    let labels = head_labels(repo)?;
1253
    let mut added: Vec<ChangeView> = head_state
1254
        .changes()
1255
        .filter(|(h, _)| !base_state.contains(h))
1256
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
1257
        .collect();
1258
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
1259
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
1260
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
1261
    Ok(Compare { base, head, added, missing, files, bases })
1262
}
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
1276
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
1277
    let list = repo.bookmarks()?;
1278
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
1279
    let mut out = Vec::new();
1280
    for (b, brief) in list.iter().zip(briefs) {
1281
        // Only a conflicted state is loaded whole.
1282
        if !brief.conflicted {
1283
            continue;
1284
        }
1285
        let loaded = cache.load(repo, &b.heads)?;
1286
        out.extend(conflicts_in(repo, &loaded, &b.name));
1287
    }
1288
    Ok(out)
1289
}
1290
1291
/// The conflicts of one loaded state, labelled with `bookmark`.
1292
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
1293
    let labels = head_labels(repo).unwrap_or_default();
1294
    let mut out = Vec::new();
1295
    {
1296
        let b_name = bookmark.to_string();
1297
        let state = &loaded.state;
1298
        let snapshot = &loaded.snapshot;
1299
        for c in &snapshot.tree.conflicts {
1300
            let (path, kind) = describe_tree_conflict(snapshot, c);
1301
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
1302
        }
1303
        for (path, f) in &snapshot.files {
1304
            if !f.is_conflicted() {
1305
                continue;
1306
            }
1307
            let (kind, marked, contributors) = match &f.content {
1308
                FileContent::Text { .. } => {
1309
                    let (bytes, _) = state.render_file(&f.node);
1310
                    let regions = state.conflict_regions(&f.node);
1311
                    let contributors: Vec<ChangeView> = regions
1312
                        .contributors
1313
                        .iter()
1314
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
1315
                        .collect();
1316
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
1317
                }
1318
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
1319
                FileContent::Dir => continue,
1320
            };
1321
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
1322
        }
1323
    }
1324
    out
1325
}
1326
1327
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
1328
    let by_node = snapshot.tree.by_node();
1329
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
1330
    match c {
1331
        TreeConflict::Name { name, nodes, parent } => {
1332
            let path = if parent.is_root() { name.clone() } else { format!("{}/{name}", path_of(parent)) };
1333
            (path, format!("name: {} entries want this name", nodes.len()))
1334
        }
1335
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
1336
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
1337
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
1338
        other => (String::new(), format!("{other:?}")),
1339
    }
1340
}
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
1392
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
1393
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
1394
    match found {
1395
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
1396
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
1397
    }
1398
}
1399
1400
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
1401
    let heads = all_heads(repo)?;
1402
    let loaded = cache.load(repo, &heads)?;
1403
    let state = &loaded.state;
1404
    let mut v = Verification::default();
1405
    for (h, _) in state.changes() {
1406
        v.total += 1;
1407
        match signature(repo, h) {
1408
            SigView::Unsigned => v.unsigned += 1,
1409
            SigView::Valid { sealed, revoked, .. } => {
1410
                if revoked {
1411
                    v.revoked += 1;
1412
                }
1413
                if sealed {
1414
                    v.sealed += 1
1415
                } else {
1416
                    v.signed += 1
1417
                }
1418
            }
1419
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1420
        }
1421
    }
1422
    Ok(v)
1423
}
1424
1425
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
1426
    let policy = match repo.current_policy()? {
1427
        Some((_, sp)) => {
1428
            let p = &sp.policy;
1429
            let ids = &p.identities;
1430
            let require = |r: &oxy_core::policy::Require| match r {
1431
                oxy_core::policy::Require::Signed => "signed",
1432
                oxy_core::policy::Require::Sealed => "sealed",
1433
                oxy_core::policy::Require::Any => "any",
1434
            };
1435
            Some(PolicyView {
1436
                serial: p.serial,
1437
                expires_ms: p.expires,
1438
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
1439
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
1440
                root_threshold: p.root_threshold,
1441
                rules: p
1442
                    .rules
1443
                    .iter()
1444
                    .map(|r| RuleView {
1445
                        pattern: r.pattern.clone(),
1446
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
1447
                        threshold: r.threshold,
1448
                        require: require(&r.require).into(),
1449
                        allow_conflicts: r.allow_conflicts,
1450
                    })
1451
                    .collect(),
1452
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
1453
                signatures: sp.sigs.len(),
1454
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1455
            })
1456
        }
1457
        None => None,
1458
    };
1459
    // Who has delegated to the hub: every identity in the policy or store
1460
    // that lists the hub key.
1461
    let mut delegated = Vec::new();
1462
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
1463
        for i in &p.identities {
1464
            if i.delegate(hub_key).is_some() {
1465
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
1466
            }
1467
        }
1468
    }
1469
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
1470
}
1471
1472
#[cfg(test)]
1473
mod language_tests {
1474
    use super::*;
1475
1476
    #[test]
1477
    fn languages_are_detected_and_prose_is_left_out() {
1478
        assert_eq!(language_of("src/main.rs"), Some("Rust"));
1479
        assert_eq!(language_of("boot/start.s"), Some("Assembly"));
1480
        assert_eq!(language_of("build.sh"), Some("Shell"));
1481
        assert_eq!(language_of("Makefile"), Some("Makefile"));
1482
        assert_eq!(language_of("Cargo.toml"), Some("TOML"));
1483
        assert_eq!(language_of("README.md"), None);
1484
        assert_eq!(language_of("Cargo.lock"), None);
1485
        assert_eq!(language_of("web/node_modules/x/index.js"), None);
1486
        assert_eq!(language_of("vendor/lib.c"), None);
1487
        assert_eq!(language_colour("Rust"), "#dea584");
1488
        assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable");
1489
    }
1490
}
1491
1492
#[cfg(test)]
1493
mod tests {
1494
    use super::*;
1495
1496
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
1497
        let mut m = BTreeMap::new();
1498
        for p in paths {
1499
            let mut end = 0;
1500
            let parts: Vec<&str> = p.split('/').collect();
1501
            for (i, part) in parts.iter().enumerate() {
1502
                end += part.len();
1503
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1504
                end += 1;
1505
            }
1506
        }
1507
        m
1508
    }
1509
1510
    #[test]
1511
    fn sidebar_expands_the_path_only() {
1512
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
1513
        let rows: Vec<(String, usize, bool, bool)> =
1514
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
1515
        let want = [
1516
            ("docs", 0, true, false),
1517
            ("src", 0, true, true),
1518
            ("src/lib", 1, true, true),
1519
            ("src/lib/a.rs", 2, false, false),
1520
            ("src/lib/b.rs", 2, false, true),
1521
            ("src/main.rs", 1, false, false),
1522
            ("README.md", 0, false, false),
1523
            ("Zeta.txt", 0, false, false),
1524
        ];
1525
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
1526
    }
1527
1528
    #[test]
1529
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1530
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
1531
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1532
        let files = tree(&refs);
1533
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1534
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
1535
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
1536
        assert!(listed.last().unwrap().on_path);
1537
        let more = rows.iter().find(|e| e.more).unwrap();
1538
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
1539
    }
1540
1541
    #[test]
1542
    fn state_addresses_are_sorted_and_bounded() {
1543
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
1544
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
1545
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
1546
        assert_eq!(state_spec(&[]), None);
1547
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
1548
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
1549
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
1550
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
1551
    }
1552
}