OXYGENHUB
# 155cab142b63 oxygenhub / crates / hub / src / repos / view.rs
54.8 KiB · Rust · last changed Who did the work: via AGENT, rotated identities link themselves, a Flow badge 1 month 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.load(repo, &b.heads)?.state.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.load(repo, &t.heads)?.state.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
#[derive(Clone, Debug)]
896
pub struct Overview {
897
    pub tree: Tree,
898
    pub changes: usize,
899
    pub heads: usize,
900
    pub bookmarks: Vec<BookmarkView>,
901
    pub tags: Vec<TagView>,
902
    pub latest: Option<ChangeView>,
903
    pub conflicted: bool,
904
    pub license: Option<String>,
905
    pub policy: PolicyBadge,
906
    pub contributors: Vec<Contributor>,
907
    pub languages: Vec<LanguageShare>,
908
}
909
910
/// Someone who authored changes in a state (hub spec §6.4).
911
#[derive(Clone, Debug, PartialEq, Eq)]
912
pub struct Contributor {
913
    pub name: String,
914
    /// The identity key (hex), empty for authors imported from Git.
915
    pub key: String,
916
    pub changes: usize,
917
    /// The hub account the key is linked to, filled by the web layer.
918
    pub account: Option<String>,
919
    /// Of `changes`, how many a delegate signed for this author, by the
920
    /// delegate's name (an agent's work stays the author's, and is shown).
921
    pub via: Vec<(String, usize)>,
922
}
923
924
/// One language's share of a state's code, by bytes.
925
#[derive(Clone, Debug, PartialEq)]
926
pub struct LanguageShare {
927
    pub name: String,
928
    pub bytes: u64,
929
    pub percent: f64,
930
    pub colour: String,
931
}
932
933
/// Authors of the changes of a state, most changes first. A change a
934
/// delegate signed counts for its author, and the delegate is named under
935
/// them: the signing key is read, not verified (the change rows do that).
936
pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> {
937
    let mut by: HashMap<String, Contributor> = HashMap::new();
938
    let mut names: HashMap<KeyId, String> = HashMap::new();
939
    for (hash, meta) in state.changes() {
940
        let a = author(repo, &meta.author, &meta.message);
941
        let id = if a.key.is_empty() { format!("git:{}", a.email.to_lowercase()) } else { a.key.clone() };
942
        // Unsigned changes with no Git author carry no name at all.
943
        let name =
944
            if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() };
945
        let entry = by.entry(id).or_insert_with(|| Contributor { name, key: a.key.clone(), changes: 0, account: None, via: Vec::new() });
946
        entry.changes += 1;
947
        if !meta.author.is_zero() {
948
            let signer = repo.store().signatures(hash).ok().and_then(|s| s.first().map(|s| s.key)).filter(|k| *k != meta.author);
949
            if let Some(k) = signer {
950
                let who =
951
                    names.entry(k).or_insert_with(|| repo.store().get_identity(&k).map(|i| i.name).unwrap_or_else(|_| k.short(12))).clone();
952
                match entry.via.iter_mut().find(|(n, _)| *n == who) {
953
                    Some((_, n)) => *n += 1,
954
                    None => entry.via.push((who, 1)),
955
                }
956
            }
957
        }
958
    }
959
    let mut out: Vec<Contributor> = by.into_values().collect();
960
    for c in &mut out {
961
        c.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
962
    }
963
    out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
964
    out
965
}
966
967
/// The language of a path for the languages bar: an extension table for
968
/// what syntect lacks, then syntect; `None` for prose, data, lock files and
969
/// vendored or generated paths, which Linguist leaves out too.
970
pub fn language_of(path: &str) -> Option<&'static str> {
971
    let lower = path.to_ascii_lowercase();
972
    let name = lower.rsplit('/').next().unwrap_or(&lower);
973
    let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"];
974
    if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) {
975
        return None;
976
    }
977
    if name.ends_with(".lock")
978
        || name == "package-lock.json"
979
        || name.ends_with(".min.js")
980
        || name.ends_with(".min.css")
981
        || name.ends_with(".d.ts")
982
    {
983
        return None;
984
    }
985
    let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
986
    let by_ext = match ext {
987
        "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"),
