OXYGENHUB
◆ v0.9.15 oxygenhub / crates / hub / src / repos / view.rs
57.9 KiB · Rust · last changed A default bookmark must exist: settings refuse a missing one, the overview stands in main with a note, an unknown name is not a bookmark, tag or change; Bookmarks › New bookmark makes one on the web (closes #345) 9 days ago source blame history raw
d23464c0 Andy McCall ↶ 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
9ff27da5 Andy McCall ↶ 5
use super::{RepoError, StateCache};
d23464c0 Andy McCall ↶ 6
use oxy_core::hash::{ChangeHash, KeyId};
7
use oxy_core::objects::{Change, NodeKind};
8
use oxy_core::repo::{BlameLine, FileDiff, Repo, SignatureStatus};
9ff27da5 Andy McCall ↶ 9
use oxy_core::state::{FileContent, Snapshot};
d23464c0 Andy McCall ↶ 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
6ae41081 Andy McCall ↶ 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 `+`).
9ff27da5 Andy McCall ↶ 77
pub fn resolve(repo: &Repo, cache: &StateCache, spec: &str) -> Result<RefTarget> {
6ae41081 Andy McCall ↶ 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
    }
d23464c0 Andy McCall ↶ 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
    }
9ff27da5 Andy McCall ↶ 102
    let hash = resolve_change(repo, cache, spec)?;
d23464c0 Andy McCall ↶ 103
    Ok(RefTarget { label: hash.to_hex(), kind: RefKind::Change, heads: vec![hash] })
104
}
105
351cf57e Andy McCall ↶ 106
/// The bookmark to show when the default bookmark does not exist: main,
107
/// else master, else the first by name; `None` without any.
108
fn stand_in(repo: &Repo) -> Result<Option<String>> {
109
    let view = repo.view()?;
110
    let names: Vec<&String> = view.bookmarks.keys().collect();
111
    Ok(["main", "master"]
112
        .iter()
113
        .find(|n| names.iter().any(|b| b == *n))
114
        .map(|n| n.to_string())
115
        .or_else(|| names.iter().min().map(|b| b.to_string())))
116
}
117
d23464c0 Andy McCall ↶ 118
/// A change by full hash or unique hex prefix, searched over every
119
/// bookmark's state.
9ff27da5 Andy McCall ↶ 120
pub fn resolve_change(repo: &Repo, cache: &StateCache, spec: &str) -> Result<ChangeHash> {
d23464c0 Andy McCall ↶ 121
    let spec = spec.trim_start_matches('#');
122
    if spec.len() < 4 || !spec.chars().all(|c| c.is_ascii_hexdigit()) {
351cf57e Andy McCall ↶ 123
        return Err(fail(format!("{spec:?} is not a bookmark, tag or change of this repository")));
d23464c0 Andy McCall ↶ 124
    }
125
    if let Some(h) = ChangeHash::from_hex(spec) {
126
        if repo.store().has(&h) {
127
            return Ok(h);
128
        }
129
    }
130
    let heads = all_heads(repo)?;
9ff27da5 Andy McCall ↶ 131
    let loaded = cache.load(repo, &heads)?;
132
    let matches: Vec<ChangeHash> = loaded.state.changes().map(|(h, _)| *h).filter(|h| h.starts_with_hex(spec)).collect();
d23464c0 Andy McCall ↶ 133
    match matches.len() {
134
        1 => Ok(matches[0]),
135
        0 => Err(fail(format!("no change matches {spec:?}"))),
136
        _ => Err(fail(format!("{spec:?} is ambiguous"))),
137
    }
138
}
139
140
/// The heads of every bookmark, deduplicated.
141
pub fn all_heads(repo: &Repo) -> Result<Vec<ChangeHash>> {
142
    let mut set = BTreeSet::new();
143
    for b in repo.bookmarks()? {
144
        set.extend(b.heads);
145
    }
146
    Ok(set.into_iter().collect())
147
}
148
149
// ---------------------------------------------------------------- authors
150
151
#[derive(Clone, Debug, PartialEq, Eq)]
152
pub struct AuthorView {
153
    pub name: String,
154
    pub email: String,
155
    pub key: String,
156
    /// True when the key is not an identity the store knows.
157
    pub unknown: bool,
19bb31ff Andy McCall ↶ 158
    /// The hub account the key is linked to, filled by the web layer.
159
    pub account: Option<String>,
d23464c0 Andy McCall ↶ 160
}
161
162
pub fn author(repo: &Repo, key: &KeyId, message: &str) -> AuthorView {
163
    if key.is_zero() {
164
        // Imported from Git: the trailer carries the author.
165
        let line = message.lines().rev().find_map(|l| l.strip_prefix("Git-Author: ")).unwrap_or("unknown");
166
        let (name, email) = match line.split_once('<') {
167
            Some((n, e)) => (n.trim().to_string(), e.trim_end_matches('>').trim().to_string()),
168
            None => (line.trim().to_string(), String::new()),
169
        };
19bb31ff Andy McCall ↶ 170
        return AuthorView { name, email, key: String::new(), unknown: true, account: None };
d23464c0 Andy McCall ↶ 171
    }
172
    match repo.store().get_identity(key) {
19bb31ff Andy McCall ↶ 173
        Ok(id) => AuthorView { name: id.name, email: id.email, key: key.to_hex(), unknown: false, account: None },
174
        Err(_) => AuthorView { name: key.short(12), email: String::new(), key: key.to_hex(), unknown: true, account: None },
d23464c0 Andy McCall ↶ 175
    }
176
}
177
178
// ---------------------------------------------------------------- changes
179
180
#[derive(Clone, Debug, PartialEq, Eq)]
181
pub enum SigView {
182
    Unsigned,
183
    Valid { key: String, name: String, sealed: bool, revoked: bool },
184
    Invalid(String),
185
}
186
187
impl SigView {
188
    pub fn glyph(&self) -> &'static str {
189
        match self {
190
            SigView::Unsigned => "○",
191
            SigView::Valid { revoked: true, .. } => "⊘",
192
            SigView::Valid { sealed: true, .. } => "◈",
193
            SigView::Valid { .. } => "✔",
194
            SigView::Invalid(_) => "✘",
195
        }
196
    }
197
198
    pub fn class(&self) -> &'static str {
199
        match self {
200
            SigView::Unsigned => "sig-unsigned",
201
            SigView::Valid { revoked: true, .. } => "sig-revoked",
202
            SigView::Valid { .. } => "sig-valid",
203
            SigView::Invalid(_) => "sig-invalid",
204
        }
205
    }
206
207
    pub fn title(&self) -> String {
208
        match self {
209
            SigView::Unsigned => "unsigned".into(),
210
            SigView::Valid { name, sealed: true, revoked: false, .. } => format!("sealed by {name}"),
211
            SigView::Valid { name, revoked: true, .. } => format!("signed by {name}, key revoked"),
212
            SigView::Valid { name, .. } => format!("signed by {name}"),
213
            SigView::Invalid(why) => format!("INVALID: {why}"),
214
        }
215
    }
