OXYGENHUB
# 67b24adbf35a oxygenhub / crates / hub / src / repos / view.rs
46.6 KiB · Rust · last changed Overview: the clone control looks like a button, and unsigned changes with no author count as unattributed 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
/// One change as history rows and change pages show it.
216
#[derive(Clone, Debug)]
217
pub struct ChangeView {
218
    pub hash: String,
219
    pub short: String,
220
    pub title: String,
221
    pub body: String,
222
    pub author: AuthorView,
223
    pub when_ms: u64,
224
    pub deps: Vec<String>,
225
    pub head: bool,
226
    pub resolution: bool,
227
    pub signature: SigView,
228
    /// Bookmarks and tags whose state has this change as a head.
229
    pub labels: Vec<Label>,
230
}
231
232
#[derive(Clone, Debug, PartialEq, Eq)]
233
pub struct Label {
234
    pub name: String,
235
    pub kind: RefKind,
236
}
237
238
pub fn split_message(message: &str) -> (String, String) {
239
    let mut lines = message.lines();
240
    let title = lines.next().unwrap_or("").trim().to_string();
241
    let body = lines.collect::<Vec<_>>().join("\n").trim().to_string();
242
    (title, body)
243
}
244
245
/// Every bookmark and tag head, for labelling rows.
246
pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> {
247
    let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new();
248
    for b in repo.bookmarks()? {
249
        for h in b.heads {
250
            out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark });
251
        }
252
    }
253
    for t in repo.tags()? {
254
        for h in t.heads {
255
            out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag });
256
        }
257
    }
258
    Ok(out)
259
}
260
261
pub fn change_view_pub(
262
    repo: &Repo,
263
    hash: &ChangeHash,
264
    meta: &oxy_core::state::ChangeMeta,
265
    head: bool,
266
    labels: &HashMap<ChangeHash, Vec<Label>>,
267
) -> ChangeView {
268
    change_view(repo, hash, meta, head, labels)
269
}
270
271
fn change_view(
272
    repo: &Repo,
273
    hash: &ChangeHash,
274
    meta: &oxy_core::state::ChangeMeta,
275
    head: bool,
276
    labels: &HashMap<ChangeHash, Vec<Label>>,
277
) -> ChangeView {
278
    let (title, body) = split_message(&meta.message);
279
    ChangeView {
280
        hash: hash.to_hex(),
281
        short: hash.short(12),
282
        title,
283
        body,
284
        author: author(repo, &meta.author, &meta.message),
285
        when_ms: meta.hlc.wall_ms,
286
        deps: meta.deps.iter().map(|d| d.to_hex()).collect(),
287
        head,
288
        resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution,
289
        signature: signature(repo, hash),
290
        labels: labels.get(hash).cloned().unwrap_or_default(),
291
    }
292
}
293
294
// ---------------------------------------------------------------- history
295
296
#[derive(Clone, Debug)]
297
pub struct History {
298
    pub target: RefTarget,
299
    pub entries: Vec<ChangeView>,
300
    pub total: usize,
301
    pub offset: usize,
302
    pub has_more: bool,
303
    pub path: Option<String>,
304
}
305
306
/// A window of the history of a state, newest first.
307
pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> {
308
    let loaded = cache.load(repo, &target.heads)?;
309
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
310
    let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path {
311
        Some(p) => {
312
            let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) };
313
            loaded
314
                .state
315
                .changes()
316
                .filter(|(h, _)| {
317
                    repo.store()
318
                        .get_change(h)
319
                        .map(|c| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node))
320
                        .unwrap_or(false)
321
                })
322
                .map(|(h, m)| (*h, m.clone()))
323
                .collect()
324
        }
325
        None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(),
326
    };
327
    entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0)));
328
    let total = entries.len();
329
    let labels = head_labels(repo)?;
330
    let window: Vec<ChangeView> =
331
        entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect();
332
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) })
333
}
334
335
// ----------------------------------------------------------------- change
336
337
#[derive(Clone, Debug)]
338
pub struct ChangeDetail {
339
    pub view: ChangeView,
340
    pub dependents: Vec<ChangeView>,
341
    pub deps: Vec<ChangeView>,
342
    pub files: Vec<FileDiff>,
343
    /// Base content of each modified file, for context lines.
344
    pub bases: BTreeMap<String, Vec<u8>>,
345
    pub in_bookmarks: Vec<String>,
346
    pub in_tags: Vec<String>,
347
    pub atoms: usize,
348
    pub tree_ops: usize,
349
}
350
351
pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> {
352
    let c: Change = repo.store().get_change(hash)?;
353
    let labels = head_labels(repo)?;
354
    let heads = all_heads(repo)?;
355
    let loaded = cache.load(repo, &heads)?;
356
    let state = &loaded.state;
357
    let is_head = state.heads().contains(hash);
358
    let meta = oxy_core::state::ChangeMeta::of(&c);
359
    let view = change_view(repo, hash, &meta, is_head, &labels);
360
    let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect();
361
    let mut dependents: Vec<ChangeView> = state
362
        .changes()
363
        .filter(|(_, m)| m.deps.contains(hash))
364
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels))
365
        .collect();
