OXYGENHUB
# bf3d07541368 oxygenhub / crates / hub / src / web / repo.rs
17.8 KiB · Rust · last changed Flow state stamps: a state-addressed, verifiable pipeline result for READMEs, and a raw route so Markdown images work 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
}
197
198
/// A blame gutter entry: shown only on the first line of a run.
199
pub struct BlameRow {
200
    pub first: bool,
201
    pub hash: String,
202
    pub short: String,
203
    pub author: String,
204
    pub when_ms: u64,
205
    pub run: usize,
206
    /// 0 (the file's oldest line) to 9 (its newest), for shading.
207
    pub age: u8,
208
    /// The state address of the change's dependencies.
209
    pub before: Option<String>,
210
}
211
212
/// Shade steps from `when` within the file's span of times.
213
fn age_step(when: u64, oldest: u64, newest: u64) -> u8 {
214
    if newest <= oldest {
215
        return 9;
216
    }
217
    (((when.saturating_sub(oldest)) as u128 * 9 / (newest - oldest) as u128) as u8).min(9)
218
}
219
220
fn blame_rows(
221
    lines: &[oxy_core::repo::BlameLine],
222
    before: &std::collections::HashMap<oxy_core::hash::ChangeHash, Option<String>>,
223
) -> Vec<BlameRow> {
224
    let oldest = lines.iter().map(|l| l.when_ms).min().unwrap_or(0);
225
    let newest = lines.iter().map(|l| l.when_ms).max().unwrap_or(0);
226
    let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
227
    let mut i = 0;
228
    while i < lines.len() {
229
        let mut run = 1;
230
        while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
231
            run += 1;
232
        }
233
        for k in 0..run {
234
            let l = &lines[i + k];
235
            rows.push(BlameRow {
236
                first: k == 0,
237
                hash: l.hash.to_hex(),
238
                short: l.hash.short(8),
239
                author: l.author.clone(),
240
                when_ms: l.when_ms,
241
                run,
242
                age: age_step(l.when_ms, oldest, newest),
243
                before: before.get(&l.hash).cloned().flatten(),
244
            });
245
        }
246
        i += run;
247
    }
248
    rows
249
}
250
251
pub async fn file(
252
    State(app): State<Shared>,
253
    viewer: Viewer,
254
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
255
    Query(q): Query<FileQuery>,
256
) -> Result<Response, Error> {
257
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
258
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
259
    if path == super::flow::RUN_LINK && !has_file(&app, &repo, &r, &path).await {
260
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/at/{r}")).into_response());
261
    }
262
    let limit = app.config.limits.render_limit.0;
263
    let want_blame = q.blame.is_some();
264
    let (spec, p) = (r.clone(), path.clone());
265
    let (f, blame) = app
266
        .repos
267
        .read(&repo, move |repo, cache| {
268
            let target = view::resolve(repo, cache, &spec)?;
269
            if want_blame {
270
                let b = view::blame(repo, cache, target, &p, limit)?;
271
                let rows = blame_rows(&b.lines, &b.before);
272
                Ok((b.file, Some(rows)))
273
            } else {
274
                Ok((view::file(repo, cache, target, &p, limit)?, None))
275
            }
276
        })
277
        .await
278
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
279
    if q.plain.is_some() {
280
        return Ok(super::raw(f.bytes, &f.name, true));
281
    }
282
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
283
    let is_image = super::mime_of(&f.name).starts_with("image/");
284
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
285
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
286
    let (lines, language, markdown_html) = match &f.body {
287
        FileBody::Text(text) if !is_image => {
288
            if is_markdown && !want_source {
289
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
290
                let (base, raw) = (format!("{}/file/{r}/{dir}", rs.url), format!("{}/raw/{r}/{dir}", rs.url));
291
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &raw)))
292
            } else {
293
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
294
            }
295
        }
296
        _ => (vec![], None, None),
297
    };
298
    let permalink = f.target.permalink();
