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