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