OXYGENHUB
# 39442b000e6b oxygenhub / crates / hub / src / repos / view.rs
40.1 KiB · Rust · last changed Keep bookmark briefs across restarts, and log slow requests 24 days ago source blame history raw
1
//! Page-ready views of a repository, computed from `oxy-core` alone (hub
2
//! spec §1.4). Nothing here knows about HTTP or templates; every function
3
//! takes an open `Repo` and returns plain data.
4
5
use super::{RepoError, StateCache};
6
use oxy_core::hash::{ChangeHash, KeyId};
7
use oxy_core::objects::{Change, NodeKind};
8
use oxy_core::repo::{BlameLine, FileDiff, Repo, SignatureStatus};
9
use oxy_core::state::{FileContent, Snapshot};
10
use oxy_core::tree::TreeConflict;
11
use std::collections::{BTreeMap, BTreeSet, HashMap};
12
13
type Result<T> = std::result::Result<T, RepoError>;
14
15
fn fail(msg: impl Into<String>) -> RepoError {
16
    RepoError::Oxy(oxy_core::repo::RepoError::Msg(msg.into()))
17
}
18
19
// ------------------------------------------------------------------ refs
20
21
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22
pub enum RefKind {
23
    Bookmark,
24
    Tag,
25
    Change,
26
}
27
28
/// What a `{ref}` path segment resolved to.
29
#[derive(Clone, Debug)]
30
pub struct RefTarget {
31
    /// The name as given (bookmark, tag) or the full hash.
32
    pub label: String,
33
    pub kind: RefKind,
34
    pub heads: Vec<ChangeHash>,
35
}
36
37
/// Most heads a state address or a "before this change" link carries.
38
pub const MAX_STATE_HEADS: usize = 32;
39
40
impl RefTarget {
41
    /// The label for a ref bar: the name, or `# abc123…` for a change,
42
    /// with `+N` for the further heads of a state.
43
    pub fn short_label(&self) -> String {
44
        match self.kind {
45
            RefKind::Change => {
46
                let mut parts = self.label.split('+');
47
                let first: String = parts.next().unwrap_or("").chars().take(12).collect();
48
                match parts.count() {
49
                    0 => first,
50
                    n => format!("{first} +{n}"),
51
                }
52
            }
53
            _ => self.label.clone(),
54
        }
55
    }
56
57
    /// The `{ref}` that names this target's state for good: its heads
58
    /// joined with `+` (hub spec §6.6). None for an empty state.
59
    pub fn permalink(&self) -> Option<String> {
60
        state_spec(&self.heads)
61
    }
62
}
63
64
/// Heads as a state address, sorted so one state has one address.
65
pub fn state_spec(heads: &[ChangeHash]) -> Option<String> {
66
    if heads.is_empty() || heads.len() > MAX_STATE_HEADS {
67
        return None;
68
    }
69
    let mut hex: Vec<String> = heads.iter().map(|h| h.to_hex()).collect();
70
    hex.sort();
71
    hex.dedup();
72
    Some(hex.join("+"))
73
}
74
75
/// Resolve a bookmark name, a tag name, a change hash prefix, or a state
76
/// (full hashes joined with `+`).
77
pub fn resolve(repo: &Repo, cache: &StateCache, spec: &str) -> Result<RefTarget> {
78
    if spec.contains('+') {
79
        let parts: Vec<&str> = spec.split('+').collect();
80
        if parts.len() > MAX_STATE_HEADS {
81
            return Err(fail(format!("a state address has at most {MAX_STATE_HEADS} heads")));
82
        }
83
        let mut heads = Vec::with_capacity(parts.len());
84
        for p in parts {
85
            match ChangeHash::from_hex(p) {
86
                Some(h) if p.len() == 64 && repo.store().has(&h) => heads.push(h),
87
                _ => return Err(fail(format!("{p:?} is not a change of this repository"))),
88
            }
89
        }
90
        heads.sort();
91
        heads.dedup();
92
        let label = state_spec(&heads).unwrap_or_default();
93
        return Ok(RefTarget { label, kind: RefKind::Change, heads });
94
    }
95
    let view = repo.view()?;
96
    if let Some(heads) = view.bookmarks.get(spec).map(|st| repo.store().get_state(st).map(|s| s.heads)).transpose()? {
97
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Bookmark, heads });
98
    }
99
    if let Some(heads) = repo.tag_heads(spec)? {
100
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Tag, heads });
101
    }
102
    let hash = resolve_change(repo, cache, spec)?;
103
    Ok(RefTarget { label: hash.to_hex(), kind: RefKind::Change, heads: vec![hash] })