366
    dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
367
    let base = cache.load(repo, &c.deps)?;
368
    let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot);
369
    let base_snapshot = &base.snapshot;
370
    let mut bases = BTreeMap::new();
371
    for f in &files {
372
        let old = f.from.as_deref().unwrap_or(&f.path);
373
        if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) {
374
            bases.insert(f.path.clone(), bytes.clone());
375
        }
376
    }
377
    let mut in_bookmarks = Vec::new();
378
    for b in repo.bookmarks()? {
379
        if cache.load(repo, &b.heads)?.state.contains(hash) {
380
            in_bookmarks.push(b.name);
381
        }
382
    }
383
    let mut in_tags = Vec::new();
384
    for t in repo.tags()? {
385
        if cache.load(repo, &t.heads)?.state.contains(hash) {
386
            in_tags.push(t.name);
387
        }
388
    }
389
    Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() })
390
}
391
392
// ------------------------------------------------------------------- tree
393
394
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
395
pub enum EntryKind {
396
    Dir,
397
    File,
398
    Symlink,
399
    Subrepo,
400
}
401
402
#[derive(Clone, Debug)]
403
pub struct Entry {
404
    pub name: String,
405
    pub path: String,
406
    pub kind: EntryKind,
407
    pub exec: bool,
408
    pub size: Option<u64>,
409
    pub conflicted: bool,
410
}
411
412
#[derive(Clone, Debug)]
413
pub struct Tree {
414
    pub target: RefTarget,
415
    pub path: String,
416
    pub entries: Vec<Entry>,
417
    /// `(name, path)` from the root down to this directory.
418
    pub crumbs: Vec<(String, String)>,
419
    pub readme: Option<Readme>,
420
}
421
422
#[derive(Clone, Debug)]
423
pub struct Readme {
424
    pub path: String,
425
    pub text: String,
426
}
427
428
pub fn crumbs(path: &str) -> Vec<(String, String)> {
429
    let mut out = Vec::new();
430
    let mut so_far = String::new();
431
    for part in path.split('/').filter(|p| !p.is_empty()) {
432
        if !so_far.is_empty() {
433
            so_far.push('/');
434
        }
435
        so_far.push_str(part);
436
        out.push((part.to_string(), so_far.clone()));
437
    }
438
    out
439
}
440
441
fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry {
442
    let kind = match f.kind {
443
        NodeKind::Dir => EntryKind::Dir,
444
        NodeKind::File => EntryKind::File,
445
        NodeKind::Symlink => EntryKind::Symlink,
446
        NodeKind::Subrepo => EntryKind::Subrepo,
447
    };
448
    let size = match &f.content {
449
        FileContent::Text { bytes, .. } => Some(bytes.len() as u64),
450
        _ => None,
451
    };
452
    Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() }
453
}
454
455
/// The entries directly under `dir` (`""` for the root).
456
pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> {
457
    let loaded = cache.load(repo, &target.heads)?;
458
    tree_of(repo, target, &loaded.snapshot, dir)
459
}
460
461
pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> {
462
    let dir = dir.trim_matches('/');
463
    if !dir.is_empty() {
464
        match snapshot.files.get(dir) {
465
            Some(f) if f.kind == NodeKind::Dir => {}
466
            _ => return Err(RepoError::NotFound),
467
        }
468
    }
469
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
470
    let mut entries: Vec<Entry> = snapshot
471
        .files
472
        .iter()
473
        .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/'))
474
        .map(|(p, f)| entry_of(p, &p[prefix.len()..], f))
475
        .collect();
476
    entries.sort_by(|a, b| {
477
        (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
478
    });
479
    let readme = entries
480
        .iter()
481
        .find(|e| {
482
            e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown")
483
        })
484
        .and_then(|e| match &snapshot.files.get(&e.path)?.content {
485
            FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }),
486
            _ => None,
487
        });
488
    Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme })
489
}
490
491
// ------------------------------------------------------------------- file
492
493
#[derive(Clone, Debug)]
494
pub enum FileBody {
495
    Text(String),
496
    Binary,
497
    TooLarge,
498
}
499
500
/// One row of the file page's tree sidebar (hub spec §6.6).
501
#[derive(Clone, Debug, PartialEq, Eq)]
502
pub struct SideEntry {
503
    pub name: String,
504
    pub path: String,
505
    pub depth: usize,
506
    pub dir: bool,
507
    /// A directory on the way to the file (expanded), or the file itself.
508
    pub on_path: bool,
509
    /// A "more" row standing for the rest of a long directory.
510
    pub more: bool,
511
}
512
513
/// Entries listed per directory in the sidebar before a "more" row.
514
const SIDEBAR_PER_DIR: usize = 200;
515
516
/// The tree down to `path`: each directory on the way expanded, in tree
517
/// order (directories first, then case-insensitive names).
518
pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> {
519
    sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path)
520
}
521
522
/// `sidebar` over any path map, given which values are directories.
523
pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> {
524
    let mut out = Vec::new();
525
    sidebar_dir(files, is_dir, "", path, 0, &mut out);
526
    out
527
}
528
529
fn sidebar_dir<V>(
530
    files: &BTreeMap<String, V>,
531
    is_dir: impl Fn(&V) -> bool + Copy,
532
    dir: &str,
533
    target: &str,
534
    depth: usize,
535
    out: &mut Vec<SideEntry>,
536
) {
537
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
538
    let mut children: Vec<(&str, bool)> = files
539
        .range(prefix.clone()..)
540
        .take_while(|(p, _)| p.starts_with(&prefix))
541
        .filter(|(p, _)| !p[prefix.len()..].contains('/'))
542
        .map(|(p, f)| (p.as_str(), is_dir(f)))
543
        .collect();
544
    children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));
545
    let total = children.len();
546
    for (i, (p, dir_entry)) in children.into_iter().enumerate() {
547
        let on_path = target == p || target.starts_with(&format!("{p}/"));
548
        // Past the limit, keep only the entry on the way to the file.
549
        if i >= SIDEBAR_PER_DIR && !on_path {
550
            continue;
551
        }
552
        out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false });
553
        if dir_entry && on_path && p != target {
554
            sidebar_dir(files, is_dir, p, target, depth + 1, out);
555
        }
556
    }
557
    if total > SIDEBAR_PER_DIR {
558
        out.push(SideEntry {
559
            name: format!("{} more", total - SIDEBAR_PER_DIR),
560
            path: dir.to_string(),
561
            depth,
562
            dir: true,
563
            on_path: false,
564
            more: true,
565
        });
566
    }
567
}
568
569
#[derive(Clone, Debug)]
570
pub struct FileView {
571
    pub target: RefTarget,
572
    pub path: String,
573
    pub name: String,
574
    pub crumbs: Vec<(String, String)>,
575
    pub kind: EntryKind,
576
    pub exec: bool,
577
    pub size: u64,
578
    pub body: FileBody,
579
    pub conflicted: bool,
580
    /// Raw bytes, for the `?plain=1` response and images.
581
    pub bytes: Vec<u8>,
582
    pub last_change: Option<ChangeView>,
583
    pub sidebar: Vec<SideEntry>,
584
}
585
586
pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> {
587
    let loaded = cache.load(repo, &target.heads)?;
588
    let snapshot = &loaded.snapshot;
589
    let path = path.trim_matches('/');
590
    let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) };
591
    let (kind, bytes) = match (&f.kind, &f.content) {
592
        (NodeKind::Dir, _) => return Err(RepoError::NotFound),
593
        (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()),
594
        (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()),
595
        (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()),
596
        (_, FileContent::Opaque { blobs }) => {
597
            let bytes = match blobs.first() {
598
                Some(b) => repo.read_blob(b)?,
599
                None => Vec::new(),
600
            };
601
            (EntryKind::File, bytes)
602
        }
603
        (_, FileContent::Dir) => return Err(RepoError::NotFound),
604
    };
605
    let size = bytes.len() as u64;
606
    let body = if size > render_limit {
607
        FileBody::TooLarge
608
    } else if is_binary(&bytes) {
609
        FileBody::Binary
610
    } else {
611
        FileBody::Text(String::from_utf8_lossy(&bytes).into_owned())
612
    };
613
    let labels = head_labels(repo)?;
614
    let last_change = repo
615
        .log_for_path_in(path, &target.heads)
616
        .ok()
617
        .and_then(|l| l.into_iter().next())