216
}
217
218
pub fn signature(repo: &Repo, hash: &ChangeHash) -> SigView {
219
    match repo.verify_change(hash) {
220
        Ok(SignatureStatus::Unsigned) => SigView::Unsigned,
221
        Ok(SignatureStatus::Valid { key, name, sealed, revoked, .. }) => SigView::Valid { key: key.to_hex(), name, sealed, revoked },
222
        Ok(SignatureStatus::Invalid(why)) => SigView::Invalid(why),
223
        Err(e) => SigView::Invalid(e.to_string()),
224
    }
225
}
226
8933faff Andy McCall ↶ 227
/// Who signed for the author when it was not the author: a delegate, such
228
/// as an agent, named by its identity, with the delegation that let it
229
/// (Oxygen's agent workflows doc §6).
230
#[derive(Clone, Debug, PartialEq, Eq)]
231
pub struct ViaView {
232
    pub name: String,
233
    pub email: String,
234
    pub key: String,
235
    pub short: String,
236
    /// The delegation's scope as written, `changes` for an agent.
237
    pub scope: String,
238
    pub expires_ms: Option<u64>,
239
    /// The signing key was revoked, or the delegation is no longer in the
240
    /// author's identity: the change deserves a second look.
241
    pub revoked: bool,
242
}
243
244
impl ViaView {
245
    /// The delegation, as the change page's `via` row says it.
246
    pub fn delegation(&self) -> String {
247
        if self.revoked {
248
            return "delegation revoked".into();
249
        }
250
        match self.expires_ms {
251
            Some(e) => format!("delegate for {}, until {}", self.scope, when_utc(e)),
252
            None => format!("delegate for {}", self.scope),
253
        }
254
    }
255
256
    /// What hovering the badge says.
257
    pub fn title(&self) -> String {
258
        let until = match self.expires_ms {
259
            Some(e) => format!(", until {}", when_utc(e)),
260
            None => String::new(),
261
        };
262
        if self.revoked {
263
            format!("signed by {} as a delegate of the author; that delegation has since been revoked", self.name)
264
        } else {
265
            format!("signed by {} as a delegate of the author ({}{until}), key {}", self.name, self.scope, self.short)
266
        }
267
    }
268
}
269
270
/// `2026-10-04 20:12Z` for a wall time in milliseconds.
271
fn when_utc(ms: u64) -> String {
272
    time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000)
273
        .ok()
274
        .and_then(|t| t.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]Z")).ok())
275
        .unwrap_or_else(|| ms.to_string())
276
}
277
278
/// The delegate that signed `hash` for the author, when one did.
279
pub fn via(repo: &Repo, author: &KeyId, sig: &SigView) -> Option<ViaView> {
280
    let SigView::Valid { key, name, revoked, .. } = sig else { return None };
281
    if author.is_zero() || *key == author.to_hex() {
282
        return None;
283
    }
284
    let signer = KeyId::from_hex(key)?;
285
    let entry = repo.store().get_identity(author).ok().and_then(|a| a.delegate(&signer).copied());
286
    let email = repo.store().get_identity(&signer).map(|i| i.email).unwrap_or_default();
287
    Some(ViaView {
288
        name: name.clone(),
289
        email,
290
        key: key.clone(),
291
        short: signer.short(12),
292
        scope: entry.map(|d| d.scope.to_string()).unwrap_or_else(|| "changes".into()),
293
        expires_ms: entry.and_then(|d| d.expires),
294
        revoked: *revoked || entry.is_none(),
295
    })
296
}
297
d23464c0 Andy McCall ↶ 298
/// One change as history rows and change pages show it.
299
#[derive(Clone, Debug)]
300
pub struct ChangeView {
301
    pub hash: String,
302
    pub short: String,
303
    pub title: String,
304
    pub body: String,
305
    pub author: AuthorView,
306
    pub when_ms: u64,
307
    pub deps: Vec<String>,
308
    pub head: bool,
309
    pub resolution: bool,
310
    pub signature: SigView,
8933faff Andy McCall ↶ 311
    /// Signed for the author by a delegate (an agent), when it was.
312
    pub via: Option<ViaView>,
d23464c0 Andy McCall ↶ 313
    /// Bookmarks and tags whose state has this change as a head.
314
    pub labels: Vec<Label>,
315
}
316
317
#[derive(Clone, Debug, PartialEq, Eq)]
318
pub struct Label {
319
    pub name: String,
320
    pub kind: RefKind,
321
}
322
323
pub fn split_message(message: &str) -> (String, String) {
324
    let mut lines = message.lines();
325
    let title = lines.next().unwrap_or("").trim().to_string();
326
    let body = lines.collect::<Vec<_>>().join("\n").trim().to_string();
327
    (title, body)
328
}
329
330
/// Every bookmark and tag head, for labelling rows.
331
pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> {
332
    let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new();
333
    for b in repo.bookmarks()? {
334
        for h in b.heads {
335
            out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark });
336
        }
337
    }
338
    for t in repo.tags()? {
339
        for h in t.heads {
340
            out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag });
341
        }
342
    }
343
    Ok(out)
344
}
345
de505df5 Andy McCall ↶ 346
pub fn change_view_pub(
347
    repo: &Repo,
348
    hash: &ChangeHash,
349
    meta: &oxy_core::state::ChangeMeta,
350
    head: bool,
351
    labels: &HashMap<ChangeHash, Vec<Label>>,
352
) -> ChangeView {
353
    change_view(repo, hash, meta, head, labels)
354
}
355
d23464c0 Andy McCall ↶ 356
fn change_view(
357
    repo: &Repo,
358
    hash: &ChangeHash,
359
    meta: &oxy_core::state::ChangeMeta,
360
    head: bool,
361
    labels: &HashMap<ChangeHash, Vec<Label>>,
362
) -> ChangeView {
363
    let (title, body) = split_message(&meta.message);
8933faff Andy McCall ↶ 364
    let signature = signature(repo, hash);
365
    let via = via(repo, &meta.author, &signature);
d23464c0 Andy McCall ↶ 366
    ChangeView {
367
        hash: hash.to_hex(),
368
        short: hash.short(12),
369
        title,
370
        body,
371
        author: author(repo, &meta.author, &meta.message),
372
        when_ms: meta.hlc.wall_ms,
373
        deps: meta.deps.iter().map(|d| d.to_hex()).collect(),
374
        head,
375
        resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution,
8933faff Andy McCall ↶ 376
        signature,
377
        via,
d23464c0 Andy McCall ↶ 378
        labels: labels.get(hash).cloned().unwrap_or_default(),
379
    }
380
}
381
382
// ---------------------------------------------------------------- history
383
384
#[derive(Clone, Debug)]
385
pub struct History {
386
    pub target: RefTarget,
387
    pub entries: Vec<ChangeView>,
388
    pub total: usize,
389
    pub offset: usize,
390
    pub has_more: bool,
391
    pub path: Option<String>,
392
}
393
394
/// A window of the history of a state, newest first.
9ff27da5 Andy McCall ↶ 395
pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> {
396
    let loaded = cache.load(repo, &target.heads)?;
397
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
398
    let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path {
399
        Some(p) => {
400
            let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) };
401
            loaded
402
                .state
403
                .changes()
404
                .filter(|(h, _)| {
df15b747 Andy McCall ↶ 405
                    // The skeleton says which nodes a change touches, without its text.
9ff27da5 Andy McCall ↶ 406
                    repo.store()
df15b747 Andy McCall ↶ 407
                        .get_change_lazy(h)
408
                        .map(|(c, _)| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node))
9ff27da5 Andy McCall ↶ 409
                        .unwrap_or(false)
410
                })
411
                .map(|(h, m)| (*h, m.clone()))
412
                .collect()
413
        }
414
        None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(),
d23464c0 Andy McCall ↶ 415
    };
9ff27da5 Andy McCall ↶ 416
    entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0)));
d23464c0 Andy McCall ↶ 417
    let total = entries.len();
418
    let labels = head_labels(repo)?;
419
    let window: Vec<ChangeView> =
9ff27da5 Andy McCall ↶ 420
        entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect();
