OXYGENHUB

Coverage / crates/hub/src/web/repo.rs 92.1%

373 of 405 lines run, 51 of 127 functions · run #537 on main · run missed

1
//! Repository overview, tree, file, raw and blame pages.
2
3
use super::{filters, lookup, Error, Page, RepoShell, Shell};
4
use crate::auth::Viewer;
5
use crate::render::{self, highlight};
6
use crate::repos::view::{self, EntryKind, FileBody};
7
use crate::Shared;
8
use askama::Template;
9
use axum::extract::{Path, Query, State};
10
use axum::response::{IntoResponse, Response};
11
use serde::Deserialize;
12
use std::collections::HashMap;
13
14
#[derive(Template)]
15
#[template(path = "overview.html")]
16
pub struct OverviewPage {
17
    shell: Shell,
18
    repo: RepoShell,
19
    o: view::Overview,
20
    readme_html: Option<String>,
21
    watching: bool,
22
    latest_release: Option<crate::db::releases::Release>,
23
    /// Set while the repository has no changes (hub spec §6).
24
    quickstart: Option<Quickstart>,
25
    fork: super::forks::ForkInfo,
26
    starred: bool,
27
    stars: i64,
28
    watchers: i64,
29
    topics: Vec<String>,
30
    /// Repositories that pin this one as a subrepo, and how far behind
31
    /// each is (Diffusion, #148).
32
    used_by: Vec<crate::diffusion::Consumer>,
33
    /// The upstreams it pins, with its status there (#150).
34
    follows: Vec<(crate::db::repos::RepoRow, crate::diffusion::Consumer)>,
35
    /// The bookmark or tag shown: the default unless `?at=` chose another
36
    /// (#191).
37
    at: String,
38
}
39
40
#[derive(Deserialize)]
41
pub struct OverviewQuery {
42
    at: Option<String>,
43
}
44
45
/// A remote name from the hub's host: its first label when that is a
46
/// plain lowercase word (`earth` for `https://earth.example.org:7343`),
47
/// otherwise `hub`.
4829×
fn remote_name(base_url: &str) -> String {
4929×
    let host = base_url.split("://").nth(1).unwrap_or("").split(['/', ':']).next().unwrap_or("");
5029×
    let first = host.split('.').next().unwrap_or("");
5129×
    let plain = first.len() <= 20
5229×
        && first.starts_with(|c: char| c.is_ascii_lowercase())
5320×
        && first.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
5429×
    if plain && first != "www" && first != "localhost" {
552×
        first.to_string()
56
    } else {
5727×
        "hub".to_string()
58
    }
5929×
}
60
61
/// The commands that get a first push into an empty repository, filled
62
/// in for this hub and this repository.
63
pub struct Quickstart {
64
    /// A remote name taken from the hub's host name (`earth` for
65
    /// `earth.example.org`), `hub` when that is not a plain word.
66
    pub remote: String,
67
    /// Where to download the hub's certificate, when it is self-signed.
68
    pub ca_url: Option<String>,
69
    /// Where the commands save that certificate.
70
    pub ca_file: String,
71
    /// Whether the viewer may push here.
72
    pub can_push: bool,
73
}
74
75
impl Quickstart {
7623×
    pub fn new(app: &Shared, can_push: bool) -> Quickstart {
7723×
        let base = app.config.base_url().trim_end_matches('/').to_string();
7823×
        let remote = remote_name(&base);
7923×
        let ca_file = format!("~/.config/oxy/{remote}-ca.pem");
8023×
        let ca_url = app.config.tls.self_signed.then(|| format!("{base}/.well-known/oxyhub-ca.pem"));
8123×
        Quickstart { remote, ca_url, ca_file, can_push }
8223×
    }
83
84
    /// Connect a checkout to this repository and push; the token line
85
    /// stays a placeholder so no secret is ever printed.
8611×
    pub fn connect(&self, clone_url: &str) -> String {
8711×
        let r = &self.remote;
8811×
        let mut s = format!("oxy remote add {r} {clone_url}\n");
8911×
        if let Some(ca) = &self.ca_url {
900×
            s += &format!("curl -fsSL {ca} -o {}\n", self.ca_file);
910×
            s += &format!("oxy config remote.{r}.ca {}\n", self.ca_file);
9211×
        }
9311×
        s += &format!("oxy config remote.{r}.token YOUR-TOKEN\n");
9411×
        s += &format!("oxy push {r}");
9511×
        s
9611×
    }
97
98
    /// Start a repository from nothing.
9910×
    pub fn fresh(&self, name: &str) -> String {
10010×
        format!("mkdir {name} && cd {name}\noxy init\necho \"# {name}\" > README.md\noxy commit -m \"First change\"")
10110×
    }
102
103
    /// Bring a Git branch across.
10410×
    pub fn git_import(&self, name: &str) -> String {
10510×
        format!("oxy git import --branch main path/to/git-checkout {name}\ncd {name}")
10610×
    }
107
}
108
10957×
pub async fn overview(
11057×
    State(app): State<Shared>,
11157×
    viewer: Viewer,
11257×
    Path((owner, name)): Path<(String, String)>,
11357×
    Query(q): Query<OverviewQuery>,
11457×
) -> Result<Page<OverviewPage>, Error> {
11557×
    let shell = Shell::new(&app, &format!("/{owner}/{name}"), &viewer);
11657×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
11753×
    let default = row.default_bookmark.clone();
11853×
    let at = q.at.map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).unwrap_or_else(|| default.clone());
