OXYGENHUB
◆ close-proposal-140 oxygenhub / crates / hub / src / web / repo.rs
20.2 KiB · Rust · last changed Diffusion: the reverse pin index, Used by, and how far behind 24 days ago source blame history raw
d23464c0 Andy McCall ↶ 1
//! Repository overview, tree, file, raw and blame pages.
2
3
use super::{filters, lookup, Error, Page, RepoShell, Shell};
19bb31ff Andy McCall ↶ 4
use crate::auth::Viewer;
d23464c0 Andy McCall ↶ 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;
83d5052b Andy McCall ↶ 12
use std::collections::HashMap;
d23464c0 Andy McCall ↶ 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>,
18e381ea Andy McCall ↶ 21
    watching: bool,
3f4b0ea6 Andy McCall ↶ 22
    latest_release: Option<crate::db::releases::Release>,
4edcf240 Andy McCall ↶ 23
    /// Set while the repository has no changes (hub spec §6).
24
    quickstart: Option<Quickstart>,
07b1a5bb Andy McCall ↶ 25
    fork: super::forks::ForkInfo,
1553bfc9 Andy McCall ↶ 26
    starred: bool,
27
    stars: i64,
28
    watchers: i64,
29
    topics: Vec<String>,
f677d627 Andy McCall ↶ 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>,
4edcf240 Andy McCall ↶ 33
}
34
35
/// A remote name from the hub's host: its first label when that is a
36
/// plain lowercase word (`earth` for `https://earth.example.org:7343`),
37
/// otherwise `hub`.
38
fn remote_name(base_url: &str) -> String {
39
    let host = base_url.split("://").nth(1).unwrap_or("").split(['/', ':']).next().unwrap_or("");
40
    let first = host.split('.').next().unwrap_or("");
41
    let plain = first.len() <= 20
42
        && first.starts_with(|c: char| c.is_ascii_lowercase())
43
        && first.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
44
    if plain && first != "www" && first != "localhost" {
45
        first.to_string()
46
    } else {
47
        "hub".to_string()
48
    }
49
}
50
51
/// The commands that get a first push into an empty repository, filled
52
/// in for this hub and this repository.
53
pub struct Quickstart {
54
    /// A remote name taken from the hub's host name (`earth` for
55
    /// `earth.example.org`), `hub` when that is not a plain word.
56
    pub remote: String,
57
    /// Where to download the hub's certificate, when it is self-signed.
58
    pub ca_url: Option<String>,
59
    /// Where the commands save that certificate.
60
    pub ca_file: String,
61
    /// Whether the viewer may push here.
62
    pub can_push: bool,
63
}
64
65
impl Quickstart {
66
    pub fn new(app: &Shared, can_push: bool) -> Quickstart {
67
        let base = app.config.base_url().trim_end_matches('/').to_string();
68
        let remote = remote_name(&base);
69
        let ca_file = format!("~/.config/oxy/{remote}-ca.pem");
70
        let ca_url = app.config.tls.self_signed.then(|| format!("{base}/.well-known/oxyhub-ca.pem"));
71
        Quickstart { remote, ca_url, ca_file, can_push }
72
    }
73
74
    /// Connect a checkout to this repository and push; the token line
75
    /// stays a placeholder so no secret is ever printed.
76
    pub fn connect(&self, clone_url: &str) -> String {
77
        let r = &self.remote;
78
        let mut s = format!("oxy remote add {r} {clone_url}\n");
79
        if let Some(ca) = &self.ca_url {
80
            s += &format!("curl -fsSL {ca} -o {}\n", self.ca_file);
81
            s += &format!("oxy config remote.{r}.ca {}\n", self.ca_file);
82
        }
83
        s += &format!("oxy config remote.{r}.token YOUR-TOKEN\n");
84
        s += &format!("oxy push {r}");
85
        s
86
    }
87
88
    /// Start a repository from nothing.
89
    pub fn fresh(&self, name: &str) -> String {
90
        format!("mkdir {name} && cd {name}\noxy init\necho \"# {name}\" > README.md\noxy commit -m \"First change\"")
91
    }
92
93
    /// Bring a Git branch across.
94
    pub fn git_import(&self, name: &str) -> String {
95
        format!("oxy git import --branch main path/to/git-checkout {name}\ncd {name}")
96
    }
d23464c0 Andy McCall ↶ 97
}
98
19bb31ff Andy McCall ↶ 99
pub async fn overview(
100
    State(app): State<Shared>,
101
    viewer: Viewer,
102
    Path((owner, name)): Path<(String, String)>,
103
) -> Result<Page<OverviewPage>, Error> {
104
    let shell = Shell::new(&app, &format!("/{owner}/{name}"), &viewer);
105
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d23464c0 Andy McCall ↶ 106
    let default = row.default_bookmark.clone();
83d5052b Andy McCall ↶ 107
    let mut o =
9ff27da5 Andy McCall ↶ 108
        app.repos.read(&repo, move |r, cache| view::overview(r, cache, &default)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
83d5052b Andy McCall ↶ 109
    // Contributors link to the hub accounts their keys are linked to.
110
    let linked: HashMap<String, String> = crate::db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
111
    for c in &mut o.contributors {
112
        c.account = linked.get(&c.key).cloned();
113
    }
206c1fc1 Andy McCall ↶ 114
    // One row per account: a person's keys over time are one contributor,
115
    // their agents' shares summed beneath (as `oxy log` shows via).
116
    let mut merged: Vec<view::Contributor> = Vec::new();
117
    for c in std::mem::take(&mut o.contributors) {
118
        match c.account.as_ref().and_then(|a| merged.iter_mut().find(|m| m.account.as_deref() == Some(a))) {
119
            Some(m) => {
120
                m.changes += c.changes;
121
                for (who, n) in c.via {
122
                    match m.via.iter_mut().find(|(w, _)| *w == who) {
123
                        Some((_, k)) => *k += n,
124
                        None => m.via.push((who, n)),
125
                    }
126
                }
127
                m.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
128
            }
129
            None => merged.push(c),
130
        }
131
    }
132
    merged.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
133
    o.contributors = merged;
19bb31ff Andy McCall ↶ 134
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
d23464c0 Andy McCall ↶ 135
    let readme_html = o.readme_html(&rs, &o.tree.target.label);
18e381ea Andy McCall ↶ 136
    let watching = match viewer.account() {
137
        Some(a) => crate::db::notify::watching(&app.db, a.id, row.id).await.unwrap_or(false),
138
        None => false,
139
    };
3f4b0ea6 Andy McCall ↶ 140
    let latest_release = crate::db::releases::latest(&app.db, row.id).await.ok().flatten();
4edcf240 Andy McCall ↶ 141
    let quickstart = (o.changes == 0).then(|| Quickstart::new(&app, rs.can(crate::auth::Access::Write)));
07b1a5bb Andy McCall ↶ 142
    let fork = super::forks::info(&app, &shell, &viewer, &row).await;
1553bfc9 Andy McCall ↶ 143
    let starred = match viewer.account() {
144
        Some(a) => crate::db::repos::starred(&app.db, a.id, row.id).await.unwrap_or(false),
145
        None => false,
146
    };
147
    let (stars, watchers) = crate::db::repos::counts(&app.db, row.id).await.unwrap_or((0, 0));
148
    let topics = row.topic_list().into_iter().map(String::from).collect();
f677d627 Andy McCall ↶ 149
    let used_by = crate::diffusion::consumers(&app, &row, viewer.account()).await.unwrap_or_default();
150
    Ok(Page(OverviewPage {
151
        shell,
152
        repo: rs,
153
        o,
154
        readme_html,
155
        watching,
156
        latest_release,
157
        quickstart,
158
        fork,
159
        starred,
160
        stars,
161
        watchers,
162
        topics,
163
        used_by,
164
    }))
d23464c0 Andy McCall ↶ 165
}
166
167
impl view::Overview {
168
    fn readme_html(&self, rs: &RepoShell, r: &str) -> Option<String> {
169
        self.tree.readme.as_ref().map(|md| {
170
            let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
736f6813 Andy McCall ↶ 171
            render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
d23464c0 Andy McCall ↶ 172
        })
173
    }
174
}
175
176
#[derive(Template)]
177
#[template(path = "tree.html")]
178
pub struct TreePage {
179
    shell: Shell,
180
    repo: RepoShell,
181
    t: view::Tree,
182
    readme_html: Option<String>,
183
}
184
19bb31ff Andy McCall ↶ 185
pub async fn tree_root(
186
    State(app): State<Shared>,
187
    viewer: Viewer,
188
    Path((owner, name, r)): Path<(String, String, String)>,
189
) -> Result<Page<TreePage>, Error> {
190
    tree(State(app), viewer, Path((owner, name, r, String::new()))).await
d23464c0 Andy McCall ↶ 191
}
192
193
pub async fn tree(
194
    State(app): State<Shared>,
19bb31ff Andy McCall ↶ 195
    viewer: Viewer,
d23464c0 Andy McCall ↶ 196
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
197
) -> Result<Page<TreePage>, Error> {
19bb31ff Andy McCall ↶ 198
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tree/{r}/{path}"), &viewer);
199
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d23464c0 Andy McCall ↶ 200
    let (spec, dir) = (r.clone(), path.clone());
201
    let t = app
202
        .repos
9ff27da5 Andy McCall ↶ 203
        .read(&repo, move |repo, cache| {
204
            let target = view::resolve(repo, cache, &spec)?;
205
            view::tree(repo, cache, target, &dir)
d23464c0 Andy McCall ↶ 206
        })
207
        .await
208
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
19bb31ff Andy McCall ↶ 209
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
d23464c0 Andy McCall ↶ 210
    let readme_html = t.readme.as_ref().map(|md| {
211
        let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
736f6813 Andy McCall ↶ 212
        render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
d23464c0 Andy McCall ↶ 213
    });
214
    Ok(Page(TreePage { shell, repo: rs, t, readme_html }))
215
}
216
217
#[derive(Deserialize)]
218
pub struct FileQuery {
219
    plain: Option<String>,
220
    blame: Option<String>,
221
    /// `source` shows a Markdown file's text instead of rendering it.
222
    view: Option<String>,
223
}
224
225
#[derive(Template)]
226
#[template(path = "file.html")]
227
pub struct FilePage {
228
    shell: Shell,
229
    repo: RepoShell,
230
    f: view::FileView,
231
    /// Highlighted lines when text.
232
    lines: Vec<String>,
233
    language: Option<&'static str>,
234
    markdown_html: Option<String>,
235
    is_image: bool,
236
    is_markdown: bool,
237
    blame: Option<Vec<BlameRow>>,
6ae41081 Andy McCall ↶ 238
    /// The `{ref}` of this state for good (hub spec §6.6).
239
    permalink: Option<String>,
65be9f9c Andy McCall ↶ 240
    /// Functions found in the file, each linking to its history.
241
    functions: Vec<crate::repos::functions::Function>,
d23464c0 Andy McCall ↶ 242
}
243
244
/// A blame gutter entry: shown only on the first line of a run.
245
pub struct BlameRow {
246
    pub first: bool,
247
    pub hash: String,
248
    pub short: String,
249
    pub author: String,
250
    pub when_ms: u64,
251
    pub run: usize,
6ae41081 Andy McCall ↶ 252
    /// 0 (the file's oldest line) to 9 (its newest), for shading.
253
    pub age: u8,
254
    /// The state address of the change's dependencies.
255
    pub before: Option<String>,
256
}
257
258
/// Shade steps from `when` within the file's span of times.
259
fn age_step(when: u64, oldest: u64, newest: u64) -> u8 {
260
    if newest <= oldest {
261
        return 9;
262
    }
263
    (((when.saturating_sub(oldest)) as u128 * 9 / (newest - oldest) as u128) as u8).min(9)
264
}
265
266
fn blame_rows(
267
    lines: &[oxy_core::repo::BlameLine],
268
    before: &std::collections::HashMap<oxy_core::hash::ChangeHash, Option<String>>,
269
) -> Vec<BlameRow> {
270
    let oldest = lines.iter().map(|l| l.when_ms).min().unwrap_or(0);
271
    let newest = lines.iter().map(|l| l.when_ms).max().unwrap_or(0);
272
    let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
273
    let mut i = 0;
274
    while i < lines.len() {
275
        let mut run = 1;
276
        while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
277
            run += 1;
278
        }
279
        for k in 0..run {
280
            let l = &lines[i + k];
281
            rows.push(BlameRow {
282
                first: k == 0,
283
                hash: l.hash.to_hex(),
284
                short: l.hash.short(8),
285
                author: l.author.clone(),
286
                when_ms: l.when_ms,
287
                run,
288
                age: age_step(l.when_ms, oldest, newest),
289
                before: before.get(&l.hash).cloned().flatten(),
290
            });
291
        }
292
        i += run;
293
    }
294
    rows
d23464c0 Andy McCall ↶ 295
}
296
297
pub async fn file(
298
    State(app): State<Shared>,
19bb31ff Andy McCall ↶ 299
    viewer: Viewer,
d23464c0 Andy McCall ↶ 300
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
301
    Query(q): Query<FileQuery>,
302
) -> Result<Response, Error> {
19bb31ff Andy McCall ↶ 303
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
304
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
736f6813 Andy McCall ↶ 305
    if path == super::flow::RUN_LINK && !has_file(&app, &repo, &r, &path).await {
306
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/at/{r}")).into_response());
307
    }
d23464c0 Andy McCall ↶ 308
    let limit = app.config.limits.render_limit.0;
75d611ab Andy McCall ↶ 309
    if q.plain.is_some() {
310
        // Bytes only: no last change, sidebar or highlighting to compute.
311
        let (spec, p) = (r.clone(), path.clone());
312
        let (file_name, bytes) = app
313
            .repos
314
            .read(&repo, move |repo, cache| view::raw(repo, cache, &view::resolve(repo, cache, &spec)?, &p))
315
            .await
316
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
317
        return Ok(super::raw(bytes, &file_name, true));
318
    }
d23464c0 Andy McCall ↶ 319
    let want_blame = q.blame.is_some();
320
    let (spec, p) = (r.clone(), path.clone());
321
    let (f, blame) = app
322
        .repos
9ff27da5 Andy McCall ↶ 323
        .read(&repo, move |repo, cache| {
324
            let target = view::resolve(repo, cache, &spec)?;
d23464c0 Andy McCall ↶ 325
            if want_blame {
9ff27da5 Andy McCall ↶ 326
                let b = view::blame(repo, cache, target, &p, limit)?;
6ae41081 Andy McCall ↶ 327
                let rows = blame_rows(&b.lines, &b.before);
328
                Ok((b.file, Some(rows)))
d23464c0 Andy McCall ↶ 329
            } else {
9ff27da5 Andy McCall ↶ 330
                Ok((view::file(repo, cache, target, &p, limit)?, None))
d23464c0 Andy McCall ↶ 331
            }
332
        })
333
        .await
334
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
335
    if q.plain.is_some() {
336
        return Ok(super::raw(f.bytes, &f.name, true));
337
    }
19bb31ff Andy McCall ↶ 338
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
d23464c0 Andy McCall ↶ 339
    let is_image = super::mime_of(&f.name).starts_with("image/");
340
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
341
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
342
    let (lines, language, markdown_html) = match &f.body {
343
        FileBody::Text(text) if !is_image => {
344
            if is_markdown && !want_source {
345
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
736f6813 Andy McCall ↶ 346
                let (base, raw) = (format!("{}/file/{r}/{dir}", rs.url), format!("{}/raw/{r}/{dir}", rs.url));
347
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &raw)))
d23464c0 Andy McCall ↶ 348
            } else {
349
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
350
            }