d23464c0 Andy McCall ↶ 421
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) })
422
}
423
f28389bd Andy McCall ↶ 424
/// A window of the changes a revset selects (Oxygen's
425
/// docs/revset_query_language.md §3), newest first, under a budget
426
/// stricter than the command line's so a query cannot load the server.
427
/// `target` is the reference the request named, for labels and heads.
428
pub fn history_revset(repo: &Repo, cache: &StateCache, target: RefTarget, revset: &str, offset: usize, limit: usize) -> Result<History> {
429
    let loaded = cache.load(repo, &target.heads)?;
430
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
431
    let selected = repo.revset_with_budget(revset, std::time::Duration::from_secs(2))?;
432
    let total = selected.hashes.len();
433
    let labels = head_labels(repo)?;
434
    let window: Vec<ChangeView> = selected
435
        .hashes
436
        .iter()
437
        .skip(offset)
438
        .take(limit)
439
        .filter_map(|h| selected.metas.get(h).map(|m| change_view(repo, h, m, head_set.contains(h), &labels)))
440
        .collect();
441
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: None })
442
}
443
d23464c0 Andy McCall ↶ 444
// ----------------------------------------------------------------- change
445
446
#[derive(Clone, Debug)]
447
pub struct ChangeDetail {
448
    pub view: ChangeView,
449
    pub dependents: Vec<ChangeView>,
450
    pub deps: Vec<ChangeView>,
451
    pub files: Vec<FileDiff>,
452
    /// Base content of each modified file, for context lines.
453
    pub bases: BTreeMap<String, Vec<u8>>,
454
    pub in_bookmarks: Vec<String>,
455
    pub in_tags: Vec<String>,
456
    pub atoms: usize,
457
    pub tree_ops: usize,
458
}
459
9ff27da5 Andy McCall ↶ 460
pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> {
d23464c0 Andy McCall ↶ 461
    let c: Change = repo.store().get_change(hash)?;
462
    let labels = head_labels(repo)?;
463
    let heads = all_heads(repo)?;
9ff27da5 Andy McCall ↶ 464
    let loaded = cache.load(repo, &heads)?;
465
    let state = &loaded.state;
d23464c0 Andy McCall ↶ 466
    let is_head = state.heads().contains(hash);
467
    let meta = oxy_core::state::ChangeMeta::of(&c);
468
    let view = change_view(repo, hash, &meta, is_head, &labels);
469
    let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect();
470
    let mut dependents: Vec<ChangeView> = state
471
        .changes()
472
        .filter(|(_, m)| m.deps.contains(hash))
473
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels))
474
        .collect();
475
    dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
9ff27da5 Andy McCall ↶ 476
    let base = cache.load(repo, &c.deps)?;
477
    let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot);
478
    let base_snapshot = &base.snapshot;
d23464c0 Andy McCall ↶ 479
    let mut bases = BTreeMap::new();
480
    for f in &files {
481
        let old = f.from.as_deref().unwrap_or(&f.path);
482
        if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) {
483
            bases.insert(f.path.clone(), bytes.clone());
484
        }
485
    }
486
    let mut in_bookmarks = Vec::new();
487
    for b in repo.bookmarks()? {
2e640ffa Andy McCall ↶ 488
        if cache.summary(repo, &b.heads)?.changes.contains(hash) {
d23464c0 Andy McCall ↶ 489
            in_bookmarks.push(b.name);
490
        }
491
    }
492
    let mut in_tags = Vec::new();
493
    for t in repo.tags()? {
2e640ffa Andy McCall ↶ 494
        if cache.summary(repo, &t.heads)?.changes.contains(hash) {
d23464c0 Andy McCall ↶ 495
            in_tags.push(t.name);
496
        }
497
    }
498
    Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() })
499
}
500
501
// ------------------------------------------------------------------- tree
502
503
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
504
pub enum EntryKind {
505
    Dir,
506
    File,
507
    Symlink,
508
    Subrepo,
509
}
510
511
#[derive(Clone, Debug)]
512
pub struct Entry {
513
    pub name: String,
514
    pub path: String,
515
    pub kind: EntryKind,
516
    pub exec: bool,
517
    pub size: Option<u64>,
518
    pub conflicted: bool,
519
}
520
521
#[derive(Clone, Debug)]
522
pub struct Tree {
523
    pub target: RefTarget,
524
    pub path: String,
525
    pub entries: Vec<Entry>,
526
    /// `(name, path)` from the root down to this directory.
527
    pub crumbs: Vec<(String, String)>,
528
    pub readme: Option<Readme>,
529
}
530
531
#[derive(Clone, Debug)]
532
pub struct Readme {
533
    pub path: String,
534
    pub text: String,
535
}
536
537
pub fn crumbs(path: &str) -> Vec<(String, String)> {
538
    let mut out = Vec::new();
539
    let mut so_far = String::new();
540
    for part in path.split('/').filter(|p| !p.is_empty()) {
541
        if !so_far.is_empty() {
542
            so_far.push('/');
543
        }
544
        so_far.push_str(part);
545
        out.push((part.to_string(), so_far.clone()));
546
    }
547
    out
548
}
549
550
fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry {
551
    let kind = match f.kind {
552
        NodeKind::Dir => EntryKind::Dir,
553
        NodeKind::File => EntryKind::File,
554
        NodeKind::Symlink => EntryKind::Symlink,
555
        NodeKind::Subrepo => EntryKind::Subrepo,
556
    };
557
    let size = match &f.content {
558
        FileContent::Text { bytes, .. } => Some(bytes.len() as u64),
559
        _ => None,
560
    };
561
    Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() }
562
}
563
564
/// The entries directly under `dir` (`""` for the root).
9ff27da5 Andy McCall ↶ 565
pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> {
566
    let loaded = cache.load(repo, &target.heads)?;
567
    tree_of(repo, target, &loaded.snapshot, dir)
d23464c0 Andy McCall ↶ 568
}
569
570
pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> {
571
    let dir = dir.trim_matches('/');
572
    if !dir.is_empty() {
573
        match snapshot.files.get(dir) {
574
            Some(f) if f.kind == NodeKind::Dir => {}
575
            _ => return Err(RepoError::NotFound),
576
        }
577
    }
578
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
579
    let mut entries: Vec<Entry> = snapshot
580
        .files
581
        .iter()
582
        .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/'))
583
        .map(|(p, f)| entry_of(p, &p[prefix.len()..], f))
584
        .collect();
585
    entries.sort_by(|a, b| {
586
        (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
587
    });
588
    let readme = entries
589
        .iter()
590
        .find(|e| {
591
            e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown")
592
        })
593
        .and_then(|e| match &snapshot.files.get(&e.path)?.content {
594
            FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }),
595
            _ => None,
596
        });
597
    Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme })
598
}
599
600
// ------------------------------------------------------------------- file
601
602
#[derive(Clone, Debug)]
603
pub enum FileBody {
604
    Text(String),
605
    Binary,
606
    TooLarge,
6ae41081 Andy McCall ↶ 607
}
608
609
/// One row of the file page's tree sidebar (hub spec §6.6).
610
#[derive(Clone, Debug, PartialEq, Eq)]
611
pub struct SideEntry {
612
    pub name: String,
613
    pub path: String,
614
    pub depth: usize,
615
    pub dir: bool,
616
    /// A directory on the way to the file (expanded), or the file itself.
617
    pub on_path: bool,
618
    /// A "more" row standing for the rest of a long directory.
619
    pub more: bool,
620
}
621
622
/// Entries listed per directory in the sidebar before a "more" row.
623
const SIDEBAR_PER_DIR: usize = 200;
624
625
/// The tree down to `path`: each directory on the way expanded, in tree
626
/// order (directories first, then case-insensitive names).
627
pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> {
628
    sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path)
629
}
630
631
/// `sidebar` over any path map, given which values are directories.
632
pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> {
633
    let mut out = Vec::new();
634
    sidebar_dir(files, is_dir, "", path, 0, &mut out);
635
    out
636
}
637
638
fn sidebar_dir<V>(
639
    files: &BTreeMap<String, V>,
640
    is_dir: impl Fn(&V) -> bool + Copy,
641
    dir: &str,
642
    target: &str,
643
    depth: usize,
644
    out: &mut Vec<SideEntry>,
645
) {
646
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
647
    let mut children: Vec<(&str, bool)> = files
648
        .range(prefix.clone()..)
649
        .take_while(|(p, _)| p.starts_with(&prefix))
650
        .filter(|(p, _)| !p[prefix.len()..].contains('/'))
651
        .map(|(p, f)| (p.as_str(), is_dir(f)))
652
        .collect();
653
    children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));