618
        .map(|e| change_view(repo, &e.hash, &e.change, e.is_head, &labels));
619
    let name = path.rsplit('/').next().unwrap_or(path).to_string();
620
    Ok(FileView {
621
        target,
622
        path: path.to_string(),
623
        name,
624
        crumbs: crumbs(path),
625
        kind,
626
        exec: f.mode.exec,
627
        size,
628
        body,
629
        conflicted: f.is_conflicted(),
630
        bytes,
631
        last_change,
632
        sidebar: sidebar(snapshot, path),
633
    })
634
}
635
636
pub fn is_binary(bytes: &[u8]) -> bool {
637
    let head = &bytes[..bytes.len().min(8192)];
638
    head.contains(&0)
639
        || std::str::from_utf8(head).is_err()
640
            && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20
641
}
642
643
/// Last change per entry of a directory, for tree rows (fetched lazily).
644
/// A directory's last change is the newest change touching anything
645
/// beneath it, as GitHub shows it.
646
pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> {
647
    let labels = head_labels(repo)?;
648
    let loaded = cache.load(repo, heads)?;
649
    let state = &loaded.state;
650
    let snapshot = &loaded.snapshot;
651
    // Newest change touching each node, from one pass over the log.
652
    let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new();
653
    for e in repo.log_state(heads)? {
654
        let Ok(c) = repo.store().get_change(&e.hash) else { continue };
655
        let when = e.change.hlc.wall_ms;
656
        for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) {
657
            newest.entry(node).or_insert((e.hash, when));
658
        }
659
    }
660
    let mut out = Vec::new();
661
    for p in paths {
662
        let Some(f) = snapshot.files.get(p) else { continue };
663
        let best = if f.kind == NodeKind::Dir {
664
            let prefix = format!("{p}/");
665
            snapshot
666
                .files
667
                .iter()
668
                .filter(|(q, _)| q.starts_with(&prefix))
669
                .filter_map(|(_, g)| newest.get(&g.node))
670
                .chain(newest.get(&f.node))
671
                .max_by_key(|(_, when)| *when)
672
                .copied()
673
        } else {
674
            newest.get(&f.node).copied()
675
        };
676
        if let Some((hash, _)) = best {
677
            if let Some(m) = state.get(&hash) {
678
                out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels)));
679
            }
680
        }
681
    }
682
    Ok(out)
683
}
684
685
// ------------------------------------------------------------------ blame
686
687
#[derive(Clone, Debug)]
688
pub struct Blame {
689
    pub file: FileView,
690
    pub lines: Vec<BlameLine>,
691
    /// For each blamed change, the state address of its dependencies:
692
    /// the state its author built on (None without dependencies).
693
    pub before: HashMap<ChangeHash, Option<String>>,
694
}
695
696
pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> {
697
    let heads = target.heads.clone();
698
    let file = file(repo, cache, target, path, render_limit)?;
699
    let lines = repo.blame_in(path, &heads)?;
700
    let mut before = HashMap::new();
701
    for l in &lines {
702
        before.entry(l.hash).or_insert_with(|| repo.store().get_change(&l.hash).ok().and_then(|c| state_spec(&c.deps)));
703
    }
704
    Ok(Blame { file, lines, before })
705
}
706
707
// -------------------------------------------------------------- overview
708
709
#[derive(Clone, Debug)]
710
pub struct BookmarkView {
711
    pub name: String,
712
    pub heads: Vec<String>,
713
    pub changes: usize,
714
    pub default: bool,
715
    pub conflicted: bool,
716
    pub latest_ms: u64,
717
}
718
719
#[derive(Clone, Debug)]
720
pub struct TagView {
721
    pub name: String,
722
    pub heads: Vec<String>,
723
    pub message: String,
724
    pub signer: Option<String>,
725
}
726
727
#[derive(Clone, Debug)]
728
pub struct Overview {
729
    pub tree: Tree,
730
    pub changes: usize,
731
    pub heads: usize,
732
    pub bookmarks: Vec<BookmarkView>,
733
    pub tags: Vec<TagView>,
734
    pub latest: Option<ChangeView>,
735
    pub conflicted: bool,
736
    pub license: Option<String>,
737
    pub policy: PolicyBadge,
738
    pub contributors: Vec<Contributor>,
739
    pub languages: Vec<LanguageShare>,
740
}
741
742
/// Someone who authored changes in a state (hub spec §6.4).
743
#[derive(Clone, Debug, PartialEq, Eq)]
744
pub struct Contributor {
745
    pub name: String,
746
    /// The identity key (hex), empty for authors imported from Git.
747
    pub key: String,
748
    pub changes: usize,
749
    /// The hub account the key is linked to, filled by the web layer.
750
    pub account: Option<String>,
751
}
752
753
/// One language's share of a state's code, by bytes.
754
#[derive(Clone, Debug, PartialEq)]
755
pub struct LanguageShare {
756
    pub name: String,
757
    pub bytes: u64,
758
    pub percent: f64,
759
    pub colour: String,
760
}
761
762
/// Authors of the changes of a state, most changes first.
763
pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> {
764
    let mut by: HashMap<String, Contributor> = HashMap::new();
765
    for (_, meta) in state.changes() {
766
        let a = author(repo, &meta.author, &meta.message);
767
        let id = if a.key.is_empty() { format!("git:{}", a.email.to_lowercase()) } else { a.key.clone() };
768
        // Unsigned changes with no Git author carry no name at all.
769
        let name =
770
            if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() };
771
        by.entry(id).or_insert_with(|| Contributor { name, key: a.key.clone(), changes: 0, account: None }).changes += 1;
772
    }