11953×
    let shown = at.clone();
12053×
    let mut o = app
12153×
        .repos
12253×
        .read(&repo, move |r, cache| view::overview(r, cache, &default, &shown))
12353×
        .await
12453×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
125
    // Contributors link to the hub accounts their keys are linked to.
12653×
    let linked: HashMap<String, String> = crate::db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
12753×
    let hub_key = app.hub_key.key.to_hex();
12853×
    for c in &mut o.contributors {
12933×
        c.account = linked.get(&c.key).cloned();
13033×
        c.hub = c.key == hub_key;
13133×
    }
13253×
    if let Some(c) = o.latest.as_mut() {
13331×
        c.author.account = linked.get(&c.author.key).cloned();
13431×
    }
135
    // One row per account: a person's keys over time are one contributor,
136
    // their agents' shares summed beneath (as `oxy log` shows via).
13753×
    let mut merged: Vec<view::Contributor> = Vec::new();
13853×
    for c in std::mem::take(&mut o.contributors) {
13933×
        match c.account.as_ref().and_then(|a| merged.iter_mut().find(|m| m.account.as_deref() == Some(a))) {
1402×
            Some(m) => {
1412×
                m.changes += c.changes;
1422×
                for (who, n) in c.via {
1430×
                    match m.via.iter_mut().find(|(w, _)| *w == who) {
1440×
                        Some((_, k)) => *k += n,
1450×
                        None => m.via.push((who, n)),
146
                    }
147
                }
1482×
                m.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
149
            }
15031×
            None => merged.push(c),
151
        }
152
    }
15353×
    merged.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
15453×
    o.contributors = merged;
15553×
    let rs = RepoShell::new(&app, &row, "code").with_role(role).with_sky(&app, &row).await;
15653×
    let readme_html = o.readme_html(&rs, &o.tree.target.label);
15753×
    let watching = match viewer.account() {
15827×
        Some(a) => crate::db::notify::watching(&app.db, a.id, row.id).await.unwrap_or(false),
15926×
        None => false,
160
    };
16153×
    let latest_release = crate::db::releases::latest(&app.db, row.id).await.ok().flatten();
16253×
    let quickstart = (o.changes == 0).then(|| Quickstart::new(&app, rs.can(crate::auth::Access::Write)));
16353×
    let fork = super::forks::info(&app, &shell, &viewer, &row).await;
