OXYGENHUB
# 3d3d29fbcb00 oxygenhub / crates / hub / src / web / repo.rs
18.5 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
    let want_blame = q.blame.is_some();
272
    let (spec, p) = (r.clone(), path.clone());
273
    let (f, blame) = app
274
        .repos
275
        .read(&repo, move |repo, cache| {
276
            let target = view::resolve(repo, cache, &spec)?;
277
            if want_blame {
278
                let b = view::blame(repo, cache, target, &p, limit)?;
279
                let rows = blame_rows(&b.lines, &b.before);
280
                Ok((b.file, Some(rows)))
281
            } else {
282
                Ok((view::file(repo, cache, target, &p, limit)?, None))
283
            }
284
        })
285
        .await
286
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
287
    if q.plain.is_some() {
288
        return Ok(super::raw(f.bytes, &f.name, true));
289
    }
290
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
291
    let is_image = super::mime_of(&f.name).starts_with("image/");
292
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
293
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
294
    let (lines, language, markdown_html) = match &f.body {
295
        FileBody::Text(text) if !is_image => {
296
            if is_markdown && !want_source {
297
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
298
                let (base, raw) = (format!("{}/file/{r}/{dir}", rs.url), format!("{}/raw/{r}/{dir}", rs.url));
299
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &raw)))
300
            } else {
301
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
302
            }
303
        }
304
        _ => (vec![], None, None),
305
    };
306
    let permalink = f.target.permalink();
307
    let functions = match &f.body {
308
        FileBody::Text(text) if !is_image => crate::repos::functions::functions(&f.path, text),
309
        _ => vec![],
310
    };
311
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink, functions })
312
        .into_response())
313
}
314
315
/// Whether `path` is a file in the state `r` names.
316
async fn has_file(app: &Shared, repo: &crate::repos::RepoName, r: &str, path: &str) -> bool {
317
    let (spec, p) = (r.to_string(), path.to_string());
318
    app.repos
319
        .read(repo, move |repo, cache| {
320
            let target = view::resolve(repo, cache, &spec)?;
321
            Ok(cache.load(repo, &target.heads)?.snapshot.files.get(&p).is_some_and(|f| f.kind != oxy_core::objects::NodeKind::Dir))
322
        })
323
        .await
324
        .unwrap_or(false)
325
}
326
327
/// `GET /{owner}/{name}/raw/{ref}/{path}`: a file's bytes (hub spec §6.3),
328
/// where relative images in rendered Markdown point. `.flow/stamp` is the
329
/// state stamp of `{ref}` unless a real file is there (§13.2).
330
pub async fn raw_file(
331
    State(app): State<Shared>,
332
    viewer: Viewer,
333
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
334
) -> Result<Response, Error> {
335
    let shell = Shell::new(&app, &format!("/{owner}/{name}/raw/{r}/{path}"), &viewer);
336
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
337
    if path == super::flow::STAMP_IMAGE && !has_file(&app, &repo, &r, &path).await {
338
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{r}")).into_response());
339
    }
340
    let (spec, p) = (r.clone(), path.clone());
341
    let (file_name, bytes) = app
342
        .repos
343
        .read(&repo, move |repo, cache| {
344
            let target = view::resolve(repo, cache, &spec)?;
345
            view::raw(repo, cache, &target, &p)
346
        })
347
        .await
348
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
349
    Ok(super::raw(bytes, &file_name, true))
350
}
351
352
#[derive(Deserialize)]
353
pub struct LastQuery {
354
    /// Comma-separated paths.
355
    paths: String,
356
}
357
358
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
359
/// path, fetched by the tree page after it paints (hub spec §6.5).
360
pub async fn last_changes(
361
    State(app): State<Shared>,
362
    viewer: Viewer,
363
    Path((owner, name, r)): Path<(String, String, String)>,
364
    Query(q): Query<LastQuery>,
365
) -> Result<Response, Error> {
366
    let shell = Shell::new(&app, "", &viewer);
367
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
368
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
369
    let spec = r.clone();
370
    let found = app
371
        .repos
372
        .read(&repo, move |repo, cache| {
373
            let target = view::resolve(repo, cache, &spec)?;
374
            view::last_changes(repo, cache, &target.heads, &paths)
375
        })
376
        .await
377
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
378
    let now = crate::db::now_ms() as u64;
379
    let body: Vec<serde_json::Value> = found
380
        .into_iter()
381
        .map(|(p, c)| {
382
            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) })