773
    let mut out: Vec<Contributor> = by.into_values().collect();
774
    out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
775
    out
776
}
777
778
/// The language of a path for the languages bar: an extension table for
779
/// what syntect lacks, then syntect; `None` for prose, data, lock files and
780
/// vendored or generated paths, which Linguist leaves out too.
781
pub fn language_of(path: &str) -> Option<&'static str> {
782
    let lower = path.to_ascii_lowercase();
783
    let name = lower.rsplit('/').next().unwrap_or(&lower);
784
    let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"];
785
    if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) {
786
        return None;
787
    }
788
    if name.ends_with(".lock")
789
        || name == "package-lock.json"
790
        || name.ends_with(".min.js")
791
        || name.ends_with(".min.css")
792
        || name.ends_with(".d.ts")
793
    {
794
        return None;
795
    }
796
    let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
797
    let by_ext = match ext {
798
        "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"),
799
        "toml" => Some("TOML"),
800
        "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"),
801
        "kdl" => Some("KDL"),
802
        "sh" | "bash" | "zsh" => Some("Shell"),
803
        "h" => Some("C"),
804
        "hpp" | "hh" | "cc" | "cxx" => Some("C++"),
805
        "vue" => Some("Vue"),
806
        "svelte" => Some("Svelte"),
807
        "zig" => Some("Zig"),
808
        "nix" => Some("Nix"),
809
        "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None,
810
        _ => None,
811
    };
812
    if by_ext.is_some() {
813
        return by_ext;
814
    }
815
    let lang = crate::render::highlight::language(path)?;
816
    Some(match lang {
817
        "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell",
818
        "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None,
819
        l => l,
820
    })
821
}
822
823
/// Linguist's colours for common languages; a stable colour otherwise.
824
pub fn language_colour(name: &str) -> String {
825
    let known = match name {
826
        "Rust" => "#dea584",
827
        "Python" => "#3572a5",
828
        "Shell" => "#89e051",
829
        "Makefile" => "#427819",
830
        "C" => "#555555",
831
        "C++" => "#f34b7d",
832
        "C#" => "#178600",
833
        "Assembly" => "#6e4c13",
834
        "JavaScript" => "#f1e05a",
835
        "TypeScript" => "#3178c6",
836
        "HTML" => "#e34c26",
837
        "CSS" => "#663399",
838
        "Go" => "#00add8",
839
        "Java" => "#b07219",
840
        "TOML" => "#9c4221",
841
        "YAML" => "#cb171e",
842
        "SQL" => "#e38c00",
843
        "Lua" => "#000080",
844
        "Ruby" => "#701516",
845
        "PHP" => "#4f5d95",
846
        "Haskell" => "#5e5086",
847
        "KDL" => "#ffb3b3",
848
        "Dockerfile" => "#384d54",
849
        "Vue" => "#41b883",
850
        "Zig" => "#ec915c",
851
        "Nix" => "#7e7eff",
852
        _ => "",
853
    };
854
    if !known.is_empty() {
855
        return known.to_string();
856
    }
857
    let h = blake3::hash(name.as_bytes());
858
    let b = h.as_bytes();
859
    format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2)