654
    let total = children.len();
655
    for (i, (p, dir_entry)) in children.into_iter().enumerate() {
656
        let on_path = target == p || target.starts_with(&format!("{p}/"));
657
        // Past the limit, keep only the entry on the way to the file.
658
        if i >= SIDEBAR_PER_DIR && !on_path {
659
            continue;
660
        }
661
        out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false });
662
        if dir_entry && on_path && p != target {
663
            sidebar_dir(files, is_dir, p, target, depth + 1, out);
664
        }
665
    }
666
    if total > SIDEBAR_PER_DIR {
667
        out.push(SideEntry {
668
            name: format!("{} more", total - SIDEBAR_PER_DIR),
669
            path: dir.to_string(),
670
            depth,
671
            dir: true,
672
            on_path: false,
673
            more: true,
674
        });
675
    }
d23464c0 Andy McCall ↶ 676
}
677
678
#[derive(Clone, Debug)]
679
pub struct FileView {
680
    pub target: RefTarget,
681
    pub path: String,
682
    pub name: String,
683
    pub crumbs: Vec<(String, String)>,
684
    pub kind: EntryKind,
685
    pub exec: bool,
686
    pub size: u64,
687
    pub body: FileBody,
688
    pub conflicted: bool,
689
    /// Raw bytes, for the `?plain=1` response and images.
690
    pub bytes: Vec<u8>,
691
    pub last_change: Option<ChangeView>,
6ae41081 Andy McCall ↶ 692
    pub sidebar: Vec<SideEntry>,
d23464c0 Andy McCall ↶ 693
}
694
9ff27da5 Andy McCall ↶ 695
pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> {
696
    let loaded = cache.load(repo, &target.heads)?;
697
    let snapshot = &loaded.snapshot;
d23464c0 Andy McCall ↶ 698
    let path = path.trim_matches('/');
699
    let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) };
700
    let (kind, bytes) = match (&f.kind, &f.content) {
701
        (NodeKind::Dir, _) => return Err(RepoError::NotFound),
702
        (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()),
703
        (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()),
704
        (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()),
705
        (_, FileContent::Opaque { blobs }) => {
706
            let bytes = match blobs.first() {
707
                Some(b) => repo.read_blob(b)?,
708
                None => Vec::new(),
709
            };
710
            (EntryKind::File, bytes)
711
        }
712
        (_, FileContent::Dir) => return Err(RepoError::NotFound),
713
    };
714
    let size = bytes.len() as u64;
715
    let body = if size > render_limit {
716
        FileBody::TooLarge
717
    } else if is_binary(&bytes) {
718
        FileBody::Binary
719
    } else {
720
        FileBody::Text(String::from_utf8_lossy(&bytes).into_owned())
721
    };
722
    let labels = head_labels(repo)?;
b19606f2 Andy McCall ↶ 723
    let last_change = last_change_of(repo, &loaded.state, &target.heads, path)
75d611ab Andy McCall ↶ 724
        .and_then(|h| loaded.state.get(&h).map(|meta| change_view(repo, &h, meta, loaded.state.heads().contains(&h), &labels)));
d23464c0 Andy McCall ↶ 725
    let name = path.rsplit('/').next().unwrap_or(path).to_string();
726
    Ok(FileView {
727
        target,
728
        path: path.to_string(),
729
        name,
730
        crumbs: crumbs(path),
731
        kind,
732
        exec: f.mode.exec,
733
        size,
734
        body,
735
        conflicted: f.is_conflicted(),
736
        bytes,
737
        last_change,
6ae41081 Andy McCall ↶ 738
        sidebar: sidebar(snapshot, path),
d23464c0 Andy McCall ↶ 739
    })
740
}
741
736f6813 Andy McCall ↶ 742
/// A file's name and bytes, and nothing else (for raw responses).
743
pub fn raw(repo: &Repo, cache: &StateCache, target: &RefTarget, path: &str) -> Result<(String, Vec<u8>)> {
744
    let loaded = cache.load(repo, &target.heads)?;
745
    let path = path.trim_matches('/');
746
    let Some(f) = loaded.snapshot.files.get(path) else { return Err(RepoError::NotFound) };
747
    let bytes = match (&f.kind, &f.content) {
748
        (NodeKind::Dir, _) | (_, FileContent::Dir) => return Err(RepoError::NotFound),
749
        (_, FileContent::Text { bytes, .. }) => bytes.clone(),
750
        (_, FileContent::Opaque { blobs }) => match blobs.first() {
751
            Some(b) => repo.read_blob(b)?,
752
            None => Vec::new(),
753
        },
754
    };
755
    Ok((path.rsplit('/').next().unwrap_or(path).to_string(), bytes))
75d611ab Andy McCall ↶ 756
}
757
758
/// Facts about a path in a state never change, so they are cached by the
759
/// state's heads and the path (hub spec §16.3).
760
fn state_path_key(tag: &[u8], heads: &[ChangeHash], path: &str) -> [u8; 32] {
761
    let mut sorted: Vec<&ChangeHash> = heads.iter().collect();
762
    sorted.sort();
763
    let joined: Vec<u8> = sorted.iter().flat_map(|h| h.to_hex().into_bytes()).collect();
764
    crate::render::cache::key(&[tag, &joined, path.as_bytes()])
736f6813 Andy McCall ↶ 765
}
766
75d611ab Andy McCall ↶ 767
struct Last(Option<ChangeHash>);
768
769
impl crate::render::cache::Weigh for Last {
770
    fn weight(&self) -> usize {
771
        64
772
    }
773
}
774
775
/// The newest change touching `path` in the state, from a cache of 4 MiB.
b19606f2 Andy McCall ↶ 776
pub fn last_change_of(repo: &Repo, state: &oxy_core::state::State, heads: &[ChangeHash], path: &str) -> Option<ChangeHash> {
75d611ab Andy McCall ↶ 777
    static C: std::sync::OnceLock<crate::render::cache::Lru<Last>> = std::sync::OnceLock::new();
778
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(4 << 20));
779
    let key = state_path_key(b"last1", heads, path);
b19606f2 Andy McCall ↶ 780
    cache.get_or(key, || Last(repo.log_for_path_of(state, path, Some(1)).ok().and_then(|l| l.into_iter().next()).map(|e| e.hash))).0
75d611ab Andy McCall ↶ 781
}
782
783
struct BlameLines(Vec<BlameLine>);
784
785
impl crate::render::cache::Weigh for BlameLines {
786
    fn weight(&self) -> usize {
787
        self.0.iter().map(|l| l.text.len() + l.author.len() + 128).sum::<usize>() + 32
788
    }
789
}
790
791
/// `Repo::blame_in`, cached by state and path (64 MiB).
b19606f2 Andy McCall ↶ 792
fn blame_cached(repo: &Repo, cache_state: &StateCache, heads: &[ChangeHash], path: &str) -> Result<Vec<BlameLine>> {
75d611ab Andy McCall ↶ 793
    static C: std::sync::OnceLock<crate::render::cache::Lru<BlameLines>> = std::sync::OnceLock::new();
794
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(64 << 20));
795
    let key = state_path_key(b"blame1", heads, path);
796
    let mut failure = None;
b19606f2 Andy McCall ↶ 797
    let lines = cache.get_or(key, || {
798
        match cache_state
799
            .load(repo, heads)
800
            .map_err(|e| oxy_core::repo::RepoError::Msg(e.to_string()))
801
            .and_then(|loaded| repo.blame_of(&loaded.state, &loaded.snapshot.tree, path))
802
        {
803
            Ok(l) => BlameLines(l),
804
            Err(e) => {
805
                failure = Some(e);
806
                BlameLines(Vec::new())
807
            }
75d611ab Andy McCall ↶ 808
        }
809
    });