16453×
    let starred = match viewer.account() {
16527×
        Some(a) => crate::db::repos::starred(&app.db, a.id, row.id).await.unwrap_or(false),
16626×
        None => false,
167
    };
16853×
    let (stars, watchers) = crate::db::repos::counts(&app.db, row.id).await.unwrap_or((0, 0));
16953×
    let topics = row.topic_list().into_iter().map(String::from).collect();
17053×
    let used_by = crate::diffusion::consumers(&app, &row, viewer.account()).await.unwrap_or_default();
17153×
    let follows = crate::diffusion::follows(&app, &row, viewer.account()).await;
17253×
    Ok(Page(OverviewPage {
17353×
        shell,
17453×
        repo: rs,
17553×
        o,
17653×
        readme_html,
17753×
        watching,
17853×
        latest_release,
17953×
        quickstart,
18053×
        fork,
18153×
        starred,
18253×
        stars,
18353×
        watchers,
18453×
        topics,
18553×
        used_by,
18653×
        follows,
18753×
        at,
18853×
    }))
18957×
}
190
191
impl view::Overview {
19253×
    fn readme_html(&self, rs: &RepoShell, r: &str) -> Option<String> {
19353×
        self.tree.readme.as_ref().map(|md| {
19413×
            let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
19513×
            render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
19613×
        })
19753×
    }
198
}
199
200
#[derive(Template)]
201
#[template(path = "tree.html")]
202
pub struct TreePage {
203
    shell: Shell,
204
    repo: RepoShell,
205
    t: view::Tree,
206
    readme_html: Option<String>,
207
}
208
2092×
pub async fn tree_root(Path((owner, name, r)): Path<(String, String, String)>) -> Response {
210
    // A bookmark's or tag's root is the overview with it chosen, side bar
211
    // and all (#191).
2122×
    axum::response::Redirect::to(&format!("/{owner}/{name}?at={}", super::settings::urlencode(&r))).into_response()
2132×
}
214
2153×
pub async fn tree(
2163×
    State(app): State<Shared>,
2173×
    viewer: Viewer,
2183×
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
2193×
) -> Result<Page<TreePage>, Error> {
2203×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tree/{r}/{path}"), &viewer);
2213×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
2223×
    let (spec, dir) = (r.clone(), path.clone());
2233×
    let t = app
2243×
        .repos
2253×
        .read(&repo, move |repo, cache| {
2263×
            let target = view::resolve(repo, cache, &spec)?;
2273×
            view::tree(repo, cache, target, &dir)
2283×
        })
2293×
        .await
2303×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
2312×
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
2322×
    let readme_html = t.readme.as_ref().map(|md| {
2330×
        let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
2340×
        render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
2350×
    });
2362×
    Ok(Page(TreePage { shell, repo: rs, t, readme_html }))
2373×
}
238
239
#[derive(Deserialize)]
240
pub struct FileQuery {
241
    plain: Option<String>,
242
    blame: Option<String>,
243
    /// `source` shows a Markdown file's text instead of rendering it.
244
    view: Option<String>,
245
}
246
247
#[derive(Template)]
248
#[template(path = "file.html")]
249
pub struct FilePage {
250
    shell: Shell,
251
    repo: RepoShell,
252
    f: view::FileView,
253
    /// Highlighted lines when text.
254
    lines: Vec<String>,
255
    language: Option<&'static str>,
256
    markdown_html: Option<String>,
257
    is_image: bool,
258
    is_markdown: bool,
259
    blame: Option<Vec<BlameRow>>,
260
    /// The `{ref}` of this state for good (hub spec §6.6).
261
    permalink: Option<String>,
262
    /// Functions found in the file, each linking to its history.
263
    functions: Vec<crate::repos::functions::Function>,
264
}
265
266
/// A blame gutter entry: shown only on the first line of a run.
267
pub struct BlameRow {
268
    pub first: bool,
269
    pub hash: String,
270
    pub short: String,
271
    pub author: String,
272
    pub when_ms: u64,
273
    pub run: usize,
274
    /// 0 (the file's oldest line) to 9 (its newest), for shading.
275
    pub age: u8,
276
    /// The state address of the change's dependencies.
277
    pub before: Option<String>,
278
}
279
280
/// Shade steps from `when` within the file's span of times.
28112×
fn age_step(when: u64, oldest: u64, newest: u64) -> u8 {
28212×
    if newest <= oldest {
2833×
        return 9;
2849×
    }
2859×
    (((when.saturating_sub(oldest)) as u128 * 9 / (newest - oldest) as u128) as u8).min(9)
28612×
}
287
2883×
fn blame_rows(
2893×
    lines: &[oxy_core::repo::BlameLine],
2903×
    before: &std::collections::HashMap<oxy_core::hash::ChangeHash, Option<String>>,
2913×
) -> Vec<BlameRow> {
2923×
    let oldest = lines.iter().map(|l| l.when_ms).min().unwrap_or(0);
2933×
    let newest = lines.iter().map(|l| l.when_ms).max().unwrap_or(0);
2943×
    let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
2953×
    let mut i = 0;
29612×
    while i < lines.len() {
2979×
        let mut run = 1;
29812×
        while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
2993×
            run += 1;
3003×
        }
30112×
        for k in 0..run {
30212×
            let l = &lines[i + k];
30312×
            rows.push(BlameRow {
30412×
                first: k == 0,
30512×
                hash: l.hash.to_hex(),
30612×
                short: l.hash.short(8),
30712×
                author: l.author.clone(),
30812×
                when_ms: l.when_ms,
30912×
                run,
31012×
                age: age_step(l.when_ms, oldest, newest),
31112×
                before: before.get(&l.hash).cloned().flatten(),
31212×
            });
31312×
        }
3149×
        i += run;
315
    }
