OXYGENHUB

Coverage / crates/hub/src/repos/view.rs 92.1%

982 of 1066 lines run, 175 of 355 functions · run #519 on main · run missed

1
//! Page-ready views of a repository, computed from `oxy-core` alone (hub
2
//! spec §1.4). Nothing here knows about HTTP or templates; every function
3
//! takes an open `Repo` and returns plain data.
4
5
use super::{RepoError, StateCache};
6
use oxy_core::hash::{ChangeHash, KeyId};
7
use oxy_core::objects::{Change, NodeKind};
8
use oxy_core::repo::{BlameLine, FileDiff, Repo, SignatureStatus};
9
use oxy_core::state::{FileContent, Snapshot};
10
use oxy_core::tree::TreeConflict;
11
use std::collections::{BTreeMap, BTreeSet, HashMap};
12
13
type Result<T> = std::result::Result<T, RepoError>;
14
152×
fn fail(msg: impl Into<String>) -> RepoError {
162×
    RepoError::Oxy(oxy_core::repo::RepoError::Msg(msg.into()))
172×
}
18
19
// ------------------------------------------------------------------ refs
20
21
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22
pub enum RefKind {
23
    Bookmark,
24
    Tag,
25
    Change,
26
}
27
28
/// What a `{ref}` path segment resolved to.
29
#[derive(Clone, Debug)]
30
pub struct RefTarget {
31
    /// The name as given (bookmark, tag) or the full hash.
32
    pub label: String,
33
    pub kind: RefKind,
34
    pub heads: Vec<ChangeHash>,
35
}
36
37
/// Most heads a state address or a "before this change" link carries.
38
pub const MAX_STATE_HEADS: usize = 32;
39
40
impl RefTarget {
41
    /// The label for a ref bar: the name, or `# abc123…` for a change,
42
    /// with `+N` for the further heads of a state.
4343×
    pub fn short_label(&self) -> String {
4443×
        match self.kind {
45
            RefKind::Change => {
465×
                let mut parts = self.label.split('+');
475×
                let first: String = parts.next().unwrap_or("").chars().take(12).collect();
485×
                match parts.count() {
492×
                    0 => first,
503×
                    n => format!("{first} +{n}"),
51
                }
52
            }
5338×
            _ => self.label.clone(),
54
        }
5543×
    }
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.
5917×
    pub fn permalink(&self) -> Option<String> {
6017×
        state_spec(&self.heads)
6117×
    }
62
}
63
64
/// Heads as a state address, sorted so one state has one address.
6532×
pub fn state_spec(heads: &[ChangeHash]) -> Option<String> {
6632×
    if heads.is_empty() || heads.len() > MAX_STATE_HEADS {
676×
        return None;
6826×
    }
6955×
    let mut hex: Vec<String> = heads.iter().map(|h| h.to_hex()).collect();
7026×
    hex.sort();
7126×
    hex.dedup();
7226×
    Some(hex.join("+"))
7332×
}
74
75
/// Resolve a bookmark name, a tag name, a change hash prefix, or a state
76
/// (full hashes joined with `+`).
77216×
pub fn resolve(repo: &Repo, cache: &StateCache, spec: &str) -> Result<RefTarget> {
78216×
    if spec.contains('+') {
793×
        let parts: Vec<&str> = spec.split('+').collect();
803×
        if parts.len() > MAX_STATE_HEADS {
810×
            return Err(fail(format!("a state address has at most {MAX_STATE_HEADS} heads")));
823×
        }
833×
        let mut heads = Vec::with_capacity(parts.len());
8410×
        for p in parts {
8510×
            match ChangeHash::from_hex(p) {
8610×
                Some(h) if p.len() == 64 && repo.store().has(&h) => heads.push(h),
870×
                _ => return Err(fail(format!("{p:?} is not a change of this repository"))),
88
            }
89
        }
903×
        heads.sort();
913×
        heads.dedup();
923×
        let label = state_spec(&heads).unwrap_or_default();
933×
        return Ok(RefTarget { label, kind: RefKind::Change, heads });
94213×
    }
95213×
    let view = repo.view()?;
96213×
    if let Some(heads) = view.bookmarks.get(spec).map(|st| repo.store().get_state(st).map(|s| s.heads)).transpose()? {
97204×
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Bookmark, heads });
989×
    }
999×
    if let Some(heads) = repo.tag_heads(spec)? {
1002×
        return Ok(RefTarget { label: spec.into(), kind: RefKind::Tag, heads });
1017×
    }
1027×
    let hash = resolve_change(repo, cache, spec)?;
1035×
    Ok(RefTarget { label: hash.to_hex(), kind: RefKind::Change, heads: vec![hash] })
104216×
}
105
106
/// The bookmark to show when the default bookmark does not exist: main,
107
/// else master, else the first by name; `None` without any.
1081×
fn stand_in(repo: &Repo) -> Result<Option<String>> {
1091×
    let view = repo.view()?;
1101×
    let names: Vec<&String> = view.bookmarks.keys().collect();
1111×
    Ok(["main", "master"]
1121×
        .iter()
1132×
        .find(|n| names.iter().any(|b| b == *n))
1141×
        .map(|n| n.to_string())
1151×
        .or_else(|| names.iter().min().map(|b| b.to_string())))
1161×
}
117
118
/// A change by full hash or unique hex prefix, searched over every
119
/// bookmark's state.
12023×
pub fn resolve_change(repo: &Repo, cache: &StateCache, spec: &str) -> Result<ChangeHash> {
12123×
    let spec = spec.trim_start_matches('#');
1221236×
    if spec.len() < 4 || !spec.chars().all(|c| c.is_ascii_hexdigit()) {
1232×
        return Err(fail(format!("{spec:?} is not a bookmark, tag or change of this repository")));
12421×
    }
12521×
    if let Some(h) = ChangeHash::from_hex(spec) {
12619×
        if repo.store().has(&h) {
12719×
            return Ok(h);
1280×
        }
1292×
    }
1302×
    let heads = all_heads(repo)?;
1312×
    let loaded = cache.load(repo, &heads)?;
1324×
    let matches: Vec<ChangeHash> = loaded.state.changes().map(|(h, _)| *h).filter(|h| h.starts_with_hex(spec)).collect();
1332×
    match matches.len() {
1342×
        1 => Ok(matches[0]),
1350×
        0 => Err(fail(format!("no change matches {spec:?}"))),
1360×
        _ => Err(fail(format!("{spec:?} is ambiguous"))),
137
    }
13823×
}
139
140
/// The heads of every bookmark, deduplicated.
14123×
pub fn all_heads(repo: &Repo) -> Result<Vec<ChangeHash>> {
14223×
    let mut set = BTreeSet::new();
14343×
    for b in repo.bookmarks()? {
14443×
        set.extend(b.heads);
14543×
    }
14623×
    Ok(set.into_iter().collect())
14723×
}
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,
158
    /// The hub account the key is linked to, filled by the web layer.
159
    pub account: Option<String>,
160
}
161
162472×
pub fn author(repo: &Repo, key: &KeyId, message: &str) -> AuthorView {
163472×
    if key.is_zero() {
164
        // Imported from Git: the trailer carries the author.
165152×
        let line = message.lines().rev().find_map(|l| l.strip_prefix("Git-Author: ")).unwrap_or("unknown");
166138×
        let (name, email) = match line.split_once('<') {
1670×
            Some((n, e)) => (n.trim().to_string(), e.trim_end_matches('>').trim().to_string()),
168138×
            None => (line.trim().to_string(), String::new()),
169
        };
170138×
        return AuthorView { name, email, key: String::new(), unknown: true, account: None };
171334×
    }
172334×
    match repo.store().get_identity(key) {
173334×
        Ok(id) => AuthorView { name: id.name, email: id.email, key: key.to_hex(), unknown: false, account: None },
1740×
        Err(_) => AuthorView { name: key.short(12), email: String::new(), key: key.to_hex(), unknown: true, account: None },
175
    }
176472×
}
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 {
18874×
    pub fn glyph(&self) -> &'static str {
18974×
        match self {
19022×
            SigView::Unsigned => "○",
1910×
            SigView::Valid { revoked: true, .. } => "⊘",
1920×
            SigView::Valid { sealed: true, .. } => "◈",
19352×
            SigView::Valid { .. } => "✔",
1940×
            SigView::Invalid(_) => "✘",
195
        }
19674×
    }