351
        }
352
        _ => (vec![], None, None),
353
    };
6ae41081 Andy McCall ↶ 354
    let permalink = f.target.permalink();
65be9f9c Andy McCall ↶ 355
    let functions = match &f.body {
356
        FileBody::Text(text) if !is_image => crate::repos::functions::functions(&f.path, text),
357
        _ => vec![],
358
    };
359
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink, functions })
360
        .into_response())
736f6813 Andy McCall ↶ 361
}
362
363
/// Whether `path` is a file in the state `r` names.
364
async fn has_file(app: &Shared, repo: &crate::repos::RepoName, r: &str, path: &str) -> bool {
365
    let (spec, p) = (r.to_string(), path.to_string());
366
    app.repos
367
        .read(repo, move |repo, cache| {
368
            let target = view::resolve(repo, cache, &spec)?;
369
            Ok(cache.load(repo, &target.heads)?.snapshot.files.get(&p).is_some_and(|f| f.kind != oxy_core::objects::NodeKind::Dir))
370
        })
371
        .await
372
        .unwrap_or(false)
373
}
374
375
/// `GET /{owner}/{name}/raw/{ref}/{path}`: a file's bytes (hub spec §6.3),
376
/// where relative images in rendered Markdown point. `.flow/stamp` is the
377
/// state stamp of `{ref}` unless a real file is there (§13.2).
378
pub async fn raw_file(
379
    State(app): State<Shared>,
380
    viewer: Viewer,
381
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
382
) -> Result<Response, Error> {
383
    let shell = Shell::new(&app, &format!("/{owner}/{name}/raw/{r}/{path}"), &viewer);
384
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
385
    if path == super::flow::STAMP_IMAGE && !has_file(&app, &repo, &r, &path).await {
386
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{r}")).into_response());
387
    }
388
    let (spec, p) = (r.clone(), path.clone());
389
    let (file_name, bytes) = app
390
        .repos
391
        .read(&repo, move |repo, cache| {
392
            let target = view::resolve(repo, cache, &spec)?;
393
            view::raw(repo, cache, &target, &p)
394
        })
395
        .await
396
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
397
    Ok(super::raw(bytes, &file_name, true))
d23464c0 Andy McCall ↶ 398
}
399
400
#[derive(Deserialize)]
401
pub struct LastQuery {
402
    /// Comma-separated paths.
403
    paths: String,
404
}
405
406
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
407
/// path, fetched by the tree page after it paints (hub spec §6.5).
408
pub async fn last_changes(
409
    State(app): State<Shared>,
19bb31ff Andy McCall ↶ 410
    viewer: Viewer,
d23464c0 Andy McCall ↶ 411
    Path((owner, name, r)): Path<(String, String, String)>,
412
    Query(q): Query<LastQuery>,
413
) -> Result<Response, Error> {
19bb31ff Andy McCall ↶ 414
    let shell = Shell::new(&app, "", &viewer);
415
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d23464c0 Andy McCall ↶ 416
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
417
    let spec = r.clone();
418
    let found = app
419
        .repos
9ff27da5 Andy McCall ↶ 420
        .read(&repo, move |repo, cache| {
421
            let target = view::resolve(repo, cache, &spec)?;
422
            view::last_changes(repo, cache, &target.heads, &paths)
d23464c0 Andy McCall ↶ 423
        })
424
        .await
425
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
426
    let now = crate::db::now_ms() as u64;
427
    let body: Vec<serde_json::Value> = found
428
        .into_iter()
429
        .map(|(p, c)| {
430
            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) })