860
}
861
862
/// Languages of a state's files by bytes, largest first; under 1% folds into "Other".
863
pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> {
864
    let mut by: HashMap<&'static str, u64> = HashMap::new();
865
    for (path, f) in &snapshot.files {
866
        if let FileContent::Text { bytes, .. } = &f.content {
867
            if let Some(l) = language_of(path) {
868
                *by.entry(l).or_default() += bytes.len() as u64;
869
            }
870
        }
871
    }
872
    let total: u64 = by.values().sum();
873
    if total == 0 {
874
        return vec![];
875
    }
876
    let mut list: Vec<(&str, u64)> = by.into_iter().collect();
877
    list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
878
    let mut out: Vec<LanguageShare> = Vec::new();
879
    let mut other = 0u64;
880
    for (name, bytes) in list {
881
        if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 {
882
            other += bytes;
883
        } else {
884
            out.push(LanguageShare {
885
                name: name.to_string(),
886
                bytes,
887
                percent: bytes as f64 * 100.0 / total as f64,
888
                colour: language_colour(name),
889
            });
890
        }
891
    }
892
    if other > 0 {
893
        out.push(LanguageShare {
894
            name: "Other".into(),
895
            bytes: other,
896
            percent: other as f64 * 100.0 / total as f64,
897
            colour: "#8592ad".into(),
898
        });
899
    }
900
    out
901
}
902
903
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
904
pub enum PolicyBadge {
905
    None,
906
    Active,
907
    Expired,
908
}
909
910
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
911
    let mut out = Vec::new();
912
    for b in repo.bookmarks()? {
913
        let loaded = cache.load(repo, &b.heads)?;
914
        let state = &loaded.state;
915
        let latest_ms = state.changes().map(|(_, m)| m.hlc.wall_ms).max().unwrap_or(0);
916
        let conflicted = loaded.snapshot.is_conflicted();
917
        out.push(BookmarkView {
918
            name: b.name.clone(),
919
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
920
            changes: state.len(),
921
            default: b.name == default,
922
            conflicted,
923
            latest_ms,
924
        });
925
    }
926
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
927
    Ok(out)
928
}
929
930
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
931
    let mut out: Vec<TagView> = repo
932
        .tags()?
933
        .into_iter()
934
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
935
        .collect();
936
    out.sort_by(|a, b| b.name.cmp(&a.name));
937
    Ok(out)
938
}
939
940
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
941
    match repo.current_policy() {
942
        Ok(Some((_, sp))) => {
943
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
944
                PolicyBadge::Expired
945
            } else {
946
                PolicyBadge::Active
947
            }
948
        }
949
        _ => PolicyBadge::None,
950
    }
951
}
952
953
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str) -> Result<Overview> {
954
    let target = match resolve(repo, cache, default_bookmark) {
955
        Ok(t) => t,
956
        Err(_) => RefTarget { label: default_bookmark.into(), kind: RefKind::Bookmark, heads: vec![] },
957
    };
958
    let heads = target.heads.len();
959
    // One load of the default state serves the counts, the latest change
960
    // and the tree (hub spec §16.3).
961
    let loaded = cache.load(repo, &target.heads)?;
962
    let state = &loaded.state;
963
    let snapshot = &loaded.snapshot;
964
    let changes = state.len();
965
    let conflicted = snapshot.is_conflicted();
966
    let labels = head_labels(repo)?;
967
    let latest = state
968
        .changes()
969
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
970
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
971
    let tree = tree_of(repo, target, snapshot, "")?;
972
    let license = tree
973
        .entries
974
        .iter()
975
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
976
        .map(|e| e.path.clone());
977
    Ok(Overview {
978
        tree,
979
        changes,
980
        heads,
981
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
982
        tags: tags(repo)?,
983
        latest,
984
        conflicted,
985
        license,
986
        policy: policy_badge(repo),
987
        contributors: contributors(repo, state),
988
        languages: languages(snapshot),
989
    })
990
}
991
992
// -------------------------------------------------------------- compare
993
994
#[derive(Clone, Debug)]
995
pub struct Compare {
996
    pub base: RefTarget,
997
    pub head: RefTarget,
998
    /// Changes in `head`'s state not in `base`'s.
999
    pub added: Vec<ChangeView>,
1000
    /// Changes in `base`'s state not in `head`'s.
1001
    pub missing: usize,
1002
    pub files: Vec<FileDiff>,
1003
    pub bases: BTreeMap<String, Vec<u8>>,
1004
}
1005
1006
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
1007
    let base_loaded = cache.load(repo, &base.heads)?;
1008
    let head_loaded = cache.load(repo, &head.heads)?;
1009
    let base_state = &base_loaded.state;
1010
    let head_state = &head_loaded.state;
1011
    let labels = head_labels(repo)?;
1012
    let mut added: Vec<ChangeView> = head_state
1013
        .changes()