197
19874×
    pub fn class(&self) -> &'static str {
19974×
        match self {
20022×
            SigView::Unsigned => "sig-unsigned",
2010×
            SigView::Valid { revoked: true, .. } => "sig-revoked",
20252×
            SigView::Valid { .. } => "sig-valid",
2030×
            SigView::Invalid(_) => "sig-invalid",
204
        }
20574×
    }
206
20787×
    pub fn title(&self) -> String {
20887×
        match self {
20927×
            SigView::Unsigned => "unsigned".into(),
2100×
            SigView::Valid { name, sealed: true, revoked: false, .. } => format!("sealed by {name}"),
2110×
            SigView::Valid { name, revoked: true, .. } => format!("signed by {name}, key revoked"),
21260×
            SigView::Valid { name, .. } => format!("signed by {name}"),
2130×
            SigView::Invalid(why) => format!("INVALID: {why}"),
214
        }
21587×
    }
216
}
217
218421×
pub fn signature(repo: &Repo, hash: &ChangeHash) -> SigView {
219421×
    match repo.verify_change(hash) {
220184×
        Ok(SignatureStatus::Unsigned) => SigView::Unsigned,
221237×
        Ok(SignatureStatus::Valid { key, name, sealed, revoked, .. }) => SigView::Valid { key: key.to_hex(), name, sealed, revoked },
2220×
        Ok(SignatureStatus::Invalid(why)) => SigView::Invalid(why),
2230×
        Err(e) => SigView::Invalid(e.to_string()),
224
    }
225421×
}
226
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.
2464×
    pub fn delegation(&self) -> String {
2474×
        if self.revoked {
2480×
            return "delegation revoked".into();
2494×
        }
2504×
        match self.expires_ms {
2510×
            Some(e) => format!("delegate for {}, until {}", self.scope, when_utc(e)),
2524×
            None => format!("delegate for {}", self.scope),
253
        }
2544×
    }
255
256
    /// What hovering the badge says.
25729×
    pub fn title(&self) -> String {
25829×
        let until = match self.expires_ms {
2590×
            Some(e) => format!(", until {}", when_utc(e)),
26029×
            None => String::new(),
261
        };
26229×
        if self.revoked {
2630×
            format!("signed by {} as a delegate of the author; that delegation has since been revoked", self.name)
264
        } else {
26529×
            format!("signed by {} as a delegate of the author ({}{until}), key {}", self.name, self.scope, self.short)
266
        }
26729×
    }
268
}
269
270
/// `2026-10-04 20:12Z` for a wall time in milliseconds.
2710×
fn when_utc(ms: u64) -> String {
2720×
    time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000)
2730×
        .ok()
2740×
        .and_then(|t| t.format(&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]Z")).ok())
2750×
        .unwrap_or_else(|| ms.to_string())
2760×
}
277
278
/// The delegate that signed `hash` for the author, when one did.
279414×
pub fn via(repo: &Repo, author: &KeyId, sig: &SigView) -> Option<ViaView> {
280414×
    let SigView::Valid { key, name, revoked, .. } = sig else { return None };
281231×
    if author.is_zero() || *key == author.to_hex() {
282109×
        return None;
283122×
    }
284122×
    let signer = KeyId::from_hex(key)?;
285122×
    let entry = repo.store().get_identity(author).ok().and_then(|a| a.delegate(&signer).copied());
286122×
    let email = repo.store().get_identity(&signer).map(|i| i.email).unwrap_or_default();
287
    Some(ViaView {
288122×
        name: name.clone(),
289122×
        email,
290122×
        key: key.clone(),
291122×
        short: signer.short(12),
292122×
        scope: entry.map(|d| d.scope.to_string()).unwrap_or_else(|| "changes".into()),
293122×
        expires_ms: entry.and_then(|d| d.expires),
294122×
        revoked: *revoked || entry.is_none(),
295
    })
296414×
}
297
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,
311
    /// Signed for the author by a delegate (an agent), when it was.
312
    pub via: Option<ViaView>,
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
323414×
pub fn split_message(message: &str) -> (String, String) {
324414×
    let mut lines = message.lines();
325414×
    let title = lines.next().unwrap_or("").trim().to_string();
326414×
    let body = lines.collect::<Vec<_>>().join("\n").trim().to_string();
327414×
    (title, body)
328414×
}
329
330
/// Every bookmark and tag head, for labelling rows.
331368×
pub fn head_labels(repo: &Repo) -> Result<HashMap<ChangeHash, Vec<Label>>> {
332368×
    let mut out: HashMap<ChangeHash, Vec<Label>> = HashMap::new();
333972×
    for b in repo.bookmarks()? {
3342305×
        for h in b.heads {
3352305×
            out.entry(h).or_default().push(Label { name: b.name.clone(), kind: RefKind::Bookmark });
3362305×
        }
337
    }
338368×
    for t in repo.tags()? {
33932×
        for h in t.heads {
34032×
            out.entry(h).or_default().push(Label { name: t.name.clone(), kind: RefKind::Tag });
34132×
        }
342
    }
343368×
    Ok(out)
344368×
}
345
346235×
pub fn change_view_pub(
347235×
    repo: &Repo,
348235×
    hash: &ChangeHash,
349235×
    meta: &oxy_core::state::ChangeMeta,
350235×
    head: bool,
351235×
    labels: &HashMap<ChangeHash, Vec<Label>>,
352235×
) -> ChangeView {
353235×
    change_view(repo, hash, meta, head, labels)
354235×
}
355
356414×
fn change_view(
357414×
    repo: &Repo,
358414×
    hash: &ChangeHash,
359414×
    meta: &oxy_core::state::ChangeMeta,
360414×
    head: bool,
361414×
    labels: &HashMap<ChangeHash, Vec<Label>>,
362414×
) -> ChangeView {
363414×
    let (title, body) = split_message(&meta.message);
364414×
    let signature = signature(repo, hash);
365414×
    let via = via(repo, &meta.author, &signature);
366
    ChangeView {
367414×
        hash: hash.to_hex(),
368414×
        short: hash.short(12),
369414×
        title,
370414×
        body,
371414×
        author: author(repo, &meta.author, &meta.message),
372414×
        when_ms: meta.hlc.wall_ms,
373414×
        deps: meta.deps.iter().map(|d| d.to_hex()).collect(),
374414×
        head,
375414×
        resolution: meta.kind == oxy_core::objects::ChangeKind::Resolution,
376414×
        signature,
377414×
        via,
378414×
        labels: labels.get(hash).cloned().unwrap_or_default(),
379
    }
380414×
}
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.
39521×
pub fn history(repo: &Repo, cache: &StateCache, target: RefTarget, path: Option<&str>, offset: usize, limit: usize) -> Result<History> {
39621×
    let loaded = cache.load(repo, &target.heads)?;
39721×
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
39821×
    let mut entries: Vec<(ChangeHash, oxy_core::state::ChangeMeta)> = match path {
3997×
        Some(p) => {
4007×
            let Some(node) = loaded.snapshot.files.get(p).map(|f| f.node) else { return Err(fail(format!("{p} is not in that state"))) };
4017×
            loaded
4027×
                .state
4037×
                .changes()
40414×
                .filter(|(h, _)| {
405
                    // The skeleton says which nodes a change touches, without its text.
40614×
                    repo.store()
40714×
                        .get_change_lazy(h)
40814×
                        .map(|(c, _)| c.tree_ops.iter().any(|o| o.node() == node) || c.edits.iter().any(|x| x.node() == node))
40914×
                        .unwrap_or(false)
41014×
                })
4118×
                .map(|(h, m)| (*h, m.clone()))
4127×
                .collect()
413
        }
41452×
        None => loaded.state.changes().map(|(h, m)| (*h, m.clone())).collect(),
415
    };
416101×
    entries.sort_by(|a, b| b.1.hlc.cmp(&a.1.hlc).then(b.0.cmp(&a.0)));
41721×
    let total = entries.len();
41821×
    let labels = head_labels(repo)?;
41921×
    let window: Vec<ChangeView> =
42060×
        entries.iter().skip(offset).take(limit).map(|(h, m)| change_view(repo, h, m, head_set.contains(h), &labels)).collect();
42121×
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: path.map(String::from) })
42221×
}
423
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.
4284×
pub fn history_revset(repo: &Repo, cache: &StateCache, target: RefTarget, revset: &str, offset: usize, limit: usize) -> Result<History> {
4294×
    let loaded = cache.load(repo, &target.heads)?;
4304×
    let head_set: BTreeSet<ChangeHash> = loaded.state.heads().into_iter().collect();
4314×
    let selected = repo.revset_with_budget(revset, std::time::Duration::from_secs(2))?;
4322×
    let total = selected.hashes.len();
4332×
    let labels = head_labels(repo)?;
4342×
    let window: Vec<ChangeView> = selected
4352×
        .hashes
4362×
        .iter()
4372×
        .skip(offset)
4382×
        .take(limit)
4392×
        .filter_map(|h| selected.metas.get(h).map(|m| change_view(repo, h, m, head_set.contains(h), &labels)))
4402×
        .collect();
4412×
    Ok(History { target, entries: window, total, offset, has_more: offset + limit < total, path: None })
4424×
}
443
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
46017×
pub fn change(repo: &Repo, cache: &StateCache, hash: &ChangeHash) -> Result<ChangeDetail> {
46117×
    let c: Change = repo.store().get_change(hash)?;
46217×
    let labels = head_labels(repo)?;
46317×
    let heads = all_heads(repo)?;
46417×
    let loaded = cache.load(repo, &heads)?;
46517×
    let state = &loaded.state;
46617×
    let is_head = state.heads().contains(hash);
46717×
    let meta = oxy_core::state::ChangeMeta::of(&c);
46817×
    let view = change_view(repo, hash, &meta, is_head, &labels);
46917×
    let deps = c.deps.iter().filter_map(|d| state.get(d).map(|m| change_view(repo, d, m, state.heads().contains(d), &labels))).collect();
47017×
    let mut dependents: Vec<ChangeView> = state
47117×
        .changes()
47259×
        .filter(|(_, m)| m.deps.contains(hash))
47317×
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels))
47417×
        .collect();
