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