299
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink }).into_response())
300
}
301
302
/// Whether `path` is a file in the state `r` names.
303
async fn has_file(app: &Shared, repo: &crate::repos::RepoName, r: &str, path: &str) -> bool {
304
    let (spec, p) = (r.to_string(), path.to_string());
305
    app.repos
306
        .read(repo, move |repo, cache| {
307
            let target = view::resolve(repo, cache, &spec)?;
308
            Ok(cache.load(repo, &target.heads)?.snapshot.files.get(&p).is_some_and(|f| f.kind != oxy_core::objects::NodeKind::Dir))
309
        })
310
        .await
311
        .unwrap_or(false)
312
}
313
314
/// `GET /{owner}/{name}/raw/{ref}/{path}`: a file's bytes (hub spec §6.3),
315
/// where relative images in rendered Markdown point. `.flow/stamp` is the
316
/// state stamp of `{ref}` unless a real file is there (§13.2).
317
pub async fn raw_file(
318
    State(app): State<Shared>,
319
    viewer: Viewer,
320
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
321
) -> Result<Response, Error> {
322
    let shell = Shell::new(&app, &format!("/{owner}/{name}/raw/{r}/{path}"), &viewer);
323
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
324
    if path == super::flow::STAMP_IMAGE && !has_file(&app, &repo, &r, &path).await {
325
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{r}")).into_response());
326
    }
327
    let (spec, p) = (r.clone(), path.clone());
328
    let (file_name, bytes) = app
329
        .repos
330
        .read(&repo, move |repo, cache| {
331
            let target = view::resolve(repo, cache, &spec)?;
332
            view::raw(repo, cache, &target, &p)
333
        })
334
        .await
335
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
336
    Ok(super::raw(bytes, &file_name, true))
337
}
338
339
#[derive(Deserialize)]
340
pub struct LastQuery {
341
    /// Comma-separated paths.
342
    paths: String,
343
}
344
345
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
346
/// path, fetched by the tree page after it paints (hub spec §6.5).
347
pub async fn last_changes(
348
    State(app): State<Shared>,
349
    viewer: Viewer,
350
    Path((owner, name, r)): Path<(String, String, String)>,
351
    Query(q): Query<LastQuery>,
352
) -> Result<Response, Error> {
353
    let shell = Shell::new(&app, "", &viewer);
354
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
355
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
356
    let spec = r.clone();
357
    let found = app
358
        .repos
359
        .read(&repo, move |repo, cache| {
360
            let target = view::resolve(repo, cache, &spec)?;
361
            view::last_changes(repo, cache, &target.heads, &paths)
362
        })
363
        .await
364
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
365
    let now = crate::db::now_ms() as u64;
366
    let body: Vec<serde_json::Value> = found
367
        .into_iter()
368
        .map(|(p, c)| {
369
            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) })
370
        })
371
        .collect();
372
    Ok(axum::Json(body).into_response())
373
}
374
375
impl EntryKind {
376
    pub fn glyph(&self) -> &'static str {
377
        match self {
378
            EntryKind::Dir => "▸",
379
            EntryKind::File => "·",
380
            EntryKind::Symlink => "↪",
381
            EntryKind::Subrepo => "◫",
382
        }
383
    }
384
}
385
386
#[derive(Deserialize)]
387
pub struct CodeQuery {
388
    #[serde(default)]
389
    q: String,
390
    #[serde(default, rename = "ref")]
391
    r: Option<String>,
392
    #[serde(default)]
393
    path: String,
394
    #[serde(default)]
395
    re: Option<String>,
396
    #[serde(default)]
397
    case: Option<String>,
398
}
399
400
#[derive(Template)]
401
#[template(path = "code_search.html")]
402
pub struct CodeSearchPage {
403
    shell: Shell,
404
    repo: RepoShell,
405
    q: String,
406
    r: String,
407
    path: String,
408
    regex: bool,
409
    case: bool,
410
    results: crate::repos::search::Results,
411
    error: Option<String>,
412
}
413
414
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
415
pub async fn code_search(
416
    State(app): State<Shared>,
417
    viewer: Viewer,
418
    Path((owner, name)): Path<(String, String)>,
419
    Query(q): Query<CodeQuery>,
420
) -> Result<Page<CodeSearchPage>, Error> {
421
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
422
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
423
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
424
    let (regex, case) = (q.re.is_some(), q.case.is_some());
425
    let mut results = crate::repos::search::Results::default();
426
    let mut error = None;
427
    if !q.q.trim().is_empty() {
428
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
429
        let app2 = app.clone();
430
        let out = app
431
            .repos
432
            .read(&repo, move |repo, cache| {
433
                let target = view::resolve(repo, cache, &spec)?;
434
                let loaded = cache.load(repo, &target.heads)?;
435
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
436
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
437
                if let Some(hit) = app2.repos.searches.get(&key) {
438
                    return Ok(Ok(hit));
439
                }
440
                let res = crate::repos::search::run(
441
                    &loaded,
442
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
443
                );
444
                if let Ok(r) = &res {
445
                    app2.repos.searches.put(key, r.clone());
446
                }
447
                Ok(res)
448
            })
449
            .await
450
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
451
        match out {
452
            Ok(r) => results = r,
453
            Err(e) => error = Some(e),
454
        }
455
    }
456
    Ok(Page(CodeSearchPage {
457
        shell,
458
        repo: RepoShell::new(&app, &row, "code").with_role(role),
459
        q: q.q,
460
        r,
461
        path: q.path,
462
        regex,
463
        case,
464
        results,
465
        error,
466
    }))
467
}
468
469
#[cfg(test)]
470
mod tests {
471
    use super::remote_name;
472
473
    #[test]
474
    fn remote_names_come_from_the_host() {
475
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
476
        assert_eq!(remote_name("https://hub.example.org"), "hub");
477
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
478
        assert_eq!(remote_name("http://localhost:7300"), "hub");
479
        assert_eq!(remote_name("https://www.example.org"), "hub");
480
        assert_eq!(remote_name("https://My-Host.example"), "hub");
481
    }
482
}