431
        })
432
        .collect();
433
    Ok(axum::Json(body).into_response())
434
}
435
436
impl EntryKind {
437
    pub fn glyph(&self) -> &'static str {
438
        match self {
439
            EntryKind::Dir => "▸",
440
            EntryKind::File => "·",
441
            EntryKind::Symlink => "↪",
442
            EntryKind::Subrepo => "◫",
443
        }
444
    }
445
}
3f4b0ea6 Andy McCall ↶ 446
447
#[derive(Deserialize)]
448
pub struct CodeQuery {
449
    #[serde(default)]
450
    q: String,
451
    #[serde(default, rename = "ref")]
452
    r: Option<String>,
453
    #[serde(default)]
454
    path: String,
455
    #[serde(default)]
456
    re: Option<String>,
457
    #[serde(default)]
458
    case: Option<String>,
459
}
460
461
#[derive(Template)]
462
#[template(path = "code_search.html")]
463
pub struct CodeSearchPage {
464
    shell: Shell,
465
    repo: RepoShell,
466
    q: String,
467
    r: String,
468
    path: String,
469
    regex: bool,
470
    case: bool,
471
    results: crate::repos::search::Results,
472
    error: Option<String>,
473
}
474
475
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
476
pub async fn code_search(
477
    State(app): State<Shared>,
478
    viewer: Viewer,
479
    Path((owner, name)): Path<(String, String)>,
480
    Query(q): Query<CodeQuery>,
481
) -> Result<Page<CodeSearchPage>, Error> {
482
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
483
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
484
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
485
    let (regex, case) = (q.re.is_some(), q.case.is_some());
486
    let mut results = crate::repos::search::Results::default();
487
    let mut error = None;
488
    if !q.q.trim().is_empty() {
489
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
490
        let app2 = app.clone();
491
        let out = app
492
            .repos
493
            .read(&repo, move |repo, cache| {
494
                let target = view::resolve(repo, cache, &spec)?;
495
                let loaded = cache.load(repo, &target.heads)?;
496
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
497
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
498
                if let Some(hit) = app2.repos.searches.get(&key) {
499
                    return Ok(Ok(hit));
500
                }
501
                let res = crate::repos::search::run(
502
                    &loaded,
503
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
504
                );
505
                if let Ok(r) = &res {
506
                    app2.repos.searches.put(key, r.clone());
507
                }
508
                Ok(res)
509
            })
510
            .await
511
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
512
        match out {
513
            Ok(r) => results = r,
514
            Err(e) => error = Some(e),
515
        }
516
    }
517
    Ok(Page(CodeSearchPage {
518
        shell,
519
        repo: RepoShell::new(&app, &row, "code").with_role(role),
520
        q: q.q,
521
        r,
522
        path: q.path,
523
        regex,
524
        case,
525
        results,
526
        error,
527
    }))
528
}
4edcf240 Andy McCall ↶ 529
530
#[cfg(test)]
531
mod tests {
532
    use super::remote_name;
533
534
    #[test]
535
    fn remote_names_come_from_the_host() {
536
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
537
        assert_eq!(remote_name("https://hub.example.org"), "hub");
538
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
539
        assert_eq!(remote_name("http://localhost:7300"), "hub");
540
        assert_eq!(remote_name("https://www.example.org"), "hub");
541
        assert_eq!(remote_name("https://My-Host.example"), "hub");
542
    }
543
}