383
        })
384
        .collect();
385
    Ok(axum::Json(body).into_response())
386
}
387
388
impl EntryKind {
389
    pub fn glyph(&self) -> &'static str {
390
        match self {
391
            EntryKind::Dir => "▸",
392
            EntryKind::File => "·",
393
            EntryKind::Symlink => "↪",
394
            EntryKind::Subrepo => "◫",
395
        }
396
    }
397
}
398
399
#[derive(Deserialize)]
400
pub struct CodeQuery {
401
    #[serde(default)]
402
    q: String,
403
    #[serde(default, rename = "ref")]
404
    r: Option<String>,
405
    #[serde(default)]
406
    path: String,
407
    #[serde(default)]
408
    re: Option<String>,
409
    #[serde(default)]
410
    case: Option<String>,
411
}
412
413
#[derive(Template)]
414
#[template(path = "code_search.html")]
415
pub struct CodeSearchPage {
416
    shell: Shell,
417
    repo: RepoShell,
418
    q: String,
419
    r: String,
420
    path: String,
421
    regex: bool,
422
    case: bool,
423
    results: crate::repos::search::Results,
424
    error: Option<String>,
425
}
426
427
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
428
pub async fn code_search(
429
    State(app): State<Shared>,
430
    viewer: Viewer,
431
    Path((owner, name)): Path<(String, String)>,
432
    Query(q): Query<CodeQuery>,
433
) -> Result<Page<CodeSearchPage>, Error> {
434
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
435
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
436
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
437
    let (regex, case) = (q.re.is_some(), q.case.is_some());
438
    let mut results = crate::repos::search::Results::default();
439
    let mut error = None;
440
    if !q.q.trim().is_empty() {
441
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
442
        let app2 = app.clone();
443
        let out = app
444
            .repos
445
            .read(&repo, move |repo, cache| {
446
                let target = view::resolve(repo, cache, &spec)?;
447
                let loaded = cache.load(repo, &target.heads)?;
448
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
449
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
450
                if let Some(hit) = app2.repos.searches.get(&key) {
451
                    return Ok(Ok(hit));
452
                }
453
                let res = crate::repos::search::run(
454
                    &loaded,
455
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
456
                );
457
                if let Ok(r) = &res {
458
                    app2.repos.searches.put(key, r.clone());
459
                }
460
                Ok(res)
461
            })
462
            .await
463
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
464
        match out {
465
            Ok(r) => results = r,
466
            Err(e) => error = Some(e),
467
        }
468
    }
469
    Ok(Page(CodeSearchPage {
470
        shell,
471
        repo: RepoShell::new(&app, &row, "code").with_role(role),
472
        q: q.q,
473
        r,
474
        path: q.path,
475
        regex,
476
        case,
477
        results,
478
        error,
479
    }))
480
}
481
482
#[cfg(test)]
483
mod tests {
484
    use super::remote_name;
485
486
    #[test]
487
    fn remote_names_come_from_the_host() {
488
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
489
        assert_eq!(remote_name("https://hub.example.org"), "hub");
490
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
491
        assert_eq!(remote_name("http://localhost:7300"), "hub");
492
        assert_eq!(remote_name("https://www.example.org"), "hub");
493
        assert_eq!(remote_name("https://My-Host.example"), "hub");
494
    }
495
}