104
}
105
106
/// A change by full hash or unique hex prefix, searched over every
107
/// bookmark's state.
108
pub fn resolve_change(repo: &Repo, cache: &StateCache, spec: &str) -> Result<ChangeHash> {
109
    let spec = spec.trim_start_matches('#');
110
    if spec.len() < 4 || !spec.chars().all(|c| c.is_ascii_hexdigit()) {
111
        return Err(fail(format!("{spec:?} is not a change")));
112
    }
113
    if let Some(h) = ChangeHash::from_hex(spec) {
114
        if repo.store().has(&h) {
115
            return Ok(h);
116
        }
117
    }
118
    let heads = all_heads(repo)?;
119
    let loaded = cache.load(repo, &heads)?;
120
    let matches: Vec<ChangeHash> = loaded.state.changes().map(|(h, _)| *h).filter(|h| h.starts_with_hex(spec)).collect();
121
    match matches.len() {
122
        1 => Ok(matches[0]),
123
        0 => Err(fail(format!("no change matches {spec:?}"))),
124
        _ => Err(fail(format!("{spec:?} is ambiguous"))),
125
    }
126
}
127
128
/// The heads of every bookmark, deduplicated.
129
pub fn all_heads(repo: &Repo) -> Result<Vec<ChangeHash>> {
130
    let mut set = BTreeSet::new();
131
    for b in repo.bookmarks()? {
132
        set.extend(b.heads);
133
    }
134
    Ok(set.into_iter().collect())
135
}
136
137
// ---------------------------------------------------------------- authors
138
139
#[derive(Clone, Debug, PartialEq, Eq)]
140
pub struct AuthorView {
141
    pub name: String,
142
    pub email: String,
143
    pub key: String,
144
    /// True when the key is not an identity the store knows.
145
    pub unknown: bool,
146
    /// The hub account the key is linked to, filled by the web layer.
147
    pub account: Option<String>,
148
}
149
150
pub fn author(repo: &Repo, key: &KeyId, message: &str) -> AuthorView {
151
    if key.is_zero() {
152
        // Imported from Git: the trailer carries the author.
153
        let line = message.lines().rev().find_map(|l| l.strip_prefix("Git-Author: ")).unwrap_or("unknown");
154
        let (name, email) = match line.split_once('<') {
155
            Some((n, e)) => (n.trim().to_string(), e.trim_end_matches('>').trim().to_string()),
156
            None => (line.trim().to_string(), String::new()),
157
        };
158
        return AuthorView { name, email, key: String::new(), unknown: true, account: None };
159
    }
160
    match repo.store().get_identity(key) {
161
        Ok(id) => AuthorView { name: id.name, email: id.email, key: key.to_hex(), unknown: false, account: None },
162
        Err(_) => AuthorView { name: key.short(12), email: String::new(), key: key.to_hex(), unknown: true, account: None },
163
    }
164
}
165
166
// ---------------------------------------------------------------- changes
167
168
#[derive(Clone, Debug, PartialEq, Eq)]
169
pub enum SigView {
170
    Unsigned,
171
    Valid { key: String, name: String, sealed: bool, revoked: bool },
172
    Invalid(String),
173
}
174
175
impl SigView {
176
    pub fn glyph(&self) -> &'static str {
177
        match self {
178
            SigView::Unsigned => "○",
179
            SigView::Valid { revoked: true, .. } => "⊘",
180
            SigView::Valid { sealed: true, .. } => "◈",
181
            SigView::Valid { .. } => "✔",
182
            SigView::Invalid(_) => "✘",
183
        }
184
    }
185
186
    pub fn class(&self) -> &'static str {
187
        match self {
188
            SigView::Unsigned => "sig-unsigned",
189
            SigView::Valid { revoked: true, .. } => "sig-revoked",
190
            SigView::Valid { .. } => "sig-valid",
191
            SigView::Invalid(_) => "sig-invalid",
192
        }
193
    }
194
195
    pub fn title(&self) -> String {
196
        match self {
197
            SigView::Unsigned => "unsigned".into(),
198
            SigView::Valid { name, sealed: true, revoked: false, .. } => format!("sealed by {name}"),
199
            SigView::Valid { name, revoked: true, .. } => format!("signed by {name}, key revoked"),
200
            SigView::Valid { name, .. } => format!("signed by {name}"),
201
            SigView::Invalid(why) => format!("INVALID: {why}"),
202
        }
203
    }