988
        "toml" => Some("TOML"),
989
        "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"),
990
        "kdl" => Some("KDL"),
991
        "sh" | "bash" | "zsh" => Some("Shell"),
992
        "h" => Some("C"),
993
        "hpp" | "hh" | "cc" | "cxx" => Some("C++"),
994
        "vue" => Some("Vue"),
995
        "svelte" => Some("Svelte"),
996
        "zig" => Some("Zig"),
997
        "nix" => Some("Nix"),
998
        "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None,
999
        _ => None,
1000
    };
1001
    if by_ext.is_some() {
1002
        return by_ext;
1003
    }
1004
    let lang = crate::render::highlight::language(path)?;
1005
    Some(match lang {
1006
        "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell",
1007
        "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None,
1008
        l => l,
1009
    })
1010
}
1011
1012
/// Linguist's colours for common languages; a stable colour otherwise.
1013
pub fn language_colour(name: &str) -> String {
1014
    let known = match name {
1015
        "Rust" => "#dea584",
1016
        "Python" => "#3572a5",
1017
        "Shell" => "#89e051",
1018
        "Makefile" => "#427819",
1019
        "C" => "#555555",
1020
        "C++" => "#f34b7d",
1021
        "C#" => "#178600",
1022
        "Assembly" => "#6e4c13",
1023
        "JavaScript" => "#f1e05a",
1024
        "TypeScript" => "#3178c6",
1025
        "HTML" => "#e34c26",
1026
        "CSS" => "#663399",
1027
        "Go" => "#00add8",
1028
        "Java" => "#b07219",
1029
        "TOML" => "#9c4221",
1030
        "YAML" => "#cb171e",
1031
        "SQL" => "#e38c00",
1032
        "Lua" => "#000080",
1033
        "Ruby" => "#701516",
1034
        "PHP" => "#4f5d95",
1035
        "Haskell" => "#5e5086",
1036
        "KDL" => "#ffb3b3",
1037
        "Dockerfile" => "#384d54",
1038
        "Vue" => "#41b883",
1039
        "Zig" => "#ec915c",
1040
        "Nix" => "#7e7eff",
1041
        _ => "",
1042
    };
1043
    if !known.is_empty() {
1044
        return known.to_string();
1045
    }
1046
    let h = blake3::hash(name.as_bytes());
1047
    let b = h.as_bytes();
1048
    format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2)
1049
}
1050
1051
/// Languages of a state's files by bytes, largest first; under 1% folds into "Other".
1052
pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> {
1053
    let mut by: HashMap<&'static str, u64> = HashMap::new();
1054
    for (path, f) in &snapshot.files {
1055
        if let FileContent::Text { bytes, .. } = &f.content {
1056
            if let Some(l) = language_of(path) {
1057
                *by.entry(l).or_default() += bytes.len() as u64;
1058
            }
1059
        }
1060
    }
1061
    let total: u64 = by.values().sum();
1062
    if total == 0 {
1063
        return vec![];
1064
    }
1065
    let mut list: Vec<(&str, u64)> = by.into_iter().collect();
1066
    list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
1067
    let mut out: Vec<LanguageShare> = Vec::new();
1068
    let mut other = 0u64;
1069
    for (name, bytes) in list {
1070
        if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 {
1071
            other += bytes;
1072
        } else {
1073
            out.push(LanguageShare {
1074
                name: name.to_string(),
1075
                bytes,
1076
                percent: bytes as f64 * 100.0 / total as f64,
1077
                colour: language_colour(name),
1078
            });
1079
        }
1080
    }
1081
    if other > 0 {
1082
        out.push(LanguageShare {
1083
            name: "Other".into(),
1084
            bytes: other,
1085
            percent: other as f64 * 100.0 / total as f64,
1086
            colour: "#8592ad".into(),
1087
        });
1088
    }
1089
    out
1090
}
1091
1092
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1093
pub enum PolicyBadge {
1094
    None,
1095
    Active,
1096
    Expired,
1097
}
1098
1099
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
1100
    let mut out = Vec::new();