47517×
    dependents.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
47617×
    let base = cache.load(repo, &c.deps)?;
47717×
    let files = crate::render::diff::change_files(&c, &base.state, &base.snapshot);
47817×
    let base_snapshot = &base.snapshot;
47917×
    let mut bases = BTreeMap::new();
48018×
    for f in &files {
48118×
        let old = f.from.as_deref().unwrap_or(&f.path);
48218×
        if let Some(FileContent::Text { bytes, .. }) = base_snapshot.files.get(old).map(|s| &s.content) {
4839×
            bases.insert(f.path.clone(), bytes.clone());
4849×
        }
485
    }
48617×
    let mut in_bookmarks = Vec::new();
48734×
    for b in repo.bookmarks()? {
48834×
        if cache.summary(repo, &b.heads)?.changes.contains(hash) {
48917×
            in_bookmarks.push(b.name);
49017×
        }
491
    }
49217×
    let mut in_tags = Vec::new();
49317×
    for t in repo.tags()? {
4942×
        if cache.summary(repo, &t.heads)?.changes.contains(hash) {
4952×
            in_tags.push(t.name);
4962×
        }
497
    }
49817×
    Ok(ChangeDetail { view, dependents, deps, files, bases, in_bookmarks, in_tags, atoms: c.edits.len(), tree_ops: c.tree_ops.len() })
49917×
}
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
53786×
pub fn crumbs(path: &str) -> Vec<(String, String)> {
53886×
    let mut out = Vec::new();
53986×
    let mut so_far = String::new();
54092×
    for part in path.split('/').filter(|p| !p.is_empty()) {
54139×
        if !so_far.is_empty() {
5426×
            so_far.push('/');
54333×
        }
54439×
        so_far.push_str(part);
54539×
        out.push((part.to_string(), so_far.clone()));
546
    }
54786×
    out
54886×
}
549
55062×
fn entry_of(path: &str, name: &str, f: &oxy_core::state::FileState) -> Entry {
55162×
    let kind = match f.kind {
55220×
        NodeKind::Dir => EntryKind::Dir,
55342×
        NodeKind::File => EntryKind::File,
5540×
        NodeKind::Symlink => EntryKind::Symlink,
5550×
        NodeKind::Subrepo => EntryKind::Subrepo,
556
    };
55762×
    let size = match &f.content {
55842×
        FileContent::Text { bytes, .. } => Some(bytes.len() as u64),
55920×
        _ => None,
560
    };
56162×
    Entry { name: name.to_string(), path: path.to_string(), kind, exec: f.mode.exec, size, conflicted: f.is_conflicted() }
56262×
}
563
564
/// The entries directly under `dir` (`""` for the root).
5654×
pub fn tree(repo: &Repo, cache: &StateCache, target: RefTarget, dir: &str) -> Result<Tree> {
5664×
    let loaded = cache.load(repo, &target.heads)?;
5674×
    tree_of(repo, target, &loaded.snapshot, dir)
5684×
}
569
57056×
pub fn tree_of(_repo: &Repo, target: RefTarget, snapshot: &Snapshot, dir: &str) -> Result<Tree> {
57156×
    let dir = dir.trim_matches('/');
57256×
    if !dir.is_empty() {
5733×
        match snapshot.files.get(dir) {
5742×
            Some(f) if f.kind == NodeKind::Dir => {}
5751×
            _ => return Err(RepoError::NotFound),
576
        }
57753×
    }
57855×
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
57955×
    let mut entries: Vec<Entry> = snapshot
58055×
        .files
58155×
        .iter()
58290×
        .filter(|(p, _)| p.starts_with(&prefix) && !p[prefix.len()..].contains('/'))
58362×
        .map(|(p, f)| entry_of(p, &p[prefix.len()..], f))
58455×
        .collect();
58555×
    entries.sort_by(|a, b| {
58639×
        (a.kind != EntryKind::Dir).cmp(&(b.kind != EntryKind::Dir)).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
58739×
    });
58855×
    let readme = entries
58955×
        .iter()
59059×
        .find(|e| {
59159×
            e.kind == EntryKind::File && matches!(e.name.to_lowercase().as_str(), "readme.md" | "readme" | "readme.txt" | "readme.markdown")
59259×
        })
59355×
        .and_then(|e| match &snapshot.files.get(&e.path)?.content {
59413×
            FileContent::Text { bytes, .. } => Some(Readme { path: e.path.clone(), text: String::from_utf8_lossy(bytes).into_owned() }),
5950×
            _ => None,
59613×
        });
59755×
    Ok(Tree { target, path: dir.to_string(), entries, crumbs: crumbs(dir), readme })
59856×
}
599
600
// ------------------------------------------------------------------- file
601
602
#[derive(Clone, Debug)]
603
pub enum FileBody {
604
    Text(String),
605
    Binary,
606
    TooLarge,
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).
62731×
pub fn sidebar(snapshot: &Snapshot, path: &str) -> Vec<SideEntry> {
62869×
    sidebar_in(&snapshot.files, |f| f.kind == NodeKind::Dir, path)
62931×
}
630
631
/// `sidebar` over any path map, given which values are directories.
63233×
pub fn sidebar_in<V>(files: &BTreeMap<String, V>, is_dir: impl Fn(&V) -> bool + Copy, path: &str) -> Vec<SideEntry> {
63333×
    let mut out = Vec::new();
63433×
    sidebar_dir(files, is_dir, "", path, 0, &mut out);
63533×
    out
63633×
}
637
63842×
fn sidebar_dir<V>(
63942×
    files: &BTreeMap<String, V>,
64042×
    is_dir: impl Fn(&V) -> bool + Copy,
64142×
    dir: &str,
64242×
    target: &str,
64342×
    depth: usize,
64442×
    out: &mut Vec<SideEntry>,
64542×
) {
64642×
    let prefix = if dir.is_empty() { String::new() } else { format!("{dir}/") };
64742×
    let mut children: Vec<(&str, bool)> = files
64842×
        .range(prefix.clone()..)
649612×
        .take_while(|(p, _)| p.starts_with(&prefix))
650611×
        .filter(|(p, _)| !p[prefix.len()..].contains('/'))
651328×
        .map(|(p, f)| (p.as_str(), is_dir(f)))
65242×
        .collect();
653294×
    children.sort_by(|a, b| (!a.1).cmp(&!b.1).then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase())));