204
}
205
206
pub fn signature(repo: &Repo, hash: &ChangeHash) -> SigView {
207
    match repo.verify_change(hash) {
208
        Ok(SignatureStatus::Unsigned) => SigView::Unsigned,
209
        Ok(SignatureStatus::Valid { key, name, sealed, revoked, .. }) => SigView::Valid { key: key.to_hex(), name, sealed, revoked },
210
        Ok(SignatureStatus::Invalid(why)) => SigView::Invalid(why),
211
        Err(e) => SigView::Invalid(e.to_string()),
212
    }
213
}
214
215
/// One change as history rows and change pages show it.
216
#[derive(Clone, Debug)]
217
pub struct ChangeView {
218
    pub hash: String,
219
    pub short: String,
220
    pub title: String,
221
    pub body: String,
222
    pub author: AuthorView,
223
    pub when_ms: u64,
224
    pub deps: Vec<String>,
225
    pub head: bool,
226
    pub resolution: bool,
227
    pub signature: SigView,
228
    /// Bookmarks and tags whose state has this change as a head.
229
    pub labels: Vec<Label>,
230
}
231
232
#[derive(Clone, Debug, PartialEq, Eq)]
233
pub struct Label {
234
    pub name: String,
235
    pub kind: RefKind,
236
}
237
238
pub fn split_message(message: &str) -> (String, String) {
239
    let mut lines = message.lines();
240
    let title = lines.next().unwrap_or("").trim().to_string();
241
    let body = lines.collect::<Vec<_>>().join("\n").trim().to_string();
242
    (title, body)
243
}
244
245
/// Every bookmark and tag head, for labelling rows.
246
pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> {
247
    let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new();
248
    for b in repo.bookmarks()? {
249
        for h in b.heads {
250
            out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark });
251
        }
252
    }
253
    for t in repo.tags()? {
254
        for h in t.heads {
255
            out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag });
256
        }
257
    }
258
    Ok(out)
259
}
260
261
pub fn change_view_pub(
262
    repo: &Repo,
263
    hash: &ChangeHash,
264
    meta: &oxy_core::state::ChangeMeta,
265
    head: bool,
266
    labels: &HashMap<ChangeHash, Vec<Label>>,
267
) -> ChangeView {
268
    change_view(repo, hash, meta, head, labels)
269
}
270
271
fn change_view(
272
    repo: &Repo,
273
    hash: &ChangeHash,
274
    meta: &oxy_core::state::ChangeMeta,
275
    head: bool,
276
    labels: &HashMap<ChangeHash, Vec<Label>>,
277
) -> ChangeView {
278
    let (title, body) = split_message(&meta.message);
279
    ChangeView {
280
        hash: hash.to_hex(),
281
        short: hash.short(12),
282
        title,
283
        body,
284
        author: author(repo, &meta.author, &meta.message),
285
        when_ms: meta.hlc.wall_ms,
286
        deps: meta.deps.iter().map(|d| d.to_hex()).collect(),
287
        head,
288
        resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution,
289
        signature: signature(repo, hash),
290
        labels: labels.get(hash).cloned().unwrap_or_default(),
291
    }
292
}
293
294
// ---------------------------------------------------------------- history
295
296
#[derive(Clone, Debug)]
297
pub struct History {
298
    pub target: RefTarget,
299
    pub entries: Vec<ChangeView>,
300
    pub total: usize,
301
    pub offset: usize,
302
    pub has_more: bool,
303
    pub path: Option<String>,
304
}
305
306
/// A window of the history of a state, newest first.
307
pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> {
308
    let loaded = cache.load(repo, &target.heads)?;
309
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
310
    let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path {
311
        Some(p) => {
312
            let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) };
313
            loaded
314
                .state
315
                .changes()
316
                .filter(|(h, _)| {
317
                    repo.store()
318
                        .get_change(h)
319
                        .map(|c| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node))
320
                        .unwrap_or(false)
321
                })
322
                .map(|(h, m)| (*h, m.clone()))
323
                .collect()
324
        }
325
        None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(),
326
    };
327
    entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0)));
328
    let total = entries.len();
329
    let labels = head_labels(repo)?;
330
    let window: Vec<ChangeView> =
331
        entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect();
332
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) })
333
}
334
335
// ----------------------------------------------------------------- change
336
337
#[derive(Clone, Debug)]
338
pub struct ChangeDetail {
339
    pub view: ChangeView,
340
    pub dependents: Vec<ChangeView>,
341
    pub deps: Vec<ChangeView>,
342
    pub files: Vec<FileDiff>,
343
    /// Base content of each modified file, for context lines.
344
    pub bases: BTreeMap<String, Vec<u8>>,
345
    pub in_bookmarks: Vec<String>,
346
    pub in_tags: Vec<String>,
347
    pub atoms: usize,
348
    pub tree_ops: usize,
349
}
350
351
pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> {
352
    let c: Change = repo.store().get_change(hash)?;
353
    let labels = head_labels(repo)?;
354
    let heads = all_heads(repo)?;
355
    let loaded = cache.load(repo, &heads)?;
356
    let state = &loaded.state;
357
    let is_head = state.heads().contains(hash);
358
    let meta = oxy_core::state::ChangeMeta::of(&c);
359
    let view = change_view(repo, hash, &meta, is_head, &labels);
360
    let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect();
361
    let mut dependents: Vec<ChangeView> = state
362
        .changes()
363
        .filter(|(_, m)| m.deps.contains(hash))
364
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels))
365
        .collect();
