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