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