366
    dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
367
    let base = cache.load(repo, &c.deps)?;
368
    let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot);
369
    let base_snapshot = &base.snapshot;
370
    let mut bases = BTreeMap::new();
371
    for f in &files {
372
        let old = f.from.as_deref().unwrap_or(&f.path);
373
        if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) {
374
            bases.insert(f.path.clone(), bytes.clone());
375
        }
376
    }
377
    let mut in_bookmarks = Vec::new();
378
    for b in repo.bookmarks()? {
379
        if cache.summary(repo, &b.heads)?.changes.contains(hash) {
380
            in_bookmarks.push(b.name);
381
        }
382
    }
383
    let mut in_tags = Vec::new();
384
    for t in repo.tags()? {
385
        if cache.summary(repo, &t.heads)?.changes.contains(hash) {
386
            in_tags.push(t.name);
387
        }
388
    }
389
    Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() })
390
}
391
392
// ------------------------------------------------------------------- tree
393
394
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
395
pub enum EntryKind {
396
    Dir,
397
    File,
398
    Symlink,
399
    Subrepo,
400
}
401
402
#[derive(Clone, Debug)]
403
pub struct Entry {
404
    pub name: String,
405
    pub path: String,
406
    pub kind: EntryKind,
407
    pub exec: bool,
408
    pub size: Option<u64>,
409
    pub conflicted: bool,
410
}
411
412
#[derive(Clone, Debug)]
413
pub struct Tree {
414
    pub target: RefTarget,
415
    pub path: String,
416
    pub entries: Vec<Entry>,
417
    /// `(name, path)` from the root down to this directory.
418
    pub crumbs: Vec<(String, String)>,
419
    pub readme: Option<Readme>,
420
}
421
422
#[derive(Clone, Debug)]
423
pub struct Readme {
424
    pub path: String,
425
    pub text: String,
426
}
427
428
pub fn crumbs(path: &str) -> Vec<(String, String)> {
429
    let mut out = Vec::new();
430
    let mut so_far = String::new();
431
    for part in path.split('/').filter(|p| !p.is_empty()) {
432
        if !so_far.is_empty() {
433
            so_far.push('/');
434
        }
435
        so_far.push_str(part);
436
        out.push((part.to_string(), so_far.clone()));
437
    }
438
    out
439
}
440
441
fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry {
442
    let kind = match f.kind {
443
        NodeKind::Dir => EntryKind::Dir,
444
        NodeKind::File => EntryKind::File,
445
        NodeKind::Symlink => EntryKind::Symlink,
446
        NodeKind::Subrepo => EntryKind::Subrepo,
447
    };
448
    let size = match &f.content {
449
        FileContent::Text { bytes, .. } => Some(bytes.len() as u64),
450
        _ => None,
451
    };
452
    Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() }
453
}
454
455
/// The entries directly under `dir` (`""` for the root).
456
pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> {
457
    let loaded = cache.load(repo, &target.heads)?;
458
    tree_of(repo, target, &loaded.snapshot, dir)
459
}
460
461
pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> {
462
    let dir = dir.trim_matches('/');
463
    if !dir.is_empty() {
464
        match snapshot.files.get(dir) {
465
            Some(f) if f.kind == NodeKind::Dir => {}
466
            _ => return Err(RepoError::NotFound),
467
        }
468
    }
469
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
470
    let mut entries: Vec<Entry> = snapshot
471
        .files
472
        .iter()
473
        .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/'))
474
        .map(|(p, f)| entry_of(p, &p[prefix.len()..], f))
475
        .collect();
476
    entries.sort_by(|a, b| {
477
        (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
478
    });
479
    let readme = entries
480
        .iter()
481
        .find(|e| {
482
            e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown")
483
        })
484
        .and_then(|e| match &snapshot.files.get(&e.path)?.content {
485
            FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }),
486
            _ => None,
487
        });
488
    Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme })
489
}
490
491
// ------------------------------------------------------------------- file
492
493
#[derive(Clone, Debug)]
494
pub enum FileBody {
495
    Text(String),
496
    Binary,
497
    TooLarge,
498
}
499
500
/// One row of the file page's tree sidebar (hub spec §6.6).
501
#[derive(Clone, Debug, PartialEq, Eq)]
502
pub struct SideEntry {
503
    pub name: String,
504
    pub path: String,
505
    pub depth: usize,
506
    pub dir: bool,
507
    /// A directory on the way to the file (expanded), or the file itself.
508
    pub on_path: bool,
509
    /// A "more" row standing for the rest of a long directory.
510
    pub more: bool,
511
}
512
513
/// Entries listed per directory in the sidebar before a "more" row.
514
const SIDEBAR_PER_DIR: usize = 200;
515
516
/// The tree down to `path`: each directory on the way expanded, in tree
517
/// order (directories first, then case-insensitive names).
518
pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> {
519
    sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path)