1101
    for b in repo.bookmarks()? {
1102
        let loaded = cache.load(repo, &b.heads)?;
1103
        let state = &loaded.state;
1104
        let latest_ms = state.changes().map(|(_, m)| m.hlc.wall_ms).max().unwrap_or(0);
1105
        let conflicted = loaded.snapshot.is_conflicted();
1106
        out.push(BookmarkView {
1107
            name: b.name.clone(),
1108
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
1109
            changes: state.len(),
1110
            default: b.name == default,
1111
            conflicted,
1112
            latest_ms,
1113
        });
1114
    }
1115
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
1116
    Ok(out)
1117
}
1118
1119
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
1120
    let mut out: Vec<TagView> = repo
1121
        .tags()?
1122
        .into_iter()
1123
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
1124
        .collect();
1125
    out.sort_by(|a, b| b.name.cmp(&a.name));
1126
    Ok(out)
1127
}
1128
1129
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
1130
    match repo.current_policy() {
1131
        Ok(Some((_, sp))) => {
1132
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
1133
                PolicyBadge::Expired
1134
            } else {
1135
                PolicyBadge::Active
1136
            }
1137
        }
1138
        _ => PolicyBadge::None,
1139
    }
1140
}
1141
1142
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str) -> Result<Overview> {
1143
    let target = match resolve(repo, cache, default_bookmark) {
1144
        Ok(t) => t,
1145
        Err(_) => RefTarget { label: default_bookmark.into(), kind: RefKind::Bookmark, heads: vec![] },
1146
    };
1147
    let heads = target.heads.len();
1148
    // One load of the default state serves the counts, the latest change
1149
    // and the tree (hub spec §16.3).
1150
    let loaded = cache.load(repo, &target.heads)?;
1151
    let state = &loaded.state;
1152
    let snapshot = &loaded.snapshot;
1153
    let changes = state.len();
1154
    let conflicted = snapshot.is_conflicted();
1155
    let labels = head_labels(repo)?;
1156
    let latest = state
1157
        .changes()
1158
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
1159
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
1160
    let tree = tree_of(repo, target, snapshot, "")?;
1161
    let license = tree
1162
        .entries
1163
        .iter()
1164
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
1165
        .map(|e| e.path.clone());
1166
    Ok(Overview {
1167
        tree,
1168
        changes,
1169
        heads,
1170
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
1171
        tags: tags(repo)?,
1172
        latest,
1173
        conflicted,
1174
        license,
1175
        policy: policy_badge(repo),
1176
        contributors: contributors(repo, state),
1177
        languages: languages(snapshot),
1178
    })
1179
}
1180
1181
// -------------------------------------------------------------- compare
1182
1183
#[derive(Clone, Debug)]
1184
pub struct Compare {
1185
    pub base: RefTarget,
1186
    pub head: RefTarget,
1187
    /// Changes in `head`'s state not in `base`'s.
1188
    pub added: Vec<ChangeView>,
1189
    /// Changes in `base`'s state not in `head`'s.
1190
    pub missing: usize,
1191
    pub files: Vec<FileDiff>,
1192
    pub bases: BTreeMap<String, Vec<u8>>,
1193
}
1194
1195
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
1196
    let base_loaded = cache.load(repo, &base.heads)?;
1197
    let head_loaded = cache.load(repo, &head.heads)?;
1198
    let base_state = &base_loaded.state;
1199
    let head_state = &head_loaded.state;
1200
    let labels = head_labels(repo)?;
1201
    let mut added: Vec<ChangeView> = head_state
1202
        .changes()
1203
        .filter(|(h, _)| !base_state.contains(h))
1204
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
1205
        .collect();
1206
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
1207
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
1208
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
1209
    Ok(Compare { base, head, added, missing, files, bases })
1210
}
1211
1212
// ------------------------------------------------------------ conflicts
1213
1214
#[derive(Clone, Debug)]
1215
pub struct ConflictView {
1216
    pub bookmark: String,
1217
    pub path: String,
1218
    pub kind: String,
1219
    /// The file rendered with `oxy` conflict markers, when a text file.
1220
    pub marked: Option<String>,
1221
    pub contributors: Vec<ChangeView>,
1222
}
1223
1224
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
1225
    let mut out = Vec::new();
1226
    for b in repo.bookmarks()? {
1227
        let loaded = cache.load(repo, &b.heads)?;
1228
        out.extend(conflicts_in(repo, &loaded, &b.name));
1229
    }