810
    if let Some(e) = failure {
811
        return Err(RepoError::Oxy(e));
812
    }
813
    Ok(lines.0.clone())
814
}
815
d23464c0 Andy McCall ↶ 816
pub fn is_binary(bytes: &[u8]) -> bool {
817
    let head = &bytes[..bytes.len().min(8192)];
818
    head.contains(&0)
819
        || std::str::from_utf8(head).is_err()
820
            && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20
821
}
822
823
/// Last change per entry of a directory, for tree rows (fetched lazily).
824
/// A directory's last change is the newest change touching anything
825
/// beneath it, as GitHub shows it.
9ff27da5 Andy McCall ↶ 826
pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> {
d23464c0 Andy McCall ↶ 827
    let labels = head_labels(repo)?;
9ff27da5 Andy McCall ↶ 828
    let loaded = cache.load(repo, heads)?;
829
    let state = &loaded.state;
830
    let snapshot = &loaded.snapshot;
d23464c0 Andy McCall ↶ 831
    // Newest change touching each node, from one pass over the log.
832
    let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new();
b19606f2 Andy McCall ↶ 833
    for e in repo.log_of(state) {
df15b747 Andy McCall ↶ 834
        let Ok((c, _)) = repo.store().get_change_lazy(&e.hash) else { continue };
d23464c0 Andy McCall ↶ 835
        let when = e.change.hlc.wall_ms;
836
        for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) {
837
            newest.entry(node).or_insert((e.hash, when));
838
        }
839
    }
840
    let mut out = Vec::new();
841
    for p in paths {
842
        let Some(f) = snapshot.files.get(p) else { continue };
843
        let best = if f.kind == NodeKind::Dir {
844
            let prefix = format!("{p}/");
845
            snapshot
846
                .files
847
                .iter()
848
                .filter(|(q, _)| q.starts_with(&prefix))
849
                .filter_map(|(_, g)| newest.get(&g.node))
850
                .chain(newest.get(&f.node))
851
                .max_by_key(|(_, when)| *when)
852
                .copied()
853
        } else {
854
            newest.get(&f.node).copied()
855
        };
856
        if let Some((hash, _)) = best {
857
            if let Some(m) = state.get(&hash) {
858
                out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels)));
859
            }
860
        }
861
    }
862
    Ok(out)
863
}
864
865
// ------------------------------------------------------------------ blame
866
867
#[derive(Clone, Debug)]
868
pub struct Blame {
869
    pub file: FileView,
870
    pub lines: Vec<BlameLine>,
6ae41081 Andy McCall ↶ 871
    /// For each blamed change, the state address of its dependencies:
872
    /// the state its author built on (None without dependencies).
873
    pub before: HashMap<ChangeHash, Option<String>>,
d23464c0 Andy McCall ↶ 874
}
875
9ff27da5 Andy McCall ↶ 876
pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> {
d23464c0 Andy McCall ↶ 877
    let heads = target.heads.clone();
9ff27da5 Andy McCall ↶ 878
    let file = file(repo, cache, target, path, render_limit)?;
b19606f2 Andy McCall ↶ 879
    let lines = blame_cached(repo, cache, &heads, path)?;
6ae41081 Andy McCall ↶ 880
    let mut before = HashMap::new();
881
    for l in &lines {
df15b747 Andy McCall ↶ 882
        before.entry(l.hash).or_insert_with(|| repo.store().get_change_meta(&l.hash).ok().and_then(|c| state_spec(&c.deps)));
6ae41081 Andy McCall ↶ 883
    }
884
    Ok(Blame { file, lines, before })
d23464c0 Andy McCall ↶ 885
}
886
887
// -------------------------------------------------------------- overview
888
889
#[derive(Clone, Debug)]
890
pub struct BookmarkView {
891
    pub name: String,
892
    pub heads: Vec<String>,
893
    pub changes: usize,
894
    pub default: bool,
895
    pub conflicted: bool,
896
    pub latest_ms: u64,
897
}
898
899
#[derive(Clone, Debug)]
900
pub struct TagView {
901
    pub name: String,
902
    pub heads: Vec<String>,
903
    pub message: String,
904
    pub signer: Option<String>,
905
}
906
ba0a55bb Andy McCall ↶ 907
/// A tag withdrawn here (#301): the state it named, why, by whom and when.
d23464c0 Andy McCall ↶ 908
#[derive(Clone, Debug)]
ba0a55bb Andy McCall ↶ 909
pub struct WithdrawnView {
910
    pub name: String,
911
    pub heads: Vec<String>,
912
    pub reason: String,
913
    pub signer: Option<String>,
914
    pub when_ms: i64,
915
}
916
917
#[derive(Clone, Debug)]
d23464c0 Andy McCall ↶ 918
pub struct Overview {
919
    pub tree: Tree,
920
    pub changes: usize,
921
    pub heads: usize,
922
    pub bookmarks: Vec<BookmarkView>,
923
    pub tags: Vec<TagView>,
924
    pub latest: Option<ChangeView>,
925
    pub conflicted: bool,
926
    pub license: Option<String>,
927
    pub policy: PolicyBadge,
83d5052b Andy McCall ↶ 928
    pub contributors: Vec<Contributor>,
929
    pub languages: Vec<LanguageShare>,
351cf57e Andy McCall ↶ 930
    /// The bookmark shown in the default's place when the repository has
931
    /// no bookmark of the default's name (a default set before its first
932
    /// push, or one deleted since).
933
    pub standing_in: Option<String>,
83d5052b Andy McCall ↶ 934
}
935
c9aacc0e Andy McCall ↶ 936
impl Overview {
937
    /// The sidebar's bookmarks (#152): the default first, then the most
938
    /// recently moved, ten in all.
939
    pub fn recent_bookmarks(&self) -> Vec<&BookmarkView> {
940
        let mut list: Vec<&BookmarkView> = self.bookmarks.iter().collect();
941
        list.sort_by(|a, b| b.default.cmp(&a.default).then(b.latest_ms.cmp(&a.latest_ms)).then_with(|| a.name.cmp(&b.name)));
942
        list.truncate(10);
943
        list
944
    }
945
}
946
83d5052b Andy McCall ↶ 947
/// Someone who authored changes in a state (hub spec §6.4).
948
#[derive(Clone, Debug, PartialEq, Eq)]
949
pub struct Contributor {
950
    pub name: String,
951
    /// The identity key (hex), empty for authors imported from Git.
952
    pub key: String,
953
    pub changes: usize,
954
    /// The hub account the key is linked to, filled by the web layer.
955
    pub account: Option<String>,
8933faff Andy McCall ↶ 956
    /// Of `changes`, how many a delegate signed for this author, by the
957
    /// delegate's name (an agent's work stays the author's, and is shown).
958
    pub via: Vec<(String, usize)>,
c9aacc0e Andy McCall ↶ 959
    /// The hub's own delegate key, filled by the web layer (#152).
960
    pub hub: bool,
83d5052b Andy McCall ↶ 961
}
962
963
/// One language's share of a state's code, by bytes.
964
#[derive(Clone, Debug, PartialEq)]
965
pub struct LanguageShare {
966
    pub name: String,
967
    pub bytes: u64,
968
    pub percent: f64,
969
    pub colour: String,
970
}
971
8933faff Andy McCall ↶ 972
/// Authors of the changes of a state, most changes first. A change a
973
/// delegate signed counts for its author, and the delegate is named under
974
/// them: the signing key is read, not verified (the change rows do that).
83d5052b Andy McCall ↶ 975
pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> {
976
    let mut by: HashMap<String, Contributor> = HashMap::new();
8933faff Andy McCall ↶ 977
    let mut names: HashMap<KeyId, String> = HashMap::new();
978
    for (hash, meta) in state.changes() {
83d5052b Andy McCall ↶ 979
        let a = author(repo, &meta.author, &meta.message);
980
        let id = if a.key.is_empty() { format!("git:{}", a.email.to_lowercase()) } else { a.key.clone() };
6ad368c5 Andy McCall ↶ 981
        // Unsigned changes with no Git author carry no name at all.
982
        let name =
983
            if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() };
c9aacc0e Andy McCall ↶ 984
        let entry = by.entry(id).or_insert_with(|| Contributor {
985
            name,
986
            key: a.key.clone(),
987
            changes: 0,
988
            account: None,
989
            via: Vec::new(),
990
            hub: false,
991
        });
8933faff Andy McCall ↶ 992
        entry.changes += 1;
993
        if !meta.author.is_zero() {
994
            let signer = repo.store().signatures(hash).ok().and_then(|s| s.first().map(|s| s.key)).filter(|k| *k != meta.author);
995
            if let Some(k) = signer {
996
                let who =
997
                    names.entry(k).or_insert_with(|| repo.store().get_identity(&k).map(|i| i.name).unwrap_or_else(|_| k.short(12))).clone();
998
                match entry.via.iter_mut().find(|(n, _)| *n == who) {
999
                    Some((_, n)) => *n += 1,
1000
                    None => entry.via.push((who, 1)),
1001
                }
1002
            }
1003
        }
83d5052b Andy McCall ↶ 1004
    }