520
}
521
522
/// `sidebar` over any path map, given which values are directories.
523
pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> {
524
    let mut out = Vec::new();
525
    sidebar_dir(files, is_dir, "", path, 0, &mut out);
526
    out
527
}
528
529
fn sidebar_dir<V>(
530
    files: &BTreeMap<String, V>,
531
    is_dir: impl Fn(&V) -> bool + Copy,
532
    dir: &str,
533
    target: &str,
534
    depth: usize,
535
    out: &mut Vec<SideEntry>,
536
) {
537
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
538
    let mut children: Vec<(&str, bool)> = files
539
        .range(prefix.clone()..)
540
        .take_while(|(p, _)| p.starts_with(&prefix))
541
        .filter(|(p, _)| !p[prefix.len()..].contains('/'))
542
        .map(|(p, f)| (p.as_str(), is_dir(f)))
543
        .collect();
544
    children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));
545
    let total = children.len();
546
    for (i, (p, dir_entry)) in children.into_iter().enumerate() {
547
        let on_path = target == p || target.starts_with(&format!("{p}/"));
548
        // Past the limit, keep only the entry on the way to the file.
549
        if i >= SIDEBAR_PER_DIR && !on_path {
550
            continue;
551
        }
552
        out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false });
553
        if dir_entry && on_path && p != target {
554
            sidebar_dir(files, is_dir, p, target, depth + 1, out);
555
        }
556
    }
557
    if total > SIDEBAR_PER_DIR {
558
        out.push(SideEntry {
559
            name: format!("{} more", total - SIDEBAR_PER_DIR),
560
            path: dir.to_string(),
561
            depth,
562
            dir: true,
563
            on_path: false,
564
            more: true,
565
        });
566
    }
567
}
568
569
#[derive(Clone, Debug)]
570
pub struct FileView {
571
    pub target: RefTarget,
572
    pub path: String,
573
    pub name: String,
574
    pub crumbs: Vec<(String, String)>,
575
    pub kind: EntryKind,
576
    pub exec: bool,
577
    pub size: u64,
578
    pub body: FileBody,
579
    pub conflicted: bool,
580
    /// Raw bytes, for the `?plain=1` response and images.
581
    pub bytes: Vec<u8>,
582
    pub last_change: Option<ChangeView>,
583
    pub sidebar: Vec<SideEntry>,
584
}
585
586
pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> {
587
    let loaded = cache.load(repo, &target.heads)?;
588
    let snapshot = &loaded.snapshot;
589
    let path = path.trim_matches('/');
590
    let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) };
591
    let (kind, bytes) = match (&f.kind, &f.content) {
592
        (NodeKind::Dir, _) => return Err(RepoError::NotFound),
593
        (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()),
594
        (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()),
595
        (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()),
596
        (_, FileContent::Opaque { blobs }) => {
597
            let bytes = match blobs.first() {
598
                Some(b) => repo.read_blob(b)?,
599
                None => Vec::new(),
600
            };
601
            (EntryKind::File, bytes)
602
        }
603
        (_, FileContent::Dir) => return Err(RepoError::NotFound),
604
    };
605
    let size = bytes.len() as u64;
606
    let body = if size > render_limit {
607
        FileBody::TooLarge
608
    } else if is_binary(&bytes) {
609
        FileBody::Binary
610
    } else {
611
        FileBody::Text(String::from_utf8_lossy(&bytes).into_owned())
612
    };
613
    let labels = head_labels(repo)?;
614
    let last_change = repo
615
        .log_for_path_in(path, &target.heads)
616
        .ok()
617
        .and_then(|l| l.into_iter().next())
618
        .map(|e| change_view(repo, &e.hash, &e.change, e.is_head, &labels));
619
    let name = path.rsplit('/').next().unwrap_or(path).to_string();
620
    Ok(FileView {
621
        target,
622
        path: path.to_string(),
623
        name,
624
        crumbs: crumbs(path),
625
        kind,
626
        exec: f.mode.exec,
627
        size,
628
        body,
629
        conflicted: f.is_conflicted(),
630
        bytes,
631
        last_change,
632
        sidebar: sidebar(snapshot, path),
633
    })