1014
        .filter(|(h, _)| !base_state.contains(h))
1015
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
1016
        .collect();
1017
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
1018
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
1019
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
1020
    Ok(Compare { base, head, added, missing, files, bases })
1021
}
1022
1023
// ------------------------------------------------------------ conflicts
1024
1025
#[derive(Clone, Debug)]
1026
pub struct ConflictView {
1027
    pub bookmark: String,
1028
    pub path: String,
1029
    pub kind: String,
1030
    /// The file rendered with `oxy` conflict markers, when a text file.
1031
    pub marked: Option<String>,
1032
    pub contributors: Vec<ChangeView>,
1033
}
1034
1035
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
1036
    let mut out = Vec::new();
1037
    for b in repo.bookmarks()? {
1038
        let loaded = cache.load(repo, &b.heads)?;
1039
        out.extend(conflicts_in(repo, &loaded, &b.name));
1040
    }
1041
    Ok(out)
1042
}
1043
1044
/// The conflicts of one loaded state, labelled with `bookmark`.
1045
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
1046
    let labels = head_labels(repo).unwrap_or_default();
1047
    let mut out = Vec::new();
1048
    {
1049
        let b_name = bookmark.to_string();
1050
        let state = &loaded.state;
1051
        let snapshot = &loaded.snapshot;
1052
        for c in &snapshot.tree.conflicts {
1053
            let (path, kind) = describe_tree_conflict(snapshot, c);
1054
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
1055
        }
1056
        for (path, f) in &snapshot.files {
1057
            if !f.is_conflicted() {
1058
                continue;
1059
            }
1060
            let (kind, marked, contributors) = match &f.content {
1061
                FileContent::Text { .. } => {
1062
                    let (bytes, _) = state.render_file(&f.node);
1063
                    let regions = state.conflict_regions(&f.node);
1064
                    let contributors: Vec<ChangeView> = regions
1065
                        .contributors
1066
                        .iter()
1067
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
1068
                        .collect();
1069
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
1070
                }
1071
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
1072
                FileContent::Dir => continue,
1073
            };
1074
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
1075
        }
1076
    }
1077
    out
1078
}
1079
1080
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
1081
    let by_node = snapshot.tree.by_node();
1082
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
1083
    match c {
1084
        TreeConflict::Name { name, nodes, .. } => (name.clone(), format!("name: {} entries want this name", nodes.len())),
1085
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
1086
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
1087
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
1088
        other => (String::new(), format!("{other:?}")),
1089
    }
1090
}
1091
1092
// ------------------------------------------------------------------ trust
1093
1094
#[derive(Clone, Debug)]
1095
pub struct KeyView {
1096
    pub key: String,
1097
    pub short: String,
1098
    pub name: String,
1099
    pub email: String,
1100
}
1101
1102
#[derive(Clone, Debug)]
1103
pub struct RuleView {
1104
    pub pattern: String,
1105
    pub keys: Vec<KeyView>,
1106
    pub threshold: u32,
1107
    pub require: String,
1108
    pub allow_conflicts: bool,
1109
}
1110
1111
#[derive(Clone, Debug)]
1112
pub struct PolicyView {
1113
    pub serial: u64,
1114
    pub expires_ms: u64,
1115
    pub expired: bool,
1116
    pub roots: Vec<KeyView>,
1117
    pub root_threshold: u32,
1118
    pub rules: Vec<RuleView>,
1119
    pub revoked: Vec<KeyView>,
1120
    pub signatures: usize,
1121
    pub history: usize,
1122
}
1123
1124
#[derive(Clone, Debug, Default)]
1125
pub struct Verification {
1126
    pub total: usize,
1127
    pub signed: usize,
1128
    pub sealed: usize,
1129
    pub unsigned: usize,
1130
    pub revoked: usize,
1131
    pub invalid: Vec<(String, String)>,
1132
}
1133
1134
#[derive(Clone, Debug)]
1135
pub struct Trust {
1136
    pub policy: Option<PolicyView>,
1137
    pub verification: Verification,
1138
    pub hub_key: String,
1139
    pub hub_delegated_by: Vec<KeyView>,
1140
}
1141
1142
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
1143
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
1144
    match found {
1145
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
1146
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
1147
    }
1148
}
1149
1150
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
1151
    let heads = all_heads(repo)?;
1152
    let loaded = cache.load(repo, &heads)?;
1153
    let state = &loaded.state;
1154
    let mut v = Verification::default();
