OXYGENHUB
◆ v0.9.24 oxygenhub / crates / hub / src / web / repo.rs
21.4 KiB · Rust · last changed UI polish: keys, backups, wiki, editor, bookmarks, summaries, backdrops 22 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>,
757195ad Andy McCall ↶ 33
    /// The upstreams it pins, with its status there (#150).
34
    follows: Vec<(crate::db::repos::RepoRow, crate::diffusion::Consumer)>,
ffb67a81 Andy McCall 35
    /// The bookmark or tag shown: the default unless `?at=` chose another
36
    /// (#191).
37
    at: String,
4edcf240 Andy McCall ↶ 38
}
39
ffb67a81 Andy McCall 40
#[derive(Deserialize)]
41
pub struct OverviewQuery {
42
    at: Option<String>,
43
}
44
4edcf240 Andy McCall ↶ 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`.
48
fn remote_name(base_url: &str) -> String {
49
    let host = base_url.split("://").nth(1).unwrap_or("").split(['/', ':']).next().unwrap_or("");
50
    let first = host.split('.').next().unwrap_or("");
51
    let plain = first.len() <= 20
52
        && first.starts_with(|c: char| c.is_ascii_lowercase())
53
        && first.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
54
    if plain && first != "www" && first != "localhost" {
55
        first.to_string()
56
    } else {
57
        "hub".to_string()
58
    }
59
}
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 {
76
    pub fn new(app: &Shared, can_push: bool) -> Quickstart {
77
        let base = app.config.base_url().trim_end_matches('/').to_string();
78
        let remote = remote_name(&base);
79
        let ca_file = format!("~/.config/oxy/{remote}-ca.pem");
80
        let ca_url = app.config.tls.self_signed.then(|| format!("{base}/.well-known/oxyhub-ca.pem"));
81
        Quickstart { remote, ca_url, ca_file, can_push }
82
    }
83
84
    /// Connect a checkout to this repository and push; the token line
85
    /// stays a placeholder so no secret is ever printed.
86
    pub fn connect(&self, clone_url: &str) -> String {
87
        let r = &self.remote;
88
        let mut s = format!("oxy remote add {r} {clone_url}\n");
89
        if let Some(ca) = &self.ca_url {
90
            s += &format!("curl -fsSL {ca} -o {}\n", self.ca_file);
91
            s += &format!("oxy config remote.{r}.ca {}\n", self.ca_file);
92
        }
93
        s += &format!("oxy config remote.{r}.token YOUR-TOKEN\n");
94
        s += &format!("oxy push {r}");
95
        s
96
    }
97
98
    /// Start a repository from nothing.
99
    pub fn fresh(&self, name: &str) -> String {
100
        format!("mkdir {name} && cd {name}\noxy init\necho \"# {name}\" > README.md\noxy commit -m \"First change\"")
101
    }
102
103
    /// Bring a Git branch across.
104
    pub fn git_import(&self, name: &str) -> String {
105
        format!("oxy git import --branch main path/to/git-checkout {name}\ncd {name}")
106
    }
d23464c0 Andy McCall ↶ 107
}
108
19bb31ff Andy McCall ↶ 109
pub async fn overview(
110
    State(app): State<Shared>,
111
    viewer: Viewer,
112
    Path((owner, name)): Path<(String, String)>,
ffb67a81 Andy McCall 113
    Query(q): Query<OverviewQuery>,
19bb31ff Andy McCall ↶ 114
) -> Result<Page<OverviewPage>, Error> {
115
    let shell = Shell::new(&app, &format!("/{owner}/{name}"), &viewer);
116
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d23464c0 Andy McCall ↶ 117
    let default = row.default_bookmark.clone();
ffb67a81 Andy McCall 118
    let at = q.at.map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).unwrap_or_else(|| default.clone());
119
    let shown = at.clone();
120
    let mut o = app
121
        .repos
122
        .read(&repo, move |r, cache| view::overview(r, cache, &default, &shown))
123
        .await
124
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
83d5052b Andy McCall ↶ 125
    // Contributors link to the hub accounts their keys are linked to.
126
    let linked: HashMap<String, String> = crate::db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
c9aacc0e Andy McCall ↶ 127
    let hub_key = app.hub_key.key.to_hex();
83d5052b Andy McCall ↶ 128
    for c in &mut o.contributors {
129
        c.account = linked.get(&c.key).cloned();
c9aacc0e Andy McCall ↶ 130
        c.hub = c.key == hub_key;
83d5052b Andy McCall ↶ 131
    }
c9aacc0e Andy McCall ↶ 132
    if let Some(c) = o.latest.as_mut() {
133
        c.author.account = linked.get(&c.author.key).cloned();
134
    }
206c1fc1 Andy McCall ↶ 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).
137
    let mut merged: Vec<view::Contributor> = Vec::new();
138
    for c in std::mem::take(&mut o.contributors) {
139
        match c.account.as_ref().and_then(|a| merged.iter_mut().find(|m| m.account.as_deref() == Some(a))) {
140
            Some(m) => {
141
                m.changes += c.changes;
142
                for (who, n) in c.via {
143
                    match m.via.iter_mut().find(|(w, _)| *w == who) {
144
                        Some((_, k)) => *k += n,
145
                        None => m.via.push((who, n)),
146
                    }
147
                }
148
                m.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
149
            }
150
            None => merged.push(c),
151
        }
152
    }
153
    merged.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
154
    o.contributors = merged;
ffb67a81 Andy McCall 155
    let rs = RepoShell::new(&app, &row, "code").with_role(role).with_sky(&app, &row).await;
d23464c0 Andy McCall ↶ 156
    let readme_html = o.readme_html(&rs, &o.tree.target.label);
18e381ea Andy McCall ↶ 157
    let watching = match viewer.account() {
158
        Some(a) => crate::db::notify::watching(&app.db, a.id, row.id).await.unwrap_or(false),
159
        None => false,
160
    };
3f4b0ea6 Andy McCall ↶ 161
    let latest_release = crate::db::releases::latest(&app.db, row.id).await.ok().flatten();
4edcf240 Andy McCall ↶ 162
    let quickstart = (o.changes == 0).then(|| Quickstart::new(&app, rs.can(crate::auth::Access::Write)));
07b1a5bb Andy McCall ↶ 163
    let fork = super::forks::info(&app, &shell, &viewer, &row).await;
1553bfc9 Andy McCall ↶ 164
    let starred = match viewer.account() {
165
        Some(a) => crate::db::repos::starred(&app.db, a.id, row.id).await.unwrap_or(false),
166
        None => false,
167
    };
168
    let (stars, watchers) = crate::db::repos::counts(&app.db, row.id).await.unwrap_or((0, 0));
169
    let topics = row.topic_list().into_iter().map(String::from).collect();
f677d627 Andy McCall ↶ 170
    let used_by = crate::diffusion::consumers(&app, &row, viewer.account()).await.unwrap_or_default();
757195ad Andy McCall ↶ 171
    let follows = crate::diffusion::follows(&app, &row, viewer.account()).await;
f677d627 Andy McCall ↶ 172
    Ok(Page(OverviewPage {
173
        shell,
174
        repo: rs,
175
        o,
176
        readme_html,
177
        watching,
178
        latest_release,
179
        quickstart,
180
        fork,
181
        starred,
182
        stars,
183
        watchers,
184
        topics,
185
        used_by,
757195ad Andy McCall ↶ 186
        follows,
ffb67a81 Andy McCall 187
        at,
f677d627 Andy McCall ↶ 188
    }))
d23464c0 Andy McCall ↶ 189
}
190
191
impl view::Overview {
192
    fn readme_html(&self, rs: &RepoShell, r: &str) -> Option<String> {
193
        self.tree.readme.as_ref().map(|md| {
194
            let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
736f6813 Andy McCall ↶ 195
            render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
d23464c0 Andy McCall ↶ 196
        })
197
    }
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
ffb67a81 Andy McCall 209
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).
212
    axum::response::Redirect::to(&format!("/{owner}/{name}?at={}", super::settings::urlencode(&r))).into_response()
d23464c0 Andy McCall ↶ 213
}
214
215
pub async fn tree(
216
    State(app): State<Shared>,
19bb31ff Andy McCall ↶ 217
    viewer: Viewer,
d23464c0 Andy McCall ↶ 218
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
219
) -> Result<Page<TreePage>, Error> {
19bb31ff Andy McCall ↶ 220
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tree/{r}/{path}"), &viewer);
221
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d23464c0 Andy McCall ↶ 222
    let (spec, dir) = (r.clone(), path.clone());
223
    let t = app
224
        .repos
9ff27da5 Andy McCall ↶ 225
        .read(&repo, move |repo, cache| {
226
            let target = view::resolve(repo, cache, &spec)?;
227
            view::tree(repo, cache, target, &dir)
d23464c0 Andy McCall ↶ 228
        })
229
        .await
230
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
19bb31ff Andy McCall ↶ 231
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
d23464c0 Andy McCall ↶ 232
    let readme_html = t.readme.as_ref().map(|md| {
233
        let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
736f6813 Andy McCall ↶ 234
        render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
d23464c0 Andy McCall ↶ 235
    });
236
    Ok(Page(TreePage { shell, repo: rs, t, readme_html }))
237
}
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>>,
6ae41081 Andy McCall ↶ 260
    /// The `{ref}` of this state for good (hub spec §6.6).
261
    permalink: Option<String>,
65be9f9c Andy McCall ↶ 262
    /// Functions found in the file, each linking to its history.
263
    functions: Vec<crate::repos::functions::Function>,
d23464c0 Andy McCall ↶ 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,
6ae41081 Andy McCall ↶ 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.
281
fn age_step(when: u64, oldest: u64, newest: u64) -> u8 {
282
    if newest <= oldest {
283
        return 9;
284
    }
285
    (((when.saturating_sub(oldest)) as u128 * 9 / (newest - oldest) as u128) as u8).min(9)
286
}
287
288
fn blame_rows(
289
    lines: &[oxy_core::repo::BlameLine],
290
    before: &std::collections::HashMap<oxy_core::hash::ChangeHash, Option<String>>,
291
) -> Vec<BlameRow> {
292
    let oldest = lines.iter().map(|l| l.when_ms).min().unwrap_or(0);
293
    let newest = lines.iter().map(|l| l.when_ms).max().unwrap_or(0);
294
    let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
295
    let mut i = 0;
296
    while i < lines.len() {
297
        let mut run = 1;
298
        while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
299
            run += 1;
300
        }
301
        for k in 0..run {
302
            let l = &lines[i + k];
303
            rows.push(BlameRow {
304
                first: k == 0,
305
                hash: l.hash.to_hex(),
306
                short: l.hash.short(8),
307
                author: l.author.clone(),
308
                when_ms: l.when_ms,
309
                run,
310
                age: age_step(l.when_ms, oldest, newest),
311
                before: before.get(&l.hash).cloned().flatten(),
312
            });
313
        }
314
        i += run;
315
    }
316
    rows
d23464c0 Andy McCall ↶ 317
}
318
319
pub async fn file(
320
    State(app): State<Shared>,
19bb31ff Andy McCall ↶ 321
    viewer: Viewer,
d23464c0 Andy McCall ↶ 322
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
323
    Query(q): Query<FileQuery>,
324
) -> Result<Response, Error> {
19bb31ff Andy McCall ↶ 325
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
326
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
736f6813 Andy McCall ↶ 327
    if path == super::flow::RUN_LINK && !has_file(&app, &repo, &r, &path).await {
328
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/at/{r}")).into_response());
329
    }
d23464c0 Andy McCall ↶ 330
    let limit = app.config.limits.render_limit.0;
75d611ab Andy McCall ↶ 331
    if q.plain.is_some() {
332
        // Bytes only: no last change, sidebar or highlighting to compute.
333
        let (spec, p) = (r.clone(), path.clone());
334
        let (file_name, bytes) = app
335
            .repos
336
            .read(&repo, move |repo, cache| view::raw(repo, cache, &view::resolve(repo, cache, &spec)?, &p))
337
            .await
338
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
339
        return Ok(super::raw(bytes, &file_name, true));
340
    }
d23464c0 Andy McCall ↶ 341
    let want_blame = q.blame.is_some();
342
    let (spec, p) = (r.clone(), path.clone());
343
    let (f, blame) = app
344
        .repos
9ff27da5 Andy McCall ↶ 345
        .read(&repo, move |repo, cache| {
346
            let target = view::resolve(repo, cache, &spec)?;
d23464c0 Andy McCall ↶ 347
            if want_blame {
9ff27da5 Andy McCall ↶ 348
                let b = view::blame(repo, cache, target, &p, limit)?;
6ae41081 Andy McCall ↶ 349
                let rows = blame_rows(&b.lines, &b.before);
350
                Ok((b.file, Some(rows)))
d23464c0 Andy McCall ↶ 351
            } else {
9ff27da5 Andy McCall ↶ 352
                Ok((view::file(repo, cache, target, &p, limit)?, None))
d23464c0 Andy McCall ↶ 353
            }
354
        })
355
        .await
356
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
357
    if q.plain.is_some() {
358
        return Ok(super::raw(f.bytes, &f.name, true));
359
    }
19bb31ff Andy McCall ↶ 360
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
d23464c0 Andy McCall ↶ 361
    let is_image = super::mime_of(&f.name).starts_with("image/");
362
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
363
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
364
    let (lines, language, markdown_html) = match &f.body {
365
        FileBody::Text(text) if !is_image => {
366
            if is_markdown && !want_source {
367
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
736f6813 Andy McCall ↶ 368
                let (base, raw) = (format!("{}/file/{r}/{dir}", rs.url), format!("{}/raw/{r}/{dir}", rs.url));
369
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &raw)))
d23464c0 Andy McCall ↶ 370
            } else {
371
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
372
            }
373
        }
374
        _ => (vec![], None, None),
375
    };
6ae41081 Andy McCall ↶ 376
    let permalink = f.target.permalink();
65be9f9c Andy McCall ↶ 377
    let functions = match &f.body {
378
        FileBody::Text(text) if !is_image => crate::repos::functions::functions(&f.path, text),
379
        _ => vec![],
380
    };
381
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink, functions })
382
        .into_response())
736f6813 Andy McCall ↶ 383
}
384
385
/// Whether `path` is a file in the state `r` names.
386
async fn has_file(app: &Shared, repo: &crate::repos::RepoName, r: &str, path: &str) -> bool {
387
    let (spec, p) = (r.to_string(), path.to_string());
388
    app.repos
389
        .read(repo, move |repo, cache| {
390
            let target = view::resolve(repo, cache, &spec)?;
391
            Ok(cache.load(repo, &target.heads)?.snapshot.files.get(&p).is_some_and(|f| f.kind != oxy_core::objects::NodeKind::Dir))
392
        })
393
        .await
394
        .unwrap_or(false)
395
}
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).
400
pub async fn raw_file(
401
    State(app): State<Shared>,
402
    viewer: Viewer,
403
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
404
) -> Result<Response, Error> {
405
    let shell = Shell::new(&app, &format!("/{owner}/{name}/raw/{r}/{path}"), &viewer);
406
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
407
    if path == super::flow::STAMP_IMAGE && !has_file(&app, &repo, &r, &path).await {
408
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{r}")).into_response());
409
    }
410
    let (spec, p) = (r.clone(), path.clone());
411
    let (file_name, bytes) = app
412
        .repos
413
        .read(&repo, move |repo, cache| {
414
            let target = view::resolve(repo, cache, &spec)?;
415
            view::raw(repo, cache, &target, &p)
416
        })
417
        .await
418
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
419
    Ok(super::raw(bytes, &file_name, true))
d23464c0 Andy McCall ↶ 420
}
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).
430
pub async fn last_changes(
431
    State(app): State<Shared>,
19bb31ff Andy McCall ↶ 432
    viewer: Viewer,
d23464c0 Andy McCall ↶ 433
    Path((owner, name, r)): Path<(String, String, String)>,
434
    Query(q): Query<LastQuery>,
435
) -> Result<Response, Error> {
19bb31ff Andy McCall ↶ 436
    let shell = Shell::new(&app, "", &viewer);
437
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
d23464c0 Andy McCall ↶ 438
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
439
    let spec = r.clone();
440
    let found = app
441
        .repos
9ff27da5 Andy McCall ↶ 442
        .read(&repo, move |repo, cache| {
443
            let target = view::resolve(repo, cache, &spec)?;
444
            view::last_changes(repo, cache, &target.heads, &paths)
d23464c0 Andy McCall ↶ 445
        })
446
        .await
447
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
448
    let now = crate::db::now_ms() as u64;
449
    let body: Vec<serde_json::Value> = found
450
        .into_iter()
451
        .map(|(p, c)| {
452
            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) })
453
        })
454
        .collect();
455
    Ok(axum::Json(body).into_response())
456
}
457
458
impl EntryKind {
c9aacc0e Andy McCall ↶ 459
    /// The tree's icon for the entry (oxygenhub#152).
460
    pub fn icon(&self) -> &'static str {
461
        super::icons::svg(match self {
462
            EntryKind::Dir => "dir",
463
            EntryKind::File => "file",
464
            EntryKind::Symlink => "link",
465
            EntryKind::Subrepo => "subrepo",
466
        })
467
    }
468
469
    pub fn class(&self) -> &'static str {
d23464c0 Andy McCall ↶ 470
        match self {
c9aacc0e Andy McCall ↶ 471
            EntryKind::Dir => "ic-dir",
472
            EntryKind::File => "ic-file",
473
            EntryKind::Symlink => "ic-link",
474
            EntryKind::Subrepo => "ic-sub",
d23464c0 Andy McCall ↶ 475
        }
476
    }
477
}
3f4b0ea6 Andy McCall ↶ 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).
508
pub async fn code_search(
509
    State(app): State<Shared>,
510
    viewer: Viewer,
511
    Path((owner, name)): Path<(String, String)>,
512
    Query(q): Query<CodeQuery>,
513
) -> Result<Page<CodeSearchPage>, Error> {
514
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
515
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
516
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
517
    let (regex, case) = (q.re.is_some(), q.case.is_some());
518
    let mut results = crate::repos::search::Results::default();
519
    let mut error = None;
520
    if !q.q.trim().is_empty() {
521
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
522
        let app2 = app.clone();
523
        let out = app
524
            .repos
525
            .read(&repo, move |repo, cache| {
526
                let target = view::resolve(repo, cache, &spec)?;
527
                let loaded = cache.load(repo, &target.heads)?;
528
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
529
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
530
                if let Some(hit) = app2.repos.searches.get(&key) {
531
                    return Ok(Ok(hit));
532
                }
533
                let res = crate::repos::search::run(
534
                    &loaded,
535
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
536
                );
537
                if let Ok(r) = &res {
538
                    app2.repos.searches.put(key, r.clone());
539
                }
540
                Ok(res)
541
            })
542
            .await
543
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
544
        match out {
545
            Ok(r) => results = r,
546
            Err(e) => error = Some(e),
547
        }
548
    }
549
    Ok(Page(CodeSearchPage {
550
        shell,
551
        repo: RepoShell::new(&app, &row, "code").with_role(role),
552
        q: q.q,
553
        r,
554
        path: q.path,
555
        regex,
556
        case,
557
        results,
558
        error,
559
    }))
560
}
4edcf240 Andy McCall ↶ 561
562
#[cfg(test)]
563
mod tests {
564
    use super::remote_name;
565
566
    #[test]
567
    fn remote_names_come_from_the_host() {
568
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
569
        assert_eq!(remote_name("https://hub.example.org"), "hub");
570
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
571
        assert_eq!(remote_name("http://localhost:7300"), "hub");
572
        assert_eq!(remote_name("https://www.example.org"), "hub");
573
        assert_eq!(remote_name("https://My-Host.example"), "hub");
574
    }
575
}