634
}
635
636
pub fn is_binary(bytes: &[u8]) -> bool {
637
    let head = &bytes[..bytes.len().min(8192)];
638
    head.contains(&0)
639
        || std::str::from_utf8(head).is_err()
640
            && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20
641
}
642
643
/// Last change per entry of a directory, for tree rows (fetched lazily).
644
/// A directory's last change is the newest change touching anything
645
/// beneath it, as GitHub shows it.
646
pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> {
647
    let labels = head_labels(repo)?;
648
    let loaded = cache.load(repo, heads)?;
649
    let state = &loaded.state;
650
    let snapshot = &loaded.snapshot;
651
    // Newest change touching each node, from one pass over the log.
652
    let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new();
653
    for e in repo.log_state(heads)? {
654
        let Ok(c) = repo.store().get_change(&e.hash) else { continue };
655
        let when = e.change.hlc.wall_ms;
656
        for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) {
657
            newest.entry(node).or_insert((e.hash, when));
658
        }
659
    }
660
    let mut out = Vec::new();
661
    for p in paths {
662
        let Some(f) = snapshot.files.get(p) else { continue };
663
        let best = if f.kind == NodeKind::Dir {
664
            let prefix = format!("{p}/");
665
            snapshot
666
                .files
667
                .iter()
668
                .filter(|(q, _)| q.starts_with(&prefix))
669
                .filter_map(|(_, g)| newest.get(&g.node))
670
                .chain(newest.get(&f.node))
671
                .max_by_key(|(_, when)| *when)
672
                .copied()
673
        } else {
674
            newest.get(&f.node).copied()
675
        };
676
        if let Some((hash, _)) = best {
677
            if let Some(m) = state.get(&hash) {
678
                out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels)));
679
            }
680
        }
681
    }
682
    Ok(out)
683
}
684
685
// ------------------------------------------------------------------ blame
686
687
#[derive(Clone, Debug)]
688
pub struct Blame {
689
    pub file: FileView,
690
    pub lines: Vec<BlameLine>,
691
    /// For each blamed change, the state address of its dependencies:
692
    /// the state its author built on (None without dependencies).
693
    pub before: HashMap<ChangeHash, Option<String>>,
694
}
695
696
pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> {
697
    let heads = target.heads.clone();
698
    let file = file(repo, cache, target, path, render_limit)?;
699
    let lines = repo.blame_in(path, &heads)?;
700
    let mut before = HashMap::new();
701
    for l in &lines {
702
        before.entry(l.hash).or_insert_with(|| repo.store().get_change(&l.hash).ok().and_then(|c| state_spec(&c.deps)));
703
    }
704
    Ok(Blame { file, lines, before })
705
}
706
707
// -------------------------------------------------------------- overview
708
709
#[derive(Clone, Debug)]
710
pub struct BookmarkView {
711
    pub name: String,
712
    pub heads: Vec<String>,
713
    pub changes: usize,
714
    pub default: bool,
715
    pub conflicted: bool,
716
    pub latest_ms: u64,
717
}
718
719
#[derive(Clone, Debug)]
720
pub struct TagView {
721
    pub name: String,
722
    pub heads: Vec<String>,
723
    pub message: String,
724
    pub signer: Option<String>,
725
}
726
727
#[derive(Clone, Debug)]
728
pub struct Overview {
729
    pub tree: Tree,
730
    pub changes: usize,
731
    pub heads: usize,
732
    pub bookmarks: Vec<BookmarkView>,
733
    pub tags: Vec<TagView>,
734
    pub latest: Option<ChangeView>,
735
    pub conflicted: bool,
736
    pub license: Option<String>,
737
    pub policy: PolicyBadge,
738
}
739
740
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
741
pub enum PolicyBadge {
742
    None,
743
    Active,
744
    Expired,
745
}
746
747
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
748
    let list = repo.bookmarks()?;
749
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
750
    let mut out = Vec::new();
751
    for (b, s) in list.iter().zip(briefs) {
752
        out.push(BookmarkView {
753
            name: b.name.clone(),
754
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
755
            changes: s.changes,
756
            default: b.name == default,
757
            conflicted: s.conflicted,
758
            latest_ms: s.latest_ms,
759
        });
760
    }
761
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
762
    Ok(out)
763
}
764
765
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
766
    let mut out: Vec<TagView> = repo
767
        .tags()?
768
        .into_iter()
769
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
770
        .collect();
771
    out.sort_by(|a, b| b.name.cmp(&a.name));
772
    Ok(out)
773
}
774
775
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
776
    match repo.current_policy() {
777
        Ok(Some((_, sp))) => {
778
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
779
                PolicyBadge::Expired
780
            } else {
781
                PolicyBadge::Active
782
            }
783
        }
784
        _ => PolicyBadge::None,
785
    }