1230
    Ok(out)
1231
}
1232
1233
/// The conflicts of one loaded state, labelled with `bookmark`.
1234
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
1235
    let labels = head_labels(repo).unwrap_or_default();
1236
    let mut out = Vec::new();
1237
    {
1238
        let b_name = bookmark.to_string();
1239
        let state = &loaded.state;
1240
        let snapshot = &loaded.snapshot;
1241
        for c in &snapshot.tree.conflicts {
1242
            let (path, kind) = describe_tree_conflict(snapshot, c);
1243
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
1244
        }
1245
        for (path, f) in &snapshot.files {
1246
            if !f.is_conflicted() {
1247
                continue;
1248
            }
1249
            let (kind, marked, contributors) = match &f.content {
1250
                FileContent::Text { .. } => {
1251
                    let (bytes, _) = state.render_file(&f.node);
1252
                    let regions = state.conflict_regions(&f.node);
1253
                    let contributors: Vec<ChangeView> = regions
1254
                        .contributors
1255
                        .iter()
1256
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
1257
                        .collect();
1258
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
1259
                }
1260
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
1261
                FileContent::Dir => continue,
1262
            };
1263
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
1264
        }
1265
    }
1266
    out
1267
}
1268
1269
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
1270
    let by_node = snapshot.tree.by_node();
1271
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
1272
    match c {
1273
        TreeConflict::Name { name, nodes, parent } => {
1274
            let path = if parent.is_root() { name.clone() } else { format!("{}/{name}", path_of(parent)) };
1275
            (path, format!("name: {} entries want this name", nodes.len()))
1276
        }
1277
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
1278
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
1279
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
1280
        other => (String::new(), format!("{other:?}")),
1281
    }
1282
}
1283
1284
// ------------------------------------------------------------------ trust
1285
1286
#[derive(Clone, Debug)]
1287
pub struct KeyView {
1288
    pub key: String,
1289
    pub short: String,
1290
    pub name: String,
1291
    pub email: String,
1292
}
1293
1294
#[derive(Clone, Debug)]
1295
pub struct RuleView {
1296
    pub pattern: String,
1297
    pub keys: Vec<KeyView>,
1298
    pub threshold: u32,
1299
    pub require: String,
1300
    pub allow_conflicts: bool,
1301
}
1302
1303
#[derive(Clone, Debug)]
1304
pub struct PolicyView {
1305
    pub serial: u64,
1306
    pub expires_ms: u64,
1307
    pub expired: bool,
1308
    pub roots: Vec<KeyView>,
1309
    pub root_threshold: u32,
1310
    pub rules: Vec<RuleView>,
1311
    pub revoked: Vec<KeyView>,
1312
    pub signatures: usize,
1313
    pub history: usize,
1314
}
1315
1316
#[derive(Clone, Debug, Default)]
1317
pub struct Verification {
1318
    pub total: usize,
1319
    pub signed: usize,
1320
    pub sealed: usize,
1321
    pub unsigned: usize,
1322
    pub revoked: usize,
1323
    pub invalid: Vec<(String, String)>,
1324
}
1325
1326
#[derive(Clone, Debug)]
1327
pub struct Trust {
1328
    pub policy: Option<PolicyView>,
1329
    pub verification: Verification,
1330
    pub hub_key: String,
1331
    pub hub_delegated_by: Vec<KeyView>,
1332
}
1333
1334
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
1335
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
1336
    match found {
1337
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
1338
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
1339
    }
1340
}
1341
1342
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
1343
    let heads = all_heads(repo)?;
1344
    let loaded = cache.load(repo, &heads)?;
1345
    let state = &loaded.state;
1346
    let mut v = Verification::default();
1347
    for (h, _) in state.changes() {
1348
        v.total += 1;
1349
        match signature(repo, h) {
1350
            SigView::Unsigned => v.unsigned += 1,
1351
            SigView::Valid { sealed, revoked, .. } => {
1352
                if revoked {
1353
                    v.revoked += 1;
1354
                }
1355
                if sealed {
1356
                    v.sealed += 1
1357
                } else {
1358
                    v.signed += 1
1359
                }
1360
            }
1361
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1362
        }
1363
    }
