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