786
}
787
788
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str) -> Result<Overview> {
789
    let target = match resolve(repo, cache, default_bookmark) {
790
        Ok(t) => t,
791
        Err(_) => RefTarget { label: default_bookmark.into(), kind: RefKind::Bookmark, heads: vec![] },
792
    };
793
    let heads = target.heads.len();
794
    // One load of the default state serves the counts, the latest change
795
    // and the tree (hub spec §16.3).
796
    let loaded = cache.load(repo, &target.heads)?;
797
    let state = &loaded.state;
798
    let snapshot = &loaded.snapshot;
799
    let changes = state.len();
800
    let conflicted = snapshot.is_conflicted();
801
    let labels = head_labels(repo)?;
802
    let latest = state
803
        .changes()
804
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
805
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
806
    let tree = tree_of(repo, target, snapshot, "")?;
807
    let license = tree
808
        .entries
809
        .iter()
810
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
811
        .map(|e| e.path.clone());
812
    Ok(Overview {
813
        tree,
814
        changes,
815
        heads,
816
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
817
        tags: tags(repo)?,
818
        latest,
819
        conflicted,
820
        license,
821
        policy: policy_badge(repo),
822
    })
823
}
824
825
// -------------------------------------------------------------- compare
826
827
#[derive(Clone, Debug)]
828
pub struct Compare {
829
    pub base: RefTarget,
830
    pub head: RefTarget,
831
    /// Changes in `head`'s state not in `base`'s.
832
    pub added: Vec<ChangeView>,
833
    /// Changes in `base`'s state not in `head`'s.
834
    pub missing: usize,
835
    pub files: Vec<FileDiff>,
836
    pub bases: BTreeMap<String, Vec<u8>>,
837
}
838
839
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
840
    let base_loaded = cache.load(repo, &base.heads)?;
841
    let head_loaded = cache.load(repo, &head.heads)?;
842
    let base_state = &base_loaded.state;
843
    let head_state = &head_loaded.state;
844
    let labels = head_labels(repo)?;
845
    let mut added: Vec<ChangeView> = head_state
846
        .changes()
847
        .filter(|(h, _)| !base_state.contains(h))
848
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
849
        .collect();
850
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
851
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
852
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
853
    Ok(Compare { base, head, added, missing, files, bases })
854
}
855
856
// ------------------------------------------------------------ conflicts
857
858
#[derive(Clone, Debug)]
859
pub struct ConflictView {
860
    pub bookmark: String,
861
    pub path: String,
862
    pub kind: String,
863
    /// The file rendered with `oxy` conflict markers, when a text file.
864
    pub marked: Option<String>,
865
    pub contributors: Vec<ChangeView>,
866
}
867
868
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
869
    let list = repo.bookmarks()?;
870
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
871
    let mut out = Vec::new();
872
    for (b, brief) in list.iter().zip(briefs) {
873
        // Only a conflicted state is loaded whole.
874
        if !brief.conflicted {
875
            continue;
876
        }
877
        let loaded = cache.load(repo, &b.heads)?;
878
        out.extend(conflicts_in(repo, &loaded, &b.name));
879
    }
880
    Ok(out)
881
}
882
883
/// The conflicts of one loaded state, labelled with `bookmark`.
884
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
885
    let labels = head_labels(repo).unwrap_or_default();
886
    let mut out = Vec::new();
887
    {
888
        let b_name = bookmark.to_string();
889
        let state = &loaded.state;
890
        let snapshot = &loaded.snapshot;
891
        for c in &snapshot.tree.conflicts {
892
            let (path, kind) = describe_tree_conflict(snapshot, c);
893
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
894
        }
895
        for (path, f) in &snapshot.files {
896
            if !f.is_conflicted() {
897
                continue;
898
            }
899
            let (kind, marked, contributors) = match &f.content {
900
                FileContent::Text { .. } => {
901
                    let (bytes, _) = state.render_file(&f.node);
902
                    let regions = state.conflict_regions(&f.node);
903
                    let contributors: Vec<ChangeView> = regions
904
                        .contributors
905
                        .iter()
906
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
907
                        .collect();
908
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
909
                }
910
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
911
                FileContent::Dir => continue,
912
            };
913
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
914
        }
915
    }
916
    out
917
}
918
919
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
920
    let by_node = snapshot.tree.by_node();
921
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
922
    match c {
923
        TreeConflict::Name { name, nodes, .. } => (name.clone(), format!("name: {} entries want this name", nodes.len())),
924
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
925
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
926
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
927
        other => (String::new(), format!("{other:?}")),
928
    }