1364
    Ok(v)
1365
}
1366
1367
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
1368
    let policy = match repo.current_policy()? {
1369
        Some((_, sp)) => {
1370
            let p = &sp.policy;
1371
            let ids = &p.identities;
1372
            let require = |r: &oxy_core::policy::Require| match r {
1373
                oxy_core::policy::Require::Signed => "signed",
1374
                oxy_core::policy::Require::Sealed => "sealed",
1375
                oxy_core::policy::Require::Any => "any",
1376
            };
1377
            Some(PolicyView {
1378
                serial: p.serial,
1379
                expires_ms: p.expires,
1380
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
1381
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
1382
                root_threshold: p.root_threshold,
1383
                rules: p
1384
                    .rules
1385
                    .iter()
1386
                    .map(|r| RuleView {
1387
                        pattern: r.pattern.clone(),
1388
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
1389
                        threshold: r.threshold,
1390
                        require: require(&r.require).into(),
1391
                        allow_conflicts: r.allow_conflicts,
1392
                    })
1393
                    .collect(),
1394
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
1395
                signatures: sp.sigs.len(),
1396
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1397
            })
1398
        }
1399
        None => None,
1400
    };
1401
    // Who has delegated to the hub: every identity in the policy or store
1402
    // that lists the hub key.
1403
    let mut delegated = Vec::new();
1404
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
1405
        for i in &p.identities {
1406
            if i.delegate(hub_key).is_some() {
1407
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
1408
            }
1409
        }
1410
    }
1411
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
1412
}
1413
1414
#[cfg(test)]
1415
mod language_tests {
1416
    use super::*;
1417
1418
    #[test]
1419
    fn languages_are_detected_and_prose_is_left_out() {
1420
        assert_eq!(language_of("src/main.rs"), Some("Rust"));
1421
        assert_eq!(language_of("boot/start.s"), Some("Assembly"));
1422
        assert_eq!(language_of("build.sh"), Some("Shell"));
1423
        assert_eq!(language_of("Makefile"), Some("Makefile"));
1424
        assert_eq!(language_of("Cargo.toml"), Some("TOML"));
1425
        assert_eq!(language_of("README.md"), None);
1426
        assert_eq!(language_of("Cargo.lock"), None);
1427
        assert_eq!(language_of("web/node_modules/x/index.js"), None);
1428
        assert_eq!(language_of("vendor/lib.c"), None);
1429
        assert_eq!(language_colour("Rust"), "#dea584");
1430
        assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable");
1431
    }
1432
}
1433
1434
#[cfg(test)]
1435
mod tests {
1436
    use super::*;
1437
1438
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
1439
        let mut m = BTreeMap::new();
1440
        for p in paths {
1441
            let mut end = 0;
1442
            let parts: Vec<&str> = p.split('/').collect();
1443
            for (i, part) in parts.iter().enumerate() {
1444
                end += part.len();
1445
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1446
                end += 1;
1447
            }
1448
        }
1449
        m
1450
    }
1451
1452
    #[test]
1453
    fn sidebar_expands_the_path_only() {
1454
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
1455
        let rows: Vec<(String, usize, bool, bool)> =
1456
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
1457
        let want = [
1458
            ("docs", 0, true, false),
1459
            ("src", 0, true, true),
1460
            ("src/lib", 1, true, true),
1461
            ("src/lib/a.rs", 2, false, false),
1462
            ("src/lib/b.rs", 2, false, true),
1463
            ("src/main.rs", 1, false, false),
1464
            ("README.md", 0, false, false),
1465
            ("Zeta.txt", 0, false, false),
1466
        ];
1467
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
1468
    }
1469
1470
    #[test]
1471
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1472
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
1473
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1474
        let files = tree(&refs);
1475
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1476
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
1477
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
1478
        assert!(listed.last().unwrap().on_path);
1479
        let more = rows.iter().find(|e| e.more).unwrap();
1480
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
1481
    }
1482
1483
    #[test]
1484
    fn state_addresses_are_sorted_and_bounded() {
1485
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
1486
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
1487
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
1488
        assert_eq!(state_spec(&[]), None);
1489
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
1490
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
1491
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
1492
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
1493
    }
1494
}