3163×
    rows
3173×
}
318
31915×
pub async fn file(
32015×
    State(app): State<Shared>,
32115×
    viewer: Viewer,
32215×
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
32315×
    Query(q): Query<FileQuery>,
32415×
) -> Result<Response, Error> {
32515×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
32615×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
32715×
    if path == super::flow::RUN_LINK && !has_file(&app, &repo, &r, &path).await {
3281×
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/at/{r}")).into_response());
32914×
    }
33014×
    let limit = app.config.limits.render_limit.0;
33114×
    if q.plain.is_some() {
332
        // Bytes only: no last change, sidebar or highlighting to compute.
3336×
        let (spec, p) = (r.clone(), path.clone());
3346×
        let (file_name, bytes) = app
3356×
            .repos
3366×
            .read(&repo, move |repo, cache| view::raw(repo, cache, &view::resolve(repo, cache, &spec)?, &p))
3376×
            .await
3386×
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
3396×
        return Ok(super::raw(bytes, &file_name, true));
3408×
    }
3418×
    let want_blame = q.blame.is_some();
3428×
    let (spec, p) = (r.clone(), path.clone());
3438×
    let (f, blame) = app
3448×
        .repos
3458×
        .read(&repo, move |repo, cache| {
3468×
            let target = view::resolve(repo, cache, &spec)?;
3478×
            if want_blame {
3483×
                let b = view::blame(repo, cache, target, &p, limit)?;
3493×
                let rows = blame_rows(&b.lines, &b.before);
3503×
                Ok((b.file, Some(rows)))
351
            } else {
3525×
                Ok((view::file(repo, cache, target, &p, limit)?, None))
353
            }
3548×
        })
3558×
        .await
3568×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
3577×
    if q.plain.is_some() {
3580×
        return Ok(super::raw(f.bytes, &f.name, true));
3597×
    }
3607×
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
3617×
    let is_image = super::mime_of(&f.name).starts_with("image/");
3627×
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
3637×
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
3647×
    let (lines, language, markdown_html) = match &f.body {
3657×
        FileBody::Text(text) if !is_image => {
3667×
            if is_markdown && !want_source {
3671×
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
3681×
                let (base, raw) = (format!("{}/file/{r}/{dir}", rs.url), format!("{}/raw/{r}/{dir}", rs.url));
3691×
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &raw)))
370
            } else {
3716×
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
372
            }