929
}
930
931
// ------------------------------------------------------------------ trust
932
933
#[derive(Clone, Debug)]
934
pub struct KeyView {
935
    pub key: String,
936
    pub short: String,
937
    pub name: String,
938
    pub email: String,
939
}
940
941
#[derive(Clone, Debug)]
942
pub struct RuleView {
943
    pub pattern: String,
944
    pub keys: Vec<KeyView>,
945
    pub threshold: u32,
946
    pub require: String,
947
    pub allow_conflicts: bool,
948
}
949
950
#[derive(Clone, Debug)]
951
pub struct PolicyView {
952
    pub serial: u64,
953
    pub expires_ms: u64,
954
    pub expired: bool,
955
    pub roots: Vec<KeyView>,
956
    pub root_threshold: u32,
957
    pub rules: Vec<RuleView>,
958
    pub revoked: Vec<KeyView>,
959
    pub signatures: usize,
960
    pub history: usize,
961
}
962
963
#[derive(Clone, Debug, Default)]
964
pub struct Verification {
965
    pub total: usize,
966
    pub signed: usize,
967
    pub sealed: usize,
968
    pub unsigned: usize,
969
    pub revoked: usize,
970
    pub invalid: Vec<(String, String)>,
971
}
972
973
#[derive(Clone, Debug)]
974
pub struct Trust {
975
    pub policy: Option<PolicyView>,
976
    pub verification: Verification,
977
    pub hub_key: String,
978
    pub hub_delegated_by: Vec<KeyView>,
979
}
980
981
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
982
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
983
    match found {
984
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
985
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
986
    }
987
}
988
989
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
990
    let heads = all_heads(repo)?;
991
    let loaded = cache.load(repo, &heads)?;
992
    let state = &loaded.state;
993
    let mut v = Verification::default();
994
    for (h, _) in state.changes() {
995
        v.total += 1;
996
        match signature(repo, h) {
997
            SigView::Unsigned => v.unsigned += 1,
998
            SigView::Valid { sealed, revoked, .. } => {
999
                if revoked {
1000
                    v.revoked += 1;
1001
                }
1002
                if sealed {
1003
                    v.sealed += 1
1004
                } else {
1005
                    v.signed += 1
1006
                }
1007
            }
1008
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1009
        }
1010
    }
1011
    Ok(v)
1012
}
1013
1014
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
1015
    let policy = match repo.current_policy()? {
1016
        Some((_, sp)) => {
1017
            let p = &sp.policy;
1018
            let ids = &p.identities;
1019
            let require = |r: &oxy_core::policy::Require| match r {
1020
                oxy_core::policy::Require::Signed => "signed",
1021
                oxy_core::policy::Require::Sealed => "sealed",
1022
                oxy_core::policy::Require::Any => "any",
1023
            };
1024
            Some(PolicyView {
1025
                serial: p.serial,
1026
                expires_ms: p.expires,
1027
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
1028
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
1029
                root_threshold: p.root_threshold,
1030
                rules: p
1031
                    .rules
1032
                    .iter()
1033
                    .map(|r| RuleView {
1034
                        pattern: r.pattern.clone(),
1035
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
1036
                        threshold: r.threshold,
1037
                        require: require(&r.require).into(),
1038
                        allow_conflicts: r.allow_conflicts,
1039
                    })
1040
                    .collect(),
1041
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
1042
                signatures: sp.sigs.len(),
1043
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1044
            })
1045
        }
1046
        None => None,
1047
    };
1048
    // Who has delegated to the hub: every identity in the policy or store
1049
    // that lists the hub key.
1050
    let mut delegated = Vec::new();
1051
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
1052
        for i in &p.identities {
1053
            if i.delegates.contains(hub_key) {
1054
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
1055
            }
1056
        }
1057
    }
1058
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
1059
}
1060
1061
#[cfg(test)]
1062
mod tests {
1063
    use super::*;
1064
1065
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
1066
        let mut m = BTreeMap::new();
1067
        for p in paths {
1068
            let mut end = 0;
1069
            let parts: Vec<&str> = p.split('/').collect();
1070
            for (i, part) in parts.iter().enumerate() {
1071
                end += part.len();
1072
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1073
                end += 1;
1074
            }
1075
        }
1076
        m
1077
    }
1078
1079
    #[test]
1080
    fn sidebar_expands_the_path_only() {
1081
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
1082
        let rows: Vec<(String, usize, bool, bool)> =
1083
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
1084
        let want = [
1085
            ("docs", 0, true, false),
1086
            ("src", 0, true, true),
1087
            ("src/lib", 1, true, true),
1088
            ("src/lib/a.rs", 2, false, false),
1089
            ("src/lib/b.rs", 2, false, true),
1090
            ("src/main.rs", 1, false, false),
1091
            ("README.md", 0, false, false),
1092
            ("Zeta.txt", 0, false, false),
1093
        ];
1094
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
1095
    }
1096
1097
    #[test]
1098
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1099
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
1100
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1101
        let files = tree(&refs);
1102
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1103
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
1104
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
1105
        assert!(listed.last().unwrap().on_path);
1106
        let more = rows.iter().find(|e| e.more).unwrap();
1107
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
1108
    }
1109
1110
    #[test]
1111
    fn state_addresses_are_sorted_and_bounded() {
1112
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
1113
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
1114
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
1115
        assert_eq!(state_spec(&[]), None);
1116
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
1117
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
1118
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
1119
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
1120
    }
1121
}