1155
    for (h, _) in state.changes() {
1156
        v.total += 1;
1157
        match signature(repo, h) {
1158
            SigView::Unsigned => v.unsigned += 1,
1159
            SigView::Valid { sealed, revoked, .. } => {
1160
                if revoked {
1161
                    v.revoked += 1;
1162
                }
1163
                if sealed {
1164
                    v.sealed += 1
1165
                } else {
1166
                    v.signed += 1
1167
                }
1168
            }
1169
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1170
        }
1171
    }
1172
    Ok(v)
1173
}
1174
1175
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
1176
    let policy = match repo.current_policy()? {
1177
        Some((_, sp)) => {
1178
            let p = &sp.policy;
1179
            let ids = &p.identities;
1180
            let require = |r: &oxy_core::policy::Require| match r {
1181
                oxy_core::policy::Require::Signed => "signed",
1182
                oxy_core::policy::Require::Sealed => "sealed",
1183
                oxy_core::policy::Require::Any => "any",
1184
            };
1185
            Some(PolicyView {
1186
                serial: p.serial,
1187
                expires_ms: p.expires,
1188
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
1189
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
1190
                root_threshold: p.root_threshold,
1191
                rules: p
1192
                    .rules
1193
                    .iter()
1194
                    .map(|r| RuleView {
1195
                        pattern: r.pattern.clone(),
1196
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
1197
                        threshold: r.threshold,
1198
                        require: require(&r.require).into(),
1199
                        allow_conflicts: r.allow_conflicts,
1200
                    })
1201
                    .collect(),
1202
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
1203
                signatures: sp.sigs.len(),
1204
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1205
            })
1206
        }
1207
        None => None,
1208
    };
1209
    // Who has delegated to the hub: every identity in the policy or store
1210
    // that lists the hub key.
1211
    let mut delegated = Vec::new();
1212
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
1213
        for i in &p.identities {
1214
            if i.delegates.contains(hub_key) {
1215
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
1216
            }
1217
        }
1218
    }
1219
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
1220
}
1221
1222
#[cfg(test)]
1223
mod language_tests {
1224
    use super::*;
1225
1226
    #[test]
1227
    fn languages_are_detected_and_prose_is_left_out() {
1228
        assert_eq!(language_of("src/main.rs"), Some("Rust"));
1229
        assert_eq!(language_of("boot/start.s"), Some("Assembly"));
1230
        assert_eq!(language_of("build.sh"), Some("Shell"));
1231
        assert_eq!(language_of("Makefile"), Some("Makefile"));
1232
        assert_eq!(language_of("Cargo.toml"), Some("TOML"));
1233
        assert_eq!(language_of("README.md"), None);
1234
        assert_eq!(language_of("Cargo.lock"), None);
1235
        assert_eq!(language_of("web/node_modules/x/index.js"), None);
1236
        assert_eq!(language_of("vendor/lib.c"), None);
1237
        assert_eq!(language_colour("Rust"), "#dea584");
1238
        assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable");
1239
    }
1240
}
1241
1242
#[cfg(test)]
1243
mod tests {
1244
    use super::*;
1245
1246
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
1247
        let mut m = BTreeMap::new();
1248
        for p in paths {
1249
            let mut end = 0;
1250
            let parts: Vec<&str> = p.split('/').collect();
1251
            for (i, part) in parts.iter().enumerate() {
1252
                end += part.len();
1253
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1254
                end += 1;
1255
            }
1256
        }
1257
        m
1258
    }
1259
1260
    #[test]
1261
    fn sidebar_expands_the_path_only() {
1262
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
1263
        let rows: Vec<(String, usize, bool, bool)> =
1264
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
1265
        let want = [
1266
            ("docs", 0, true, false),
1267
            ("src", 0, true, true),
1268
            ("src/lib", 1, true, true),
1269
            ("src/lib/a.rs", 2, false, false),
1270
            ("src/lib/b.rs", 2, false, true),
1271
            ("src/main.rs", 1, false, false),
1272
            ("README.md", 0, false, false),
1273
            ("Zeta.txt", 0, false, false),
1274
        ];
1275
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
1276
    }
1277
1278
    #[test]
1279
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1280
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
1281
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1282
        let files = tree(&refs);
1283
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1284
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
1285
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
1286
        assert!(listed.last().unwrap().on_path);
1287
        let more = rows.iter().find(|e| e.more).unwrap();
1288
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
1289
    }
1290
1291
    #[test]
1292
    fn state_addresses_are_sorted_and_bounded() {
1293
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
1294
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
1295
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
1296
        assert_eq!(state_spec(&[]), None);
1297
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
1298
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
1299
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
1300
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
1301
    }
1302
}