1005
    let mut out: Vec<Contributor> = by.into_values().collect();
8933faff Andy McCall ↶ 1006
    for c in &mut out {
1007
        c.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
1008
    }
83d5052b Andy McCall ↶ 1009
    out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
1010
    out
1011
}
1012
1013
/// The language of a path for the languages bar: an extension table for
1014
/// what syntect lacks, then syntect; `None` for prose, data, lock files and
1015
/// vendored or generated paths, which Linguist leaves out too.
1016
pub fn language_of(path: &str) -> Option<&'static str> {
1017
    let lower = path.to_ascii_lowercase();
1018
    let name = lower.rsplit('/').next().unwrap_or(&lower);
1019
    let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"];
1020
    if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) {
1021
        return None;
1022
    }
1023
    if name.ends_with(".lock")
1024
        || name == "package-lock.json"
1025
        || name.ends_with(".min.js")
1026
        || name.ends_with(".min.css")
1027
        || name.ends_with(".d.ts")
1028
    {
1029
        return None;
1030
    }
1031
    let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
1032
    let by_ext = match ext {
1033
        "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"),
1034
        "toml" => Some("TOML"),
1035
        "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"),
1036
        "kdl" => Some("KDL"),
1037
        "sh" | "bash" | "zsh" => Some("Shell"),
1038
        "h" => Some("C"),
1039
        "hpp" | "hh" | "cc" | "cxx" => Some("C++"),
1040
        "vue" => Some("Vue"),
1041
        "svelte" => Some("Svelte"),
1042
        "zig" => Some("Zig"),
1043
        "nix" => Some("Nix"),
1044
        "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None,
1045
        _ => None,
1046
    };
1047
    if by_ext.is_some() {
1048
        return by_ext;
1049
    }
1050
    let lang = crate::render::highlight::language(path)?;
1051
    Some(match lang {
1052
        "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell",
1053
        "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None,
1054
        l => l,
1055
    })
1056
}
1057
1058
/// Linguist's colours for common languages; a stable colour otherwise.
1059
pub fn language_colour(name: &str) -> String {
1060
    let known = match name {
1061
        "Rust" => "#dea584",
1062
        "Python" => "#3572a5",
1063
        "Shell" => "#89e051",
1064
        "Makefile" => "#427819",
1065
        "C" => "#555555",
1066
        "C++" => "#f34b7d",
1067
        "C#" => "#178600",
1068
        "Assembly" => "#6e4c13",
1069
        "JavaScript" => "#f1e05a",
1070
        "TypeScript" => "#3178c6",
1071
        "HTML" => "#e34c26",
1072
        "CSS" => "#663399",
1073
        "Go" => "#00add8",
1074
        "Java" => "#b07219",
1075
        "TOML" => "#9c4221",
1076
        "YAML" => "#cb171e",
1077
        "SQL" => "#e38c00",
1078
        "Lua" => "#000080",
1079
        "Ruby" => "#701516",
1080
        "PHP" => "#4f5d95",
1081
        "Haskell" => "#5e5086",
1082
        "KDL" => "#ffb3b3",
1083
        "Dockerfile" => "#384d54",
1084
        "Vue" => "#41b883",
1085
        "Zig" => "#ec915c",
1086
        "Nix" => "#7e7eff",
1087
        _ => "",
1088
    };
1089
    if !known.is_empty() {
1090
        return known.to_string();
1091
    }
1092
    let h = blake3::hash(name.as_bytes());
1093
    let b = h.as_bytes();
1094
    format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2)
d23464c0 Andy McCall ↶ 1095
}
1096
83d5052b Andy McCall ↶ 1097
/// Languages of a state's files by bytes, largest first; under 1% folds into "Other".
1098
pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> {
1099
    let mut by: HashMap<&'static str, u64> = HashMap::new();
1100
    for (path, f) in &snapshot.files {
1101
        if let FileContent::Text { bytes, .. } = &f.content {
1102
            if let Some(l) = language_of(path) {
1103
                *by.entry(l).or_default() += bytes.len() as u64;
1104
            }
1105
        }
1106
    }
1107
    let total: u64 = by.values().sum();
1108
    if total == 0 {
1109
        return vec![];
1110
    }
1111
    let mut list: Vec<(&str, u64)> = by.into_iter().collect();
1112
    list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
1113
    let mut out: Vec<LanguageShare> = Vec::new();
1114
    let mut other = 0u64;
1115
    for (name, bytes) in list {
1116
        if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 {
1117
            other += bytes;
1118
        } else {
1119
            out.push(LanguageShare {
1120
                name: name.to_string(),
1121
                bytes,
1122
                percent: bytes as f64 * 100.0 / total as f64,
1123
                colour: language_colour(name),
1124
            });
1125
        }
1126
    }
1127
    if other > 0 {
1128
        out.push(LanguageShare {
1129
            name: "Other".into(),
1130
            bytes: other,
1131
            percent: other as f64 * 100.0 / total as f64,
1132
            colour: "#8592ad".into(),
1133
        });
1134
    }
1135
    out
1136
}
1137
d23464c0 Andy McCall ↶ 1138
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1139
pub enum PolicyBadge {
1140
    None,
1141
    Active,
1142
    Expired,
1143
}
1144
9ff27da5 Andy McCall ↶ 1145
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
39442b00 Andy McCall ↶ 1146
    let list = repo.bookmarks()?;
1147
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
d23464c0 Andy McCall ↶ 1148
    let mut out = Vec::new();
39442b00 Andy McCall ↶ 1149
    for (b, s) in list.iter().zip(briefs) {
d23464c0 Andy McCall ↶ 1150
        out.push(BookmarkView {
1151
            name: b.name.clone(),
1152
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
39442b00 Andy McCall ↶ 1153
            changes: s.changes,
d23464c0 Andy McCall ↶ 1154
            default: b.name == default,
2e640ffa Andy McCall ↶ 1155
            conflicted: s.conflicted,
1156
            latest_ms: s.latest_ms,
d23464c0 Andy McCall ↶ 1157
        });
1158
    }
1159
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
1160
    Ok(out)
1161
}
1162
1163
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
1164
    let mut out: Vec<TagView> = repo
1165
        .tags()?
1166
        .into_iter()
1167
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
1168
        .collect();
1169
    out.sort_by(|a, b| b.name.cmp(&a.name));
ba0a55bb Andy McCall ↶ 1170
    Ok(out)