65442×
    let total = children.len();
655328×
    for (i, (p, dir_entry)) in children.into_iter().enumerate() {
656328×
        let on_path = target == p || target.starts_with(&format!("{p}/"));
657
        // Past the limit, keep only the entry on the way to the file.
658328×
        if i >= SIDEBAR_PER_DIR && !on_path {
65949×
            continue;
660279×
        }
661279×
        out.push(SideEntry { name: p[prefix.len()..].to_string(), path: p.to_string(), depth, dir: dir_entry, on_path, more: false });
662279×
        if dir_entry && on_path && p != target {
6639×
            sidebar_dir(files, is_dir, p, target, depth + 1, out);
664270×
        }
665
    }
66642×
    if total > SIDEBAR_PER_DIR {
6671×
        out.push(SideEntry {
6681×
            name: format!("{} more", total - SIDEBAR_PER_DIR),
6691×
            path: dir.to_string(),
6701×
            depth,
6711×
            dir: true,
6721×
            on_path: false,
6731×
            more: true,
6741×
        });
67541×
    }
67642×
}
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>,
692
    pub sidebar: Vec<SideEntry>,
693
}
694
69533×
pub fn file(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<FileView> {
69633×
    let loaded = cache.load(repo, &target.heads)?;
69733×
    let snapshot = &loaded.snapshot;
69833×
    let path = path.trim_matches('/');
69933×
    let Some(f) = snapshot.files.get(path) else { return Err(RepoError::NotFound) };
70031×
    let (kind, bytes) = match (&f.kind, &f.content) {
7010×
        (NodeKind::Dir, _) => return Err(RepoError::NotFound),
7020×
        (NodeKind::Symlink, FileContent::Text { bytes, .. }) => (EntryKind::Symlink, bytes.clone()),
7030×
        (NodeKind::Subrepo, FileContent::Text { bytes, .. }) => (EntryKind::Subrepo, bytes.clone()),
70428×
        (_, FileContent::Text { bytes, .. }) => (EntryKind::File, bytes.clone()),
7053×
        (_, FileContent::Opaque { blobs }) => {
7063×
            let bytes = match blobs.first() {
7073×
                Some(b) => repo.read_blob(b)?,
7080×
                None => Vec::new(),
709
            };
7103×
            (EntryKind::File, bytes)
711
        }
7120×
        (_, FileContent::Dir) => return Err(RepoError::NotFound),
713
    };
71431×
    let size = bytes.len() as u64;
71531×
    let body = if size > render_limit {
7160×
        FileBody::TooLarge
71731×
    } else if is_binary(&bytes) {
7183×
        FileBody::Binary
719
    } else {
72028×
        FileBody::Text(String::from_utf8_lossy(&bytes).into_owned())
721
    };
72231×
    let labels = head_labels(repo)?;
72331×
    let last_change = last_change_of(repo, &loaded.state, &target.heads, path)
72431×
        .and_then(|h| loaded.state.get(&h).map(|meta| change_view(repo, &h, meta, loaded.state.heads().contains(&h), &labels)));
72531×
    let name = path.rsplit('/').next().unwrap_or(path).to_string();
72631×
    Ok(FileView {
72731×
        target,
72831×
        path: path.to_string(),
72931×
        name,
73031×
        crumbs: crumbs(path),
73131×
        kind,
73231×
        exec: f.mode.exec,
73331×
        size,
73431×
        body,
73531×
        conflicted: f.is_conflicted(),
73631×
        bytes,
73731×
        last_change,
73831×
        sidebar: sidebar(snapshot, path),
73931×
    })
74033×
}
741
742
/// A file's name and bytes, and nothing else (for raw responses).
74314×
pub fn raw(repo: &Repo, cache: &StateCache, target: &RefTarget, path: &str) -> Result<(String, Vec<u8>)> {
74414×
    let loaded = cache.load(repo, &target.heads)?;
74514×
    let path = path.trim_matches('/');
74614×
    let Some(f) = loaded.snapshot.files.get(path) else { return Err(RepoError::NotFound) };
74714×
    let bytes = match (&f.kind, &f.content) {
7480×
        (NodeKind::Dir, _) | (_, FileContent::Dir) => return Err(RepoError::NotFound),
74912×
        (_, FileContent::Text { bytes, .. }) => bytes.clone(),
7502×
        (_, FileContent::Opaque { blobs }) => match blobs.first() {
7512×
            Some(b) => repo.read_blob(b)?,
7520×
            None => Vec::new(),
753
        },
754
    };
75514×
    Ok((path.rsplit('/').next().unwrap_or(path).to_string(), bytes))
75614×
}
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).
76035×
fn state_path_key(tag: &[u8], heads: &[ChangeHash], path: &str) -> [u8; 32] {
76135×
    let mut sorted: Vec<&ChangeHash> = heads.iter().collect();
76235×
    sorted.sort();
76387×
    let joined: Vec<u8> = sorted.iter().flat_map(|h| h.to_hex().into_bytes()).collect();
76435×
    crate::render::cache::key(&[tag, &joined, path.as_bytes()])
76535×
}
766
767
struct Last(Option<ChangeHash>);
768
769
impl crate::render::cache::Weigh for Last {
77013×
    fn weight(&self) -> usize {
77113×
        64
77213×
    }
773
}
774
775
/// The newest change touching `path` in the state, from a cache of 4 MiB.
77631×
pub fn last_change_of(repo: &Repo, state: &oxy_core::state::State, heads: &[ChangeHash], path: &str) -> Option<ChangeHash> {
777
    static C: std::sync::OnceLock<crate::render::cache::Lru<Last>> = std::sync::OnceLock::new();
77831×
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(4 << 20));
77931×
    let key = state_path_key(b"last1", heads, path);
78031×
    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