373
        }
3740×
        _ => (vec![], None, None),
375
    };
3767×
    let permalink = f.target.permalink();
3777×
    let functions = match &f.body {
3787×
        FileBody::Text(text) if !is_image => crate::repos::functions::functions(&f.path, text),
3790×
        _ => vec![],
380
    };
3817×
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink, functions })
3827×
        .into_response())
38315×
}
384
385
/// Whether `path` is a file in the state `r` names.
3862×
async fn has_file(app: &Shared, repo: &crate::repos::RepoName, r: &str, path: &str) -> bool {
3872×
    let (spec, p) = (r.to_string(), path.to_string());
3882×
    app.repos
3892×
        .read(repo, move |repo, cache| {
3902×
            let target = view::resolve(repo, cache, &spec)?;
3912×
            Ok(cache.load(repo, &target.heads)?.snapshot.files.get(&p).is_some_and(|f| f.kind != oxy_core::objects::NodeKind::Dir))
3922×
        })
3932×
        .await
3942×
        .unwrap_or(false)
3952×
}
396
397
/// `GET /{owner}/{name}/raw/{ref}/{path}`: a file's bytes (hub spec §6.3),
398
/// where relative images in rendered Markdown point. `.flow/stamp` is the
399
/// state stamp of `{ref}` unless a real file is there (§13.2).
4009×
pub async fn raw_file(
4019×
    State(app): State<Shared>,
4029×
    viewer: Viewer,
4039×
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
4049×
) -> Result<Response, Error> {
4059×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/raw/{r}/{path}"), &viewer);
4069×
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
4079×
    if path == super::flow::STAMP_IMAGE && !has_file(&app, &repo, &r, &path).await {
4081×
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{r}")).into_response());
4098×
    }
4108×
    let (spec, p) = (r.clone(), path.clone());
4118×
    let (file_name, bytes) = app
4128×
        .repos
4138×
        .read(&repo, move |repo, cache| {
4148×
            let target = view::resolve(repo, cache, &spec)?;
4158×
            view::raw(repo, cache, &target, &p)
4168×
        })
4178×
        .await
4188×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
4198×
    Ok(super::raw(bytes, &file_name, true))
4209×
}
421
422
#[derive(Deserialize)]
423
pub struct LastQuery {
424
    /// Comma-separated paths.
425
    paths: String,
426
}
427
428
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
429
/// path, fetched by the tree page after it paints (hub spec §6.5).
4301×
pub async fn last_changes(
4311×
    State(app): State<Shared>,
4321×
    viewer: Viewer,
4331×
    Path((owner, name, r)): Path<(String, String, String)>,
4341×
    Query(q): Query<LastQuery>,
4351×
) -> Result<Response, Error> {
4361×
    let shell = Shell::new(&app, "", &viewer);
4371×
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
4382×
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
4391×
    let spec = r.clone();
4401×
    let found = app
4411×
        .repos
4421×
        .read(&repo, move |repo, cache| {
4431×
            let target = view::resolve(repo, cache, &spec)?;
4441×
            view::last_changes(repo, cache, &target.heads, &paths)
4451×
        })
4461×
        .await
4471×
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
4481×
    let now = crate::db::now_ms() as u64;
4491×
    let body: Vec<serde_json::Value> = found
4501×
        .into_iter()
4512×
        .map(|(p, c)| {
4522×
            serde_json::json!({ "path": p, "hash": c.hash, "short": c.short, "title": c.title, "ago": render::time::ago(c.when_ms, now), "when": render::time::absolute(c.when_ms) })
4532×
        })
4541×
        .collect();
4551×
    Ok(axum::Json(body).into_response())
4561×
}
457
458
impl EntryKind {
459
    /// The tree's icon for the entry (oxygenhub#152).
46063×
    pub fn icon(&self) -> &'static str {
46163×
        super::icons::svg(match self {
46220×
            EntryKind::Dir => "dir",
46343×
            EntryKind::File => "file",
4640×
            EntryKind::Symlink => "link",
4650×
            EntryKind::Subrepo => "subrepo",
466
        })
46763×
    }