1171
}
1172
1173
/// The tags withdrawn here, newest first.
1174
pub fn withdrawn_tags(repo: &Repo) -> Result<Vec<WithdrawnView>> {
1175
    let mut out: Vec<WithdrawnView> = repo
1176
        .remote_refs()?
1177
        .withdrawn
1178
        .into_iter()
1179
        .filter_map(|t| {
1180
            let sa = t.attestation?;
1181
            let oxy_core::attest::AttestBody::Untag { reason, .. } = &sa.attest.body else { return None };
1182
            Some(WithdrawnView {
1183
                name: t.name,
1184
                heads: t.heads.iter().map(|h| h.to_hex()).collect(),
1185
                reason: reason.clone(),
1186
                signer: sa.sigs.first().and_then(|s| repo.store().get_identity(&s.key).ok()).map(|i| i.name),
1187
                when_ms: sa.attest.hlc.wall_ms as i64,
1188
            })
1189
        })
1190
        .collect();
1191
    out.sort_by_key(|w| std::cmp::Reverse(w.when_ms));
d23464c0 Andy McCall ↶ 1192
    Ok(out)
1193
}
1194
1195
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
1196
    match repo.current_policy() {
1197
        Ok(Some((_, sp))) => {
1198
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
1199
                PolicyBadge::Expired
1200
            } else {
1201
                PolicyBadge::Active
1202
            }
1203
        }
1204
        _ => PolicyBadge::None,
1205
    }
1206
}
1207
ffb67a81 Andy McCall 1208
/// The overview of `shown` (a bookmark or tag; the default bookmark
1209
/// unless the viewer chose another, oxygenhub#191).
1210
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str, shown: &str) -> Result<Overview> {
351cf57e Andy McCall ↶ 1211
    let missing = || RefTarget { label: shown.into(), kind: RefKind::Bookmark, heads: vec![] };
1212
    let (target, standing_in) = match resolve(repo, cache, shown) {
1213
        Ok(t) => (t, None),
1214
        // No bookmark of the default's name: show main, or else the first
1215
        // bookmark, and say so, rather than an empty repository.
1216
        Err(_) if shown == default_bookmark => match stand_in(repo)? {
1217
            Some(b) => (resolve(repo, cache, &b)?, Some(b)),
1218
            None => (missing(), None),
1219
        },
1220
        Err(_) => (missing(), None),
d23464c0 Andy McCall ↶ 1221
    };
1222
    let heads = target.heads.len();
1223
    // One load of the default state serves the counts, the latest change
1224
    // and the tree (hub spec §16.3).
9ff27da5 Andy McCall ↶ 1225
    let loaded = cache.load(repo, &target.heads)?;
1226
    let state = &loaded.state;
1227
    let snapshot = &loaded.snapshot;
d23464c0 Andy McCall ↶ 1228
    let changes = state.len();
1229
    let conflicted = snapshot.is_conflicted();
1230
    let labels = head_labels(repo)?;
1231
    let latest = state
1232
        .changes()
1233
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
1234
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
9ff27da5 Andy McCall ↶ 1235
    let tree = tree_of(repo, target, snapshot, "")?;
d23464c0 Andy McCall ↶ 1236
    let license = tree
1237
        .entries
1238
        .iter()
1239
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
1240
        .map(|e| e.path.clone());
1241
    Ok(Overview {
1242
        tree,
1243
        changes,
1244
        heads,
9ff27da5 Andy McCall ↶ 1245
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
d23464c0 Andy McCall ↶ 1246
        tags: tags(repo)?,
1247
        latest,
1248
        conflicted,
1249
        license,
1250
        policy: policy_badge(repo),
83d5052b Andy McCall ↶ 1251
        contributors: contributors(repo, state),
1252
        languages: languages(snapshot),
351cf57e Andy McCall ↶ 1253
        standing_in,
d23464c0 Andy McCall ↶ 1254
    })
1255
}
1256
1257
// -------------------------------------------------------------- compare
1258
1259
#[derive(Clone, Debug)]
1260
pub struct Compare {
1261
    pub base: RefTarget,
1262
    pub head: RefTarget,
1263
    /// Changes in `head`'s state not in `base`'s.
1264
    pub added: Vec<ChangeView>,
1265
    /// Changes in `base`'s state not in `head`'s.
1266
    pub missing: usize,
1267
    pub files: Vec<FileDiff>,
1268
    pub bases: BTreeMap<String, Vec<u8>>,
1269
}
1270
9ff27da5 Andy McCall ↶ 1271
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
1272
    let base_loaded = cache.load(repo, &base.heads)?;
1273
    let head_loaded = cache.load(repo, &head.heads)?;
1274
    let base_state = &base_loaded.state;
1275
    let head_state = &head_loaded.state;
d23464c0 Andy McCall ↶ 1276
    let labels = head_labels(repo)?;
1277
    let mut added: Vec<ChangeView> = head_state
1278
        .changes()
1279
        .filter(|(h, _)| !base_state.contains(h))
1280
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
1281
        .collect();
1282
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
1283
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
9ff27da5 Andy McCall ↶ 1284
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
d23464c0 Andy McCall ↶ 1285
    Ok(Compare { base, head, added, missing, files, bases })
1286
}
1287
1288
// ------------------------------------------------------------ conflicts
1289
1290
#[derive(Clone, Debug)]
1291
pub struct ConflictView {
1292
    pub bookmark: String,
1293
    pub path: String,
1294
    pub kind: String,
1295
    /// The file rendered with `oxy` conflict markers, when a text file.
1296
    pub marked: Option<String>,
1297
    pub contributors: Vec<ChangeView>,
1298
}
1299
9ff27da5 Andy McCall ↶ 1300
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
39442b00 Andy McCall ↶ 1301
    let list = repo.bookmarks()?;
1302
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
d23464c0 Andy McCall ↶ 1303
    let mut out = Vec::new();
39442b00 Andy McCall ↶ 1304
    for (b, brief) in list.iter().zip(briefs) {
2e640ffa Andy McCall ↶ 1305
        // Only a conflicted state is loaded whole.
39442b00 Andy McCall ↶ 1306
        if !brief.conflicted {
2e640ffa Andy McCall ↶ 1307
            continue;
1308
        }
9ff27da5 Andy McCall ↶ 1309
        let loaded = cache.load(repo, &b.heads)?;
de505df5 Andy McCall ↶ 1310
        out.extend(conflicts_in(repo, &loaded, &b.name));
1311
    }
1312
    Ok(out)
1313
}
1314
1315
/// The conflicts of one loaded state, labelled with `bookmark`.
1316
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
1317
    let labels = head_labels(repo).unwrap_or_default();
1318
    let mut out = Vec::new();
1319
    {
1320
        let b_name = bookmark.to_string();
9ff27da5 Andy McCall ↶ 1321
        let state = &loaded.state;
1322
        let snapshot = &loaded.snapshot;
d23464c0 Andy McCall ↶ 1323
        for c in &snapshot.tree.conflicts {
9ff27da5 Andy McCall ↶ 1324
            let (path, kind) = describe_tree_conflict(snapshot, c);
de505df5 Andy McCall ↶ 1325
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
d23464c0 Andy McCall ↶ 1326
        }
1327
        for (path, f) in &snapshot.files {
1328
            if !f.is_conflicted() {
1329
                continue;
1330
            }
1331
            let (kind, marked, contributors) = match &f.content {
1332
                FileContent::Text { .. } => {
1333
                    let (bytes, _) = state.render_file(&f.node);
1334
                    let regions = state.conflict_regions(&f.node);
1335
                    let contributors: Vec<ChangeView> = regions
1336
                        .contributors
1337
                        .iter()
1338
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
1339
                        .collect();
1340
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
1341
                }
1342
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
1343
                FileContent::Dir => continue,
1344
            };
de505df5 Andy McCall ↶ 1345
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
d23464c0 Andy McCall ↶ 1346
        }
1347
    }