78131×
}
782
783
struct BlameLines(Vec<BlameLine>);
784
785
impl crate::render::cache::Weigh for BlameLines {
7864×
    fn weight(&self) -> usize {
78713×
        self.0.iter().map(|l| l.text.len() + l.author.len() + 128).sum::<usize>() + 32
7884×
    }
789
}
790
791
/// `Repo::blame_in`, cached by state and path (64 MiB).
7924×
fn blame_cached(repo: &Repo, cache_state: &StateCache, heads: &[ChangeHash], path: &str) -> Result<Vec<BlameLine>> {
793
    static C: std::sync::OnceLock<crate::render::cache::Lru<BlameLines>> = std::sync::OnceLock::new();
7944×
    let cache = C.get_or_init(|| crate::render::cache::Lru::new(64 << 20));
7954×
    let key = state_path_key(b"blame1", heads, path);
7964×
    let mut failure = None;
7974×
    let lines = cache.get_or(key, || {
7984×
        match cache_state
7994×
            .load(repo, heads)
8004×
            .map_err(|e| oxy_core::repo::RepoError::Msg(e.to_string()))
8014×
            .and_then(|loaded| repo.blame_of(&loaded.state, &loaded.snapshot.tree, path))
802
        {
8034×
            Ok(l) => BlameLines(l),
8040×
            Err(e) => {
8050×
                failure = Some(e);
8060×
                BlameLines(Vec::new())
807
            }
808
        }
8094×
    });
8104×
    if let Some(e) = failure {
8110×
        return Err(RepoError::Oxy(e));
8124×
    }
8134×
    Ok(lines.0.clone())
8144×
}
815
816108×
pub fn is_binary(bytes: &[u8]) -> bool {
817108×
    let head = &bytes[..bytes.len().min(8192)];
818108×
    head.contains(&0)
819105×
        || std::str::from_utf8(head).is_err()
8200×
            && head.iter().filter(|b| **b < 0x20 && !matches!(**b, b'\n' | b'\r' | b'\t')).count() > head.len() / 20
821108×
}
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.
8261×
pub fn last_changes(repo: &Repo, cache: &StateCache, heads: &[ChangeHash], paths: &[String]) -> Result<Vec<(String, ChangeView)>> {
8271×
    let labels = head_labels(repo)?;
8281×
    let loaded = cache.load(repo, heads)?;
8291×
    let state = &loaded.state;
8301×
    let snapshot = &loaded.snapshot;
831
    // Newest change touching each node, from one pass over the log.
8321×
    let mut newest: HashMap<oxy_core::ids::NodeId, (ChangeHash, u64)> = HashMap::new();
8332×
    for e in repo.log_of(state) {
8342×
        let Ok((c, _)) = repo.store().get_change_lazy(&e.hash) else { continue };
8352×
        let when = e.change.hlc.wall_ms;
83611×
        for node in c.tree_ops.iter().map(|o| o.node()).chain(c.edits.iter().map(|x| x.node())) {
83711×
            newest.entry(node).or_insert((e.hash, when));
83811×
        }
839
    }
8401×
    let mut out = Vec::new();
8412×
    for p in paths {
8422×
        let Some(f) = snapshot.files.get(p) else { continue };
8432×
        let best = if f.kind == NodeKind::Dir {
8441×
            let prefix = format!("{p}/");
8451×
            snapshot
8461×
                .files
8471×
                .iter()
8485×
                .filter(|(q, _)| q.starts_with(&prefix))
8491×
                .filter_map(|(_, g)| newest.get(&g.node))
8501×
                .chain(newest.get(&f.node))
8511×
                .max_by_key(|(_, when)| *when)
8521×
                .copied()
853
        } else {
8541×
            newest.get(&f.node).copied()
855
        };
8562×
        if let Some((hash, _)) = best {
8572×
            if let Some(m) = state.get(&hash) {
8582×
                out.push((p.clone(), change_view(repo, &hash, m, state.heads().contains(&hash), &labels)));
8592×
            }
8600×
        }
861
    }
8621×
    Ok(out)
8631×
}
864
865
// ------------------------------------------------------------------ blame
866
867
#[derive(Clone, Debug)]
868
pub struct Blame {
869
    pub file: FileView,
870
    pub lines: Vec<BlameLine>,
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>>,
874
}
875
8764×
pub fn blame(repo: &Repo, cache: &StateCache, target: RefTarget, path: &str, render_limit: u64) -> Result<Blame> {
8774×
    let heads = target.heads.clone();
8784×
    let file = file(repo, cache, target, path, render_limit)?;
8794×
    let lines = blame_cached(repo, cache, &heads, path)?;
8804×
    let mut before = HashMap::new();
88113×
    for l in &lines {
88213×
        before.entry(l.hash).or_insert_with(|| repo.store().get_change_meta(&l.hash).ok().and_then(|c| state_spec(&c.deps)));
883
    }
8844×
    Ok(Blame { file, lines, before })
8854×
}
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
907
/// A tag withdrawn here (#301): the state it named, why, by whom and when.
908
#[derive(Clone, Debug)]
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)]
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,
928
    pub contributors: Vec<Contributor>,
929
    pub languages: Vec<LanguageShare>,
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>,
934
}
935
936
impl Overview {
937
    /// The sidebar's bookmarks (#152): the default first, then the most
938
    /// recently moved, ten in all.
93952×
    pub fn recent_bookmarks(&self) -> Vec<&BookmarkView> {
94052×
        let mut list: Vec<&BookmarkView> = self.bookmarks.iter().collect();
94152×
        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)));
94252×
        list.truncate(10);
94352×
        list
94452×
    }
945
}
946
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>,
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)>,
959
    /// The hub's own delegate key, filled by the web layer (#152).
960
    pub hub: bool,
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
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).
97552×
pub fn contributors(repo: &Repo, state: &oxy_core::state::State) -> Vec<Contributor> {
97652×
    let mut by: HashMap<String, Contributor> = HashMap::new();
97752×
    let mut names: HashMap<KeyId, String> = HashMap::new();
97856×
    for (hash, meta) in state.changes() {
97956×
        let a = author(repo, &meta.author, &meta.message);
98056×
        let id = if a.key.is_empty() { format!("git:{}", a.email.to_lowercase()) } else { a.key.clone() };
981
        // Unsigned changes with no Git author carry no name at all.
98256×
        let name =
98356×
            if a.key.is_empty() && a.email.is_empty() && a.name == "unknown" { "Unattributed changes".to_string() } else { a.name.clone() };
98456×
        let entry = by.entry(id).or_insert_with(|| Contributor {
98532×
            name,
98632×
            key: a.key.clone(),
987
            changes: 0,
98832×
            account: None,
98932×
            via: Vec::new(),
990
            hub: false,
99132×
        });
99256×
        entry.changes += 1;
99356×
        if !meta.author.is_zero() {
99436×
            let signer = repo.store().signatures(hash).ok().and_then(|s| s.first().map(|s| s.key)).filter(|k| *k != meta.author);
99536×
            if let Some(k) = signer {
99611×
                let who =
99711×
                    names.entry(k).or_insert_with(|| repo.store().get_identity(&k).map(|i| i.name).unwrap_or_else(|_| k.short(12))).clone();
99811×
                match entry.via.iter_mut().find(|(n, _)| *n == who) {
9999×
                    Some((_, n)) => *n += 1,
10002×
                    None => entry.via.push((who, 1)),
1001
                }
100225×
            }
100320×
        }
1004
    }
100552×
    let mut out: Vec<Contributor> = by.into_values().collect();
100652×
    for c in &mut out {
100732×
        c.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
1008
    }
100952×
    out.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
101052×
    out
101152×
}
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.
101666×
pub fn language_of(path: &str) -> Option<&'static str> {
101766×
    let lower = path.to_ascii_lowercase();
101866×
    let name = lower.rsplit('/').next().unwrap_or(&lower);
101966×
    let skip_dirs = ["vendor/", "node_modules/", "target/", "dist/", "third_party/", ".git/"];
1020387×
    if skip_dirs.iter().any(|d| lower.starts_with(d) || lower.contains(&format!("/{d}"))) {
10212×
        return None;
102264×
    }
102364×
    if name.ends_with(".lock")
102463×
        || name == "package-lock.json"
102563×
        || name.ends_with(".min.js")
102663×
        || name.ends_with(".min.css")
102763×
        || name.ends_with(".d.ts")
1028
    {
10291×
        return None;
103063×
    }
103163×
    let ext = name.rsplit_once('.').map(|(_, e)| e).unwrap_or("");