468
46963×
    pub fn class(&self) -> &'static str {
47063×
        match self {
47120×
            EntryKind::Dir => "ic-dir",
47243×
            EntryKind::File => "ic-file",
4730×
            EntryKind::Symlink => "ic-link",
4740×
            EntryKind::Subrepo => "ic-sub",
475
        }
47663×
    }
477
}
478
479
#[derive(Deserialize)]
480
pub struct CodeQuery {
481
    #[serde(default)]
482
    q: String,
483
    #[serde(default, rename = "ref")]
484
    r: Option<String>,
485
    #[serde(default)]
486
    path: String,
487
    #[serde(default)]
488
    re: Option<String>,
489
    #[serde(default)]
490
    case: Option<String>,
491
}
492
493
#[derive(Template)]
494
#[template(path = "code_search.html")]
495
pub struct CodeSearchPage {
496
    shell: Shell,
497
    repo: RepoShell,
498
    q: String,
499
    r: String,
500
    path: String,
501
    regex: bool,
502
    case: bool,
503
    results: crate::repos::search::Results,
504
    error: Option<String>,
505
}
506
507
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
5084×
pub async fn code_search(
5094×
    State(app): State<Shared>,
5104×
    viewer: Viewer,
5114×
    Path((owner, name)): Path<(String, String)>,
5124×
    Query(q): Query<CodeQuery>,
5134×
) -> Result<Page<CodeSearchPage>, Error> {
5144×
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
5154×
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
5164×
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
5174×
    let (regex, case) = (q.re.is_some(), q.case.is_some());
5184×
    let mut results = crate::repos::search::Results::default();
5194×
    let mut error = None;
5204×
    if !q.q.trim().is_empty() {
5214×
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
5224×
        let app2 = app.clone();
5234×
        let out = app
5244×
            .repos
5254×
            .read(&repo, move |repo, cache| {
5264×
                let target = view::resolve(repo, cache, &spec)?;
5274×
                let loaded = cache.load(repo, &target.heads)?;
5284×
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
5294×
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
5304×
                if let Some(hit) = app2.repos.searches.get(&key) {
5310×
                    return Ok(Ok(hit));
5324×
                }
5334×
                let res = crate::repos::search::run(
5344×
                    &loaded,
5354×
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
536
                );
5374×
                if let Ok(r) = &res {
5383×
                    app2.repos.searches.put(key, r.clone());
5393×
                }
5404×
                Ok(res)
5414×
            })
5424×
            .await
5434×
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
5444×
        match out {
5453×
            Ok(r) => results = r,
5461×
            Err(e) => error = Some(e),
547
        }
5480×
    }
5494×
    Ok(Page(CodeSearchPage {
5504×
        shell,
5514×
        repo: RepoShell::new(&app, &row, "code").with_role(role),
5524×
        q: q.q,
5534×
        r,
5544×
        path: q.path,
5554×
        regex,
5564×
        case,
5574×
        results,
5584×
        error,
5594×
    }))
5604×
}
561
562
#[cfg(test)]
563
mod tests {
564
    use super::remote_name;
565
566
    #[test]
5671×
    fn remote_names_come_from_the_host() {
5681×
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
5691×
        assert_eq!(remote_name("https://hub.example.org"), "hub");
5701×
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
5711×
        assert_eq!(remote_name("http://localhost:7300"), "hub");
5721×
        assert_eq!(remote_name("https://www.example.org"), "hub");
5731×
        assert_eq!(remote_name("https://My-Host.example"), "hub");
5741×
    }
575
}