de505df5 Andy McCall ↶ 1348
    out
d23464c0 Andy McCall ↶ 1349
}
1350
1351
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
1352
    let by_node = snapshot.tree.by_node();
1353
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
1354
    match c {
fd958fbc Andy McCall ↶ 1355
        TreeConflict::Name { name, nodes, parent } => {
1356
            let path = if parent.is_root() { name.clone() } else { format!("{}/{name}", path_of(parent)) };
1357
            (path, format!("name: {} entries want this name", nodes.len()))
1358
        }
d23464c0 Andy McCall ↶ 1359
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
1360
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
1361
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
1362
        other => (String::new(), format!("{other:?}")),
1363
    }
1364
}
1365
1366
// ------------------------------------------------------------------ trust
1367
1368
#[derive(Clone, Debug)]
1369
pub struct KeyView {
1370
    pub key: String,
1371
    pub short: String,
1372
    pub name: String,
1373
    pub email: String,
1374
}
1375
1376
#[derive(Clone, Debug)]
1377
pub struct RuleView {
1378
    pub pattern: String,
1379
    pub keys: Vec<KeyView>,
1380
    pub threshold: u32,
1381
    pub require: String,
1382
    pub allow_conflicts: bool,
1383
}
1384
1385
#[derive(Clone, Debug)]
1386
pub struct PolicyView {
1387
    pub serial: u64,
1388
    pub expires_ms: u64,
1389
    pub expired: bool,
1390
    pub roots: Vec<KeyView>,
1391
    pub root_threshold: u32,
1392
    pub rules: Vec<RuleView>,
1393
    pub revoked: Vec<KeyView>,
1394
    pub signatures: usize,
1395
    pub history: usize,
1396
}
1397
1398
#[derive(Clone, Debug, Default)]
1399
pub struct Verification {
1400
    pub total: usize,
1401
    pub signed: usize,
1402
    pub sealed: usize,
1403
    pub unsigned: usize,
1404
    pub revoked: usize,
1405
    pub invalid: Vec<(String, String)>,
1406
}
1407
1408
#[derive(Clone, Debug)]
1409
pub struct Trust {
1410
    pub policy: Option<PolicyView>,
1411
    pub verification: Verification,
1412
    pub hub_key: String,
1413
    pub hub_delegated_by: Vec<KeyView>,
1414
}
1415
1416
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
1417
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
1418
    match found {
1419
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
1420
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
1421
    }
1422
}
1423
9ff27da5 Andy McCall ↶ 1424
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
d23464c0 Andy McCall ↶ 1425
    let heads = all_heads(repo)?;
9ff27da5 Andy McCall ↶ 1426
    let loaded = cache.load(repo, &heads)?;
1427
    let state = &loaded.state;
d23464c0 Andy McCall ↶ 1428
    let mut v = Verification::default();
1429
    for (h, _) in state.changes() {
1430
        v.total += 1;
1431
        match signature(repo, h) {
1432
            SigView::Unsigned => v.unsigned += 1,
1433
            SigView::Valid { sealed, revoked, .. } => {
1434
                if revoked {
1435
                    v.revoked += 1;
1436
                }
1437
                if sealed {
1438
                    v.sealed += 1
1439
                } else {
1440
                    v.signed += 1
1441
                }
1442
            }
1443
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1444
        }
1445
    }
1446
    Ok(v)
1447
}
1448
9ff27da5 Andy McCall ↶ 1449
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
d23464c0 Andy McCall ↶ 1450
    let policy = match repo.current_policy()? {
1451
        Some((_, sp)) => {
1452
            let p = &sp.policy;
1453
            let ids = &p.identities;
1454
            let require = |r: &oxy_core::policy::Require| match r {
1455
                oxy_core::policy::Require::Signed => "signed",
1456
                oxy_core::policy::Require::Sealed => "sealed",
1457
                oxy_core::policy::Require::Any => "any",
1458
            };
1459
            Some(PolicyView {
1460
                serial: p.serial,
1461
                expires_ms: p.expires,
1462
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
1463
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
1464
                root_threshold: p.root_threshold,
1465
                rules: p
1466
                    .rules
1467
                    .iter()
1468
                    .map(|r| RuleView {
1469
                        pattern: r.pattern.clone(),
1470
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
1471
                        threshold: r.threshold,
1472
                        require: require(&r.require).into(),
1473
                        allow_conflicts: r.allow_conflicts,
1474
                    })
1475
                    .collect(),
1476
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
1477
                signatures: sp.sigs.len(),
1478
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1479
            })
1480
        }
1481
        None => None,
1482
    };
1483
    // Who has delegated to the hub: every identity in the policy or store
1484
    // that lists the hub key.
1485
    let mut delegated = Vec::new();
1486
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
1487
        for i in &p.identities {
b43a9ab0 Andy McCall ↶ 1488
            if i.delegate(hub_key).is_some() {
d23464c0 Andy McCall ↶ 1489
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
1490
            }
1491
        }
1492
    }
9ff27da5 Andy McCall ↶ 1493
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
83d5052b Andy McCall ↶ 1494
}
1495
1496
#[cfg(test)]
1497
mod language_tests {
1498
    use super::*;
1499
1500
    #[test]
1501
    fn languages_are_detected_and_prose_is_left_out() {
1502
        assert_eq!(language_of("src/main.rs"), Some("Rust"));
1503
        assert_eq!(language_of("boot/start.s"), Some("Assembly"));
1504
        assert_eq!(language_of("build.sh"), Some("Shell"));
1505
        assert_eq!(language_of("Makefile"), Some("Makefile"));
1506
        assert_eq!(language_of("Cargo.toml"), Some("TOML"));
1507
        assert_eq!(language_of("README.md"), None);
1508
        assert_eq!(language_of("Cargo.lock"), None);
1509
        assert_eq!(language_of("web/node_modules/x/index.js"), None);
1510
        assert_eq!(language_of("vendor/lib.c"), None);
1511
        assert_eq!(language_colour("Rust"), "#dea584");
1512
        assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable");
1513
    }
6ae41081 Andy McCall ↶ 1514
}
1515
1516
#[cfg(test)]
1517
mod tests {
1518
    use super::*;
1519
1520
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
1521
        let mut m = BTreeMap::new();
1522
        for p in paths {
1523
            let mut end = 0;
1524
            let parts: Vec<&str> = p.split('/').collect();
1525
            for (i, part) in parts.iter().enumerate() {
1526
                end += part.len();
1527
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1528
                end += 1;
1529
            }
1530
        }
1531
        m
1532
    }
1533
1534
    #[test]
1535
    fn sidebar_expands_the_path_only() {
1536
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
1537
        let rows: Vec<(String, usize, bool, bool)> =
1538
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
1539
        let want = [
1540
            ("docs", 0, true, false),
1541
            ("src", 0, true, true),
1542
            ("src/lib", 1, true, true),
1543
            ("src/lib/a.rs", 2, false, false),
1544
            ("src/lib/b.rs", 2, false, true),
1545
            ("src/main.rs", 1, false, false),
1546
            ("README.md", 0, false, false),
1547
            ("Zeta.txt", 0, false, false),
1548
        ];
1549
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
1550
    }
1551
1552
    #[test]
1553
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1554
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
1555
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
1556
        let files = tree(&refs);
1557
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1558
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
1559
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
1560
        assert!(listed.last().unwrap().on_path);
1561
        let more = rows.iter().find(|e| e.more).unwrap();
1562
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
1563
    }
1564
1565
    #[test]
1566
    fn state_addresses_are_sorted_and_bounded() {
1567
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
1568
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
1569
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
1570
        assert_eq!(state_spec(&[]), None);
1571
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
1572
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
1573
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
1574
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
1575
    }
d23464c0 Andy McCall ↶ 1576
}