103263×
    let by_ext = match ext {
103363×
        "s" | "asm" | "a65" | "a80" | "z80" | "inc" | "65s" => Some("Assembly"),
103462×
        "toml" => Some("TOML"),
103561×
        "ts" | "tsx" | "mts" | "cts" => Some("TypeScript"),
103661×
        "kdl" => Some("KDL"),
103756×
        "sh" | "bash" | "zsh" => Some("Shell"),
103850×
        "h" => Some("C"),
103948×
        "hpp" | "hh" | "cc" | "cxx" => Some("C++"),
104048×
        "vue" => Some("Vue"),
104148×
        "svelte" => Some("Svelte"),
104248×
        "zig" => Some("Zig"),
104348×
        "nix" => Some("Nix"),
104448×
        "md" | "markdown" | "txt" | "rst" | "adoc" | "json" | "csv" | "svg" | "xml" => return None,
104515×
        _ => None,
1046
    };
104730×
    if by_ext.is_some() {
104815×
        return by_ext;
104915×
    }
105015×
    let lang = crate::render::highlight::language(path)?;
105112×
    Some(match lang {
105212×
        "Bourne Again Shell (bash)" | "Shell-Unix-Generic" => "Shell",
105312×
        "Plain Text" | "Markdown" | "MultiMarkdown" | "JSON" | "Git Ignore" | "Git Attributes" | "Git Config" => return None,
105412×
        l => l,
1055
    })
105666×
}
1057
1058
/// Linguist's colours for common languages; a stable colour otherwise.
105923×
pub fn language_colour(name: &str) -> String {
106023×
    let known = match name {
106123×
        "Rust" => "#dea584",
106215×
        "Python" => "#3572a5",
106315×
        "Shell" => "#89e051",
106410×
        "Makefile" => "#427819",
106510×
        "C" => "#555555",
10667×
        "C++" => "#f34b7d",
10677×
        "C#" => "#178600",
10687×
        "Assembly" => "#6e4c13",
10697×
        "JavaScript" => "#f1e05a",
10707×
        "TypeScript" => "#3178c6",
10717×
        "HTML" => "#e34c26",
10727×
        "CSS" => "#663399",
10737×
        "Go" => "#00add8",
10747×
        "Java" => "#b07219",
10757×
        "TOML" => "#9c4221",
10767×
        "YAML" => "#cb171e",
10777×
        "SQL" => "#e38c00",
10787×
        "Lua" => "#000080",
10797×
        "Ruby" => "#701516",
10807×
        "PHP" => "#4f5d95",
10817×
        "Haskell" => "#5e5086",
10827×
        "KDL" => "#ffb3b3",
10832×
        "Dockerfile" => "#384d54",
10842×
        "Vue" => "#41b883",
10852×
        "Zig" => "#ec915c",
10862×
        "Nix" => "#7e7eff",
10872×
        _ => "",
1088
    };
108923×
    if !known.is_empty() {
109021×
        return known.to_string();
10912×
    }
10922×
    let h = blake3::hash(name.as_bytes());
10932×
    let b = h.as_bytes();
10942×
    format!("#{:02x}{:02x}{:02x}", 64 + b[0] / 2, 64 + b[1] / 2, 64 + b[2] / 2)
109523×
}
1096
1097
/// Languages of a state's files by bytes, largest first; under 1% folds into "Other".
109852×
pub fn languages(snapshot: &Snapshot) -> Vec<LanguageShare> {
109952×
    let mut by: HashMap<&'static str, u64> = HashMap::new();
110079×
    for (path, f) in &snapshot.files {
110179×
        if let FileContent::Text { bytes, .. } = &f.content {
110257×
            if let Some(l) = language_of(path) {
110322×
                *by.entry(l).or_default() += bytes.len() as u64;
110435×
            }
110522×
        }
1106
    }
110752×
    let total: u64 = by.values().sum();
110852×
    if total == 0 {
110939×
        return vec![];
111013×
    }
111113×
    let mut list: Vec<(&str, u64)> = by.into_iter().collect();
111213×
    list.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
111313×
    let mut out: Vec<LanguageShare> = Vec::new();
111413×
    let mut other = 0u64;
111520×
    for (name, bytes) in list {
111620×
        if (bytes as f64) * 100.0 / (total as f64) < 1.0 || out.len() >= 8 {
11170×
            other += bytes;
111820×
        } else {
111920×
            out.push(LanguageShare {
112020×
                name: name.to_string(),
112120×
                bytes,
112220×
                percent: bytes as f64 * 100.0 / total as f64,
112320×
                colour: language_colour(name),
112420×
            });
112520×
        }
1126
    }
112713×
    if other > 0 {
11280×
        out.push(LanguageShare {
11290×
            name: "Other".into(),
11300×
            bytes: other,
11310×
            percent: other as f64 * 100.0 / total as f64,
11320×
            colour: "#8592ad".into(),
11330×
        });
113413×
    }
113513×
    out
113652×
}
1137
1138
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1139
pub enum PolicyBadge {
1140
    None,
1141
    Active,
1142
    Expired,
1143
}
1144
114572×
pub fn bookmarks(repo: &Repo, cache: &StateCache, default: &str) -> Result<Vec<BookmarkView>> {
114672×
    let list = repo.bookmarks()?;
114797×
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
114872×
    let mut out = Vec::new();
114997×
    for (b, s) in list.iter().zip(briefs) {
115097×
        out.push(BookmarkView {
115197×
            name: b.name.clone(),
1152103×
            heads: b.heads.iter().map(|h| h.to_hex()).collect(),
115397×
            changes: s.changes,
115497×
            default: b.name == default,
115597×
            conflicted: s.conflicted,
115697×
            latest_ms: s.latest_ms,
1157
        });
1158
    }
115972×
    out.sort_by(|a, b| b.default.cmp(&a.default).then_with(|| a.name.cmp(&b.name)));
116072×
    Ok(out)
116172×
}
1162
116384×
pub fn tags(repo: &Repo) -> Result<Vec<TagView>> {
116484×
    let mut out: Vec<TagView> = repo
116584×
        .tags()?
116684×
        .into_iter()
116784×
        .map(|t| TagView { name: t.name, heads: t.heads.iter().map(|h| h.to_hex()).collect(), message: t.message, signer: t.signer })
116884×
        .collect();
116984×
    out.sort_by(|a, b| b.name.cmp(&a.name));
117084×
    Ok(out)
117184×
}
1172
1173
/// The tags withdrawn here, newest first.
11749×
pub fn withdrawn_tags(repo: &Repo) -> Result<Vec<WithdrawnView>> {
11759×
    let mut out: Vec<WithdrawnView> = repo
11769×
        .remote_refs()?
1177
        .withdrawn
11789×
        .into_iter()
11799×
        .filter_map(|t| {
11804×
            let sa = t.attestation?;
11814×
            let oxy_core::attest::AttestBody::Untag { reason, .. } = &sa.attest.body else { return None };
1182
            Some(WithdrawnView {
11834×
                name: t.name,
11844×
                heads: t.heads.iter().map(|h| h.to_hex()).collect(),
11854×
                reason: reason.clone(),
11864×
                signer: sa.sigs.first().and_then(|s| repo.store().get_identity(&s.key).ok()).map(|i| i.name),
11874×
                when_ms: sa.attest.hlc.wall_ms as i64,
1188
            })
11894×
        })
11909×
        .collect();
11919×
    out.sort_by_key(|w| std::cmp::Reverse(w.when_ms));
11929×
    Ok(out)
11939×
}
1194
119552×
pub fn policy_badge(repo: &Repo) -> PolicyBadge {
119652×
    match repo.current_policy() {
11971×
        Ok(Some((_, sp))) => {
11981×
            if sp.policy.expires != 0 && (sp.policy.expires as i64) < crate::db::now_ms() {
11990×
                PolicyBadge::Expired
1200
            } else {
12011×
                PolicyBadge::Active
1202
            }
1203
        }
120451×
        _ => PolicyBadge::None,
1205
    }
120652×
}
1207
1208
/// The overview of `shown` (a bookmark or tag; the default bookmark
1209
/// unless the viewer chose another, oxygenhub#191).
121052×
pub fn overview(repo: &Repo, cache: &StateCache, default_bookmark: &str, shown: &str) -> Result<Overview> {
121152×
    let missing = || RefTarget { label: shown.into(), kind: RefKind::Bookmark, heads: vec![] };
121252×
    let (target, standing_in) = match resolve(repo, cache, shown) {
121351×
        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.
12161×
        Err(_) if shown == default_bookmark => match stand_in(repo)? {
12171×
            Some(b) => (resolve(repo, cache, &b)?, Some(b)),
12180×
            None => (missing(), None),
1219
        },
12200×
        Err(_) => (missing(), None),
1221
    };
122252×
    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).
