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