122552×
    let loaded = cache.load(repo, &target.heads)?;
122652×
    let state = &loaded.state;
122752×
    let snapshot = &loaded.snapshot;
122852×
    let changes = state.len();
122952×
    let conflicted = snapshot.is_conflicted();
123052×
    let labels = head_labels(repo)?;
123152×
    let latest = state
123252×
        .changes()
123352×
        .max_by(|(ha, a), (hb, b)| a.hlc.cmp(&b.hlc).then(ha.cmp(hb)))
123452×
        .map(|(h, m)| change_view(repo, h, m, state.heads().contains(h), &labels));
123552×
    let tree = tree_of(repo, target, snapshot, "")?;
123652×
    let license = tree
123752×
        .entries
123852×
        .iter()
123959×
        .find(|e| matches!(e.name.to_lowercase().as_str(), "license" | "license.md" | "license.txt" | "licence" | "copying"))
124052×
        .map(|e| e.path.clone());
1241
    Ok(Overview {
124252×
        tree,
124352×
        changes,
124452×
        heads,
124552×
        bookmarks: bookmarks(repo, cache, default_bookmark)?,
124652×
        tags: tags(repo)?,
124752×
        latest,
124852×
        conflicted,
124952×
        license,
125052×
        policy: policy_badge(repo),
125152×
        contributors: contributors(repo, state),
125252×
        languages: languages(snapshot),
125352×
        standing_in,
1254
    })
125552×
}
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
12715×
pub fn compare(repo: &Repo, cache: &StateCache, base: RefTarget, head: RefTarget) -> Result<Compare> {
12725×
    let base_loaded = cache.load(repo, &base.heads)?;
12735×
    let head_loaded = cache.load(repo, &head.heads)?;
12745×
    let base_state = &base_loaded.state;
12755×
    let head_state = &head_loaded.state;
12765×
    let labels = head_labels(repo)?;
12775×
    let mut added: Vec<ChangeView> = head_state
12785×
        .changes()
12799×
        .filter(|(h, _)| !base_state.contains(h))
12805×
        .map(|(h, m)| change_view(repo, h, m, head_state.heads().contains(h), &labels))
12815×
        .collect();
12825×
    added.sort_by_key(|c| std::cmp::Reverse(c.when_ms));
12836×
    let missing = base_state.changes().filter(|(h, _)| !head_state.contains(h)).count();
12845×
    let (files, bases) = crate::render::diff::snapshot_diff(&base_loaded.snapshot, &head_loaded.snapshot);
12855×
    Ok(Compare { base, head, added, missing, files, bases })
12865×
}
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
13009×
pub fn conflicts(repo: &Repo, cache: &StateCache) -> Result<Vec<ConflictView>> {
13019×
    let list = repo.bookmarks()?;
130251×
    let briefs = cache.briefs(repo, &list.iter().map(|b| b.heads.clone()).collect::<Vec<_>>())?;
13039×
    let mut out = Vec::new();
130451×
    for (b, brief) in list.iter().zip(briefs) {
1305
        // Only a conflicted state is loaded whole.
130651×
        if !brief.conflicted {
130747×
            continue;
13084×
        }
13094×
        let loaded = cache.load(repo, &b.heads)?;
13104×
        out.extend(conflicts_in(repo, &loaded, &b.name));
1311
    }
13129×
    Ok(out)
13139×
}
1314
1315
/// The conflicts of one loaded state, labelled with `bookmark`.
131618×
pub fn conflicts_in(repo: &Repo, loaded: &super::cache::Loaded, bookmark: &str) -> Vec<ConflictView> {
131718×
    let labels = head_labels(repo).unwrap_or_default();
131818×
    let mut out = Vec::new();
1319
    {
132018×
        let b_name = bookmark.to_string();
132118×
        let state = &loaded.state;
132218×
        let snapshot = &loaded.snapshot;
132318×
        for c in &snapshot.tree.conflicts {
13244×
            let (path, kind) = describe_tree_conflict(snapshot, c);
13254×
            out.push(ConflictView { bookmark: b_name.clone(), path, kind, marked: None, contributors: vec![] });
13264×
        }
132770×
        for (path, f) in &snapshot.files {
132870×
            if !f.is_conflicted() {
132956×
                continue;
133014×
            }
133114×
            let (kind, marked, contributors) = match &f.content {
1332
                FileContent::Text { .. } => {
133310×
                    let (bytes, _) = state.render_file(&f.node);
133410×
                    let regions = state.conflict_regions(&f.node);
133510×
                    let contributors: Vec<ChangeView> = regions
133610×
                        .contributors
133710×
                        .iter()
133820×
                        .filter_map(|h| state.get(h).map(|m| change_view(repo, h, m, state.heads().contains(h), &labels)))
133910×
                        .collect();
134010×
                    ("lines".to_string(), Some(String::from_utf8_lossy(&bytes).into_owned()), contributors)
1341
                }
13424×
                FileContent::Opaque { blobs } => (format!("replace ({} candidates)", blobs.len()), None, vec![]),
13430×
                FileContent::Dir => continue,
1344
            };
134514×
            out.push(ConflictView { bookmark: b_name.clone(), path: path.clone(), kind, marked, contributors });
1346
        }
1347
    }
134818×
    out
134918×
}
1350
13514×
fn describe_tree_conflict(snapshot: &Snapshot, c: &TreeConflict) -> (String, String) {
13524×
    let by_node = snapshot.tree.by_node();
13534×
    let path_of = |n: &oxy_core::ids::NodeId| by_node.get(n).map(|e| e.path.clone()).unwrap_or_else(|| n.short(8));
13544×
    match c {
13554×
        TreeConflict::Name { name, nodes, parent } => {
13564×
            let path = if parent.is_root() { name.clone() } else { format!("{}/{name}", path_of(parent)) };
13574×
            (path, format!("name: {} entries want this name", nodes.len()))
1358
        }
13590×
        TreeConflict::MultiPlacement { node, placements } => (path_of(node), format!("placement: {} places", placements.len())),
13600×
        TreeConflict::Orphan { node, .. } => (path_of(node), "orphan: parent directory was removed".into()),
13610×
        TreeConflict::Cycle { node } => (path_of(node), "cycle: directory moved into itself".into()),
13620×
        other => (String::new(), format!("{other:?}")),
1363
    }
13644×
}
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
14162×
fn key_view(repo: &Repo, ids: &[oxy_core::identity::Identity], key: &KeyId) -> KeyView {
14174×
    let found = ids.iter().find(|i| i.hash() == *key).cloned().or_else(|| repo.store().get_identity(key).ok());
14182×
    match found {
14192×
        Some(i) => KeyView { key: key.to_hex(), short: key.short(12), name: i.name, email: i.email },
14200×
        None => KeyView { key: key.to_hex(), short: key.short(12), name: String::new(), email: String::new() },
1421
    }
14222×
}
1423
14244×
pub fn verification(repo: &Repo, cache: &StateCache) -> Result<Verification> {
14254×
    let heads = all_heads(repo)?;
14264×
    let loaded = cache.load(repo, &heads)?;
14274×
    let state = &loaded.state;
14284×
    let mut v = Verification::default();
14297×
    for (h, _) in state.changes() {
14307×
        v.total += 1;
14317×
        match signature(repo, h) {
14321×
            SigView::Unsigned => v.unsigned += 1,
14336×
            SigView::Valid { sealed, revoked, .. } => {
14346×
                if revoked {
14350×
                    v.revoked += 1;
14366×
                }
14376×
                if sealed {
14380×
                    v.sealed += 1
1439
                } else {
14406×
                    v.signed += 1
1441
                }
1442
            }
14430×
            SigView::Invalid(why) => v.invalid.push((h.to_hex(), why)),
1444
        }
1445
    }
14464×
    Ok(v)
14474×
}
1448
14493×
pub fn trust(repo: &Repo, cache: &StateCache, hub_key: &KeyId) -> Result<Trust> {
14503×
    let policy = match repo.current_policy()? {
14511×
        Some((_, sp)) => {
14521×
            let p = &sp.policy;
14531×
            let ids = &p.identities;
14541×
            let require = |r: &oxy_core::policy::Require| match r {
14550×
                oxy_core::policy::Require::Signed => "signed",
14560×
                oxy_core::policy::Require::Sealed => "sealed",
14571×
                oxy_core::policy::Require::Any => "any",
14581×
            };
1459
            Some(PolicyView {
14601×
                serial: p.serial,
14611×
                expires_ms: p.expires,
14621×
                expired: p.expires != 0 && (p.expires as i64) < crate::db::now_ms(),
14631×
                roots: p.roots.iter().map(|k| key_view(repo, ids, k)).collect(),
14641×
                root_threshold: p.root_threshold,
14651×
                rules: p
14661×
                    .rules
14671×
                    .iter()
14681×
                    .map(|r| RuleView {
14691×
                        pattern: r.pattern.clone(),
14701×
                        keys: r.keys.iter().map(|k| key_view(repo, ids, k)).collect(),
14711×
                        threshold: r.threshold,
14721×
                        require: require(&r.require).into(),
14731×
                        allow_conflicts: r.allow_conflicts,
14741×
                    })
14751×
                    .collect(),
14761×
                revoked: p.revoked.iter().map(|k| key_view(repo, ids, k)).collect(),
14771×
                signatures: sp.sigs.len(),
14781×
                history: repo.policy_history().map(|h| h.len()).unwrap_or(0),
1479
            })
1480
        }
14812×
        None => None,
1482
    };
1483
    // Who has delegated to the hub: every identity in the policy or store
1484
    // that lists the hub key.
14853×
    let mut delegated = Vec::new();
14863×
    if let Some(p) = repo.current_policy()?.map(|(_, sp)| sp.policy) {
14872×
        for i in &p.identities {
14882×
            if i.delegate(hub_key).is_some() {
14891×
                delegated.push(KeyView { key: i.hash().to_hex(), short: i.hash().short(12), name: i.name.clone(), email: i.email.clone() });
14901×
            }
1491
        }
14922×
    }
14933×
    Ok(Trust { policy, verification: verification(repo, cache)?, hub_key: hub_key.to_hex(), hub_delegated_by: delegated })
14943×
}
1495
1496
#[cfg(test)]
1497
mod language_tests {
1498
    use super::*;
1499
1500
    #[test]
15011×
    fn languages_are_detected_and_prose_is_left_out() {
15021×
        assert_eq!(language_of("src/main.rs"), Some("Rust"));
15031×
        assert_eq!(language_of("boot/start.s"), Some("Assembly"));
15041×
        assert_eq!(language_of("build.sh"), Some("Shell"));
15051×
        assert_eq!(language_of("Makefile"), Some("Makefile"));
15061×
        assert_eq!(language_of("Cargo.toml"), Some("TOML"));
15071×
        assert_eq!(language_of("README.md"), None);
15081×
        assert_eq!(language_of("Cargo.lock"), None);
15091×
        assert_eq!(language_of("web/node_modules/x/index.js"), None);
15101×
        assert_eq!(language_of("vendor/lib.c"), None);
15111×
        assert_eq!(language_colour("Rust"), "#dea584");
15121×
        assert_eq!(language_colour("Befunge"), language_colour("Befunge"), "stable");
15131×
    }
1514
}
1515
1516
#[cfg(test)]
1517
mod tests {
1518
    use super::*;
1519
15202×
    fn tree(paths: &[&str]) -> BTreeMap<String, bool> {
15212×
        let mut m = BTreeMap::new();
1522256×
        for p in paths {
1523256×
            let mut end = 0;
1524256×
            let parts: Vec<&str> = p.split('/').collect();
1525512×
            for (i, part) in parts.iter().enumerate() {
1526512×
                end += part.len();
1527512×
                m.insert(p[..end].to_string(), i + 1 < parts.len());
1528512×
                end += 1;
1529512×
            }
1530
        }
15312×
        m
15322×
    }
1533
1534
    #[test]
15351×
    fn sidebar_expands_the_path_only() {
15361×
        let files = tree(&["README.md", "src/main.rs", "src/lib/a.rs", "src/lib/b.rs", "docs/guide.md", "Zeta.txt"]);
15371×
        let rows: Vec<(String, usize, bool, bool)> =
15388×
            sidebar_in(&files, |d| *d, "src/lib/b.rs").into_iter().map(|e| (e.path, e.depth, e.dir, e.on_path)).collect();
15391×
        let want = [
15401×
            ("docs", 0, true, false),
15411×
            ("src", 0, true, true),
15421×
            ("src/lib", 1, true, true),
15431×
            ("src/lib/a.rs", 2, false, false),
15441×
            ("src/lib/b.rs", 2, false, true),
15451×
            ("src/main.rs", 1, false, false),
15461×
            ("README.md", 0, false, false),
15471×
            ("Zeta.txt", 0, false, false),
15481×
        ];
15498×
        assert_eq!(rows, want.iter().map(|(p, d, dir, on)| (p.to_string(), *d, *dir, *on)).collect::<Vec<_>>());
15501×
    }
1551
1552
    #[test]
15531×
    fn sidebar_cuts_long_directories_but_keeps_the_file() {
1554250×
        let names: Vec<String> = (0..250).map(|i| format!("big/f{i:03}.txt")).collect();
15551×
        let refs: Vec<&str> = names.iter().map(String::as_str).collect();
15561×
        let files = tree(&refs);
15571×
        let rows = sidebar_in(&files, |d| *d, "big/f240.txt");
1558203×
        let listed: Vec<&SideEntry> = rows.iter().filter(|e| e.depth == 1 && !e.more).collect();
15591×
        assert_eq!(listed.len(), SIDEBAR_PER_DIR + 1, "the limit plus the file itself");
15601×
        assert!(listed.last().unwrap().on_path);
15611×
        let more = rows.iter().find(|e| e.more).unwrap();
15621×
        assert_eq!((more.name.as_str(), more.path.as_str()), ("50 more", "big"));
15631×
    }
1564
1565
    #[test]
15661×
    fn state_addresses_are_sorted_and_bounded() {
15671×
        let a = ChangeHash::from_hex(&"a".repeat(64)).unwrap();
15681×
        let b = ChangeHash::from_hex(&"b".repeat(64)).unwrap();
15691×
        assert_eq!(state_spec(&[b, a, b]).unwrap(), format!("{}+{}", "a".repeat(64), "b".repeat(64)));
15701×
        assert_eq!(state_spec(&[]), None);
15711×
        assert_eq!(state_spec(&vec![a; MAX_STATE_HEADS + 1]), None);
15721×
        let t = RefTarget { label: state_spec(&[a, b]).unwrap(), kind: RefKind::Change, heads: vec![a, b] };
15731×
        assert_eq!(t.short_label(), format!("{} +1", "a".repeat(12)));
15741×
        assert_eq!(RefTarget { label: "main".into(), kind: RefKind::Bookmark, heads: vec![a] }.short_label(), "main");
15751×
    }
1576
}