OXYGENHUB
# 155cab142b63 oxygenhub / crates / hub / src / web / repo.rs
19.8 KiB · Rust · last changed Agents get their marks; contributors one row each; an assistant is tested when added 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
    // One row per account: a person's keys over time are one contributor,
112
    // their agents' shares summed beneath (as `oxy log` shows via).
113
    let mut merged: Vec<view::Contributor> = Vec::new();
114
    for c in std::mem::take(&mut o.contributors) {
115
        match c.account.as_ref().and_then(|a| merged.iter_mut().find(|m| m.account.as_deref() == Some(a))) {
116
            Some(m) => {
117
                m.changes += c.changes;
118
                for (who, n) in c.via {
119
                    match m.via.iter_mut().find(|(w, _)| *w == who) {
120
                        Some((_, k)) => *k += n,
121
                        None => m.via.push((who, n)),
122
                    }
123
                }
124
                m.via.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
125
            }
126
            None => merged.push(c),
127
        }
128
    }
129
    merged.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.name.cmp(&b.name)));
130
    o.contributors = merged;
131
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
132
    let readme_html = o.readme_html(&rs, &o.tree.target.label);
133
    let watching = match viewer.account() {
134
        Some(a) => crate::db::notify::watching(&app.db, a.id, row.id).await.unwrap_or(false),
135
        None => false,
136
    };
137
    let latest_release = crate::db::releases::latest(&app.db, row.id).await.ok().flatten();
138
    let quickstart = (o.changes == 0).then(|| Quickstart::new(&app, rs.can(crate::auth::Access::Write)));
139
    let fork = super::forks::info(&app, &shell, &viewer, &row).await;
140
    let starred = match viewer.account() {
141
        Some(a) => crate::db::repos::starred(&app.db, a.id, row.id).await.unwrap_or(false),
142
        None => false,
143
    };
144
    let (stars, watchers) = crate::db::repos::counts(&app.db, row.id).await.unwrap_or((0, 0));
145
    let topics = row.topic_list().into_iter().map(String::from).collect();
146
    Ok(Page(OverviewPage { shell, repo: rs, o, readme_html, watching, latest_release, quickstart, fork, starred, stars, watchers, topics }))
147
}
148
149
impl view::Overview {
150
    fn readme_html(&self, rs: &RepoShell, r: &str) -> Option<String> {
151
        self.tree.readme.as_ref().map(|md| {
152
            let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
153
            render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
154
        })
155
    }
156
}
157
158
#[derive(Template)]
159
#[template(path = "tree.html")]
160
pub struct TreePage {
161
    shell: Shell,
162
    repo: RepoShell,
163
    t: view::Tree,
164
    readme_html: Option<String>,
165
}
166
167
pub async fn tree_root(
168
    State(app): State<Shared>,
169
    viewer: Viewer,
170
    Path((owner, name, r)): Path<(String, String, String)>,
171
) -> Result<Page<TreePage>, Error> {
172
    tree(State(app), viewer, Path((owner, name, r, String::new()))).await
173
}
174
175
pub async fn tree(
176
    State(app): State<Shared>,
177
    viewer: Viewer,
178
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
179
) -> Result<Page<TreePage>, Error> {
180
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tree/{r}/{path}"), &viewer);
181
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
182
    let (spec, dir) = (r.clone(), path.clone());
183
    let t = app
184
        .repos
185
        .read(&repo, move |repo, cache| {
186
            let target = view::resolve(repo, cache, &spec)?;
187
            view::tree(repo, cache, target, &dir)
188
        })
189
        .await
190
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
191
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
192
    let readme_html = t.readme.as_ref().map(|md| {
193
        let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
194
        render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/raw/{r}/{dir}", rs.url))
195
    });
196
    Ok(Page(TreePage { shell, repo: rs, t, readme_html }))
197
}
198
199
#[derive(Deserialize)]
200
pub struct FileQuery {
201
    plain: Option<String>,
202
    blame: Option<String>,
203
    /// `source` shows a Markdown file's text instead of rendering it.
204
    view: Option<String>,
205
}
206
207
#[derive(Template)]
208
#[template(path = "file.html")]
209
pub struct FilePage {
210
    shell: Shell,
211
    repo: RepoShell,
212
    f: view::FileView,
213
    /// Highlighted lines when text.
214
    lines: Vec<String>,
215
    language: Option<&'static str>,
216
    markdown_html: Option<String>,
217
    is_image: bool,
218
    is_markdown: bool,
219
    blame: Option<Vec<BlameRow>>,
220
    /// The `{ref}` of this state for good (hub spec §6.6).
221
    permalink: Option<String>,
222
    /// Functions found in the file, each linking to its history.
223
    functions: Vec<crate::repos::functions::Function>,
224
}
225
226
/// A blame gutter entry: shown only on the first line of a run.
227
pub struct BlameRow {
228
    pub first: bool,
229
    pub hash: String,
230
    pub short: String,
231
    pub author: String,
232
    pub when_ms: u64,
233
    pub run: usize,
234
    /// 0 (the file's oldest line) to 9 (its newest), for shading.
235
    pub age: u8,
236
    /// The state address of the change's dependencies.
237
    pub before: Option<String>,
238
}
239
240
/// Shade steps from `when` within the file's span of times.
241
fn age_step(when: u64, oldest: u64, newest: u64) -> u8 {
242
    if newest <= oldest {
243
        return 9;
244
    }
245
    (((when.saturating_sub(oldest)) as u128 * 9 / (newest - oldest) as u128) as u8).min(9)
246
}
247
248
fn blame_rows(
249
    lines: &[oxy_core::repo::BlameLine],
250
    before: &std::collections::HashMap<oxy_core::hash::ChangeHash, Option<String>>,
251
) -> Vec<BlameRow> {
252
    let oldest = lines.iter().map(|l| l.when_ms).min().unwrap_or(0);
253
    let newest = lines.iter().map(|l| l.when_ms).max().unwrap_or(0);
254
    let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
255
    let mut i = 0;
256
    while i < lines.len() {
257
        let mut run = 1;
258
        while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
259
            run += 1;
260
        }
261
        for k in 0..run {
262
            let l = &lines[i + k];
263
            rows.push(BlameRow {
264
                first: k == 0,
265
                hash: l.hash.to_hex(),
266
                short: l.hash.short(8),
267
                author: l.author.clone(),
268
                when_ms: l.when_ms,
269
                run,
270
                age: age_step(l.when_ms, oldest, newest),
271
                before: before.get(&l.hash).cloned().flatten(),
272
            });
273
        }
274
        i += run;
275
    }
276
    rows
277
}
278
279
pub async fn file(
280
    State(app): State<Shared>,
281
    viewer: Viewer,
282
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
283
    Query(q): Query<FileQuery>,
284
) -> Result<Response, Error> {
285
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
286
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
287
    if path == super::flow::RUN_LINK && !has_file(&app, &repo, &r, &path).await {
288
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/at/{r}")).into_response());
289
    }
290
    let limit = app.config.limits.render_limit.0;
291
    if q.plain.is_some() {
292
        // Bytes only: no last change, sidebar or highlighting to compute.
293
        let (spec, p) = (r.clone(), path.clone());
294
        let (file_name, bytes) = app
295
            .repos
296
            .read(&repo, move |repo, cache| view::raw(repo, cache, &view::resolve(repo, cache, &spec)?, &p))
297
            .await
298
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
299
        return Ok(super::raw(bytes, &file_name, true));
300
    }
301
    let want_blame = q.blame.is_some();
302
    let (spec, p) = (r.clone(), path.clone());
303
    let (f, blame) = app
304
        .repos
305
        .read(&repo, move |repo, cache| {
306
            let target = view::resolve(repo, cache, &spec)?;
307
            if want_blame {
308
                let b = view::blame(repo, cache, target, &p, limit)?;
309
                let rows = blame_rows(&b.lines, &b.before);
310
                Ok((b.file, Some(rows)))
311
            } else {
312
                Ok((view::file(repo, cache, target, &p, limit)?, None))
313
            }
314
        })
315
        .await
316
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
317
    if q.plain.is_some() {
318
        return Ok(super::raw(f.bytes, &f.name, true));
319
    }
320
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
321
    let is_image = super::mime_of(&f.name).starts_with("image/");
322
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
323
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
324
    let (lines, language, markdown_html) = match &f.body {
325
        FileBody::Text(text) if !is_image => {
326
            if is_markdown && !want_source {
327
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
328
                let (base, raw) = (format!("{}/file/{r}/{dir}", rs.url), format!("{}/raw/{r}/{dir}", rs.url));
329
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &raw)))
330
            } else {
331
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
332
            }
333
        }
334
        _ => (vec![], None, None),
335
    };
336
    let permalink = f.target.permalink();
337
    let functions = match &f.body {
338
        FileBody::Text(text) if !is_image => crate::repos::functions::functions(&f.path, text),
339
        _ => vec![],
340
    };
341
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink, functions })
342
        .into_response())
343
}
344
345
/// Whether `path` is a file in the state `r` names.
346
async fn has_file(app: &Shared, repo: &crate::repos::RepoName, r: &str, path: &str) -> bool {
347
    let (spec, p) = (r.to_string(), path.to_string());
348
    app.repos
349
        .read(repo, move |repo, cache| {
350
            let target = view::resolve(repo, cache, &spec)?;
351
            Ok(cache.load(repo, &target.heads)?.snapshot.files.get(&p).is_some_and(|f| f.kind != oxy_core::objects::NodeKind::Dir))
352
        })
353
        .await
354
        .unwrap_or(false)
355
}
356
357
/// `GET /{owner}/{name}/raw/{ref}/{path}`: a file's bytes (hub spec §6.3),
358
/// where relative images in rendered Markdown point. `.flow/stamp` is the
359
/// state stamp of `{ref}` unless a real file is there (§13.2).
360
pub async fn raw_file(
361
    State(app): State<Shared>,
362
    viewer: Viewer,
363
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
364
) -> Result<Response, Error> {
365
    let shell = Shell::new(&app, &format!("/{owner}/{name}/raw/{r}/{path}"), &viewer);
366
    let (repo, _row, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
367
    if path == super::flow::STAMP_IMAGE && !has_file(&app, &repo, &r, &path).await {
368
        return Ok(axum::response::Redirect::to(&format!("/{owner}/{name}/flow/stamp/{r}")).into_response());
369
    }
370
    let (spec, p) = (r.clone(), path.clone());
371
    let (file_name, bytes) = app
372
        .repos
373
        .read(&repo, move |repo, cache| {
374
            let target = view::resolve(repo, cache, &spec)?;
375
            view::raw(repo, cache, &target, &p)
376
        })
377
        .await
378
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
379
    Ok(super::raw(bytes, &file_name, true))
380
}
381
382
#[derive(Deserialize)]
383
pub struct LastQuery {
384
    /// Comma-separated paths.
385
    paths: String,
386
}
387
388
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
389
/// path, fetched by the tree page after it paints (hub spec §6.5).
390
pub async fn last_changes(
391
    State(app): State<Shared>,
392
    viewer: Viewer,
393
    Path((owner, name, r)): Path<(String, String, String)>,
394
    Query(q): Query<LastQuery>,
395
) -> Result<Response, Error> {
396
    let shell = Shell::new(&app, "", &viewer);
397
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
398
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
399
    let spec = r.clone();
400
    let found = app
401
        .repos
402
        .read(&repo, move |repo, cache| {
403
            let target = view::resolve(repo, cache, &spec)?;
404
            view::last_changes(repo, cache, &target.heads, &paths)
405
        })
406
        .await
407
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
408
    let now = crate::db::now_ms() as u64;
409
    let body: Vec<serde_json::Value> = found
410
        .into_iter()
411
        .map(|(p, c)| {
412
            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) })
413
        })
414
        .collect();
415
    Ok(axum::Json(body).into_response())
416
}
417
418
impl EntryKind {
419
    pub fn glyph(&self) -> &'static str {
420
        match self {
421
            EntryKind::Dir => "▸",
422
            EntryKind::File => "·",
423
            EntryKind::Symlink => "↪",
424
            EntryKind::Subrepo => "◫",
425
        }
426
    }
427
}
428
429
#[derive(Deserialize)]
430
pub struct CodeQuery {
431
    #[serde(default)]
432
    q: String,
433
    #[serde(default, rename = "ref")]
434
    r: Option<String>,
435
    #[serde(default)]
436
    path: String,
437
    #[serde(default)]
438
    re: Option<String>,
439
    #[serde(default)]
440
    case: Option<String>,
441
}
442
443
#[derive(Template)]
444
#[template(path = "code_search.html")]
445
pub struct CodeSearchPage {
446
    shell: Shell,
447
    repo: RepoShell,
448
    q: String,
449
    r: String,
450
    path: String,
451
    regex: bool,
452
    case: bool,
453
    results: crate::repos::search::Results,
454
    error: Option<String>,
455
}
456
457
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
458
pub async fn code_search(
459
    State(app): State<Shared>,
460
    viewer: Viewer,
461
    Path((owner, name)): Path<(String, String)>,
462
    Query(q): Query<CodeQuery>,
463
) -> Result<Page<CodeSearchPage>, Error> {
464
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
465
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
466
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
467
    let (regex, case) = (q.re.is_some(), q.case.is_some());
468
    let mut results = crate::repos::search::Results::default();
469
    let mut error = None;
470
    if !q.q.trim().is_empty() {
471
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
472
        let app2 = app.clone();
473
        let out = app
474
            .repos
475
            .read(&repo, move |repo, cache| {
476
                let target = view::resolve(repo, cache, &spec)?;
477
                let loaded = cache.load(repo, &target.heads)?;
478
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
479
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
480
                if let Some(hit) = app2.repos.searches.get(&key) {
481
                    return Ok(Ok(hit));
482
                }
483
                let res = crate::repos::search::run(
484
                    &loaded,
485
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
486
                );
487
                if let Ok(r) = &res {
488
                    app2.repos.searches.put(key, r.clone());
489
                }
490
                Ok(res)
491
            })
492
            .await
493
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
494
        match out {
495
            Ok(r) => results = r,
496
            Err(e) => error = Some(e),
497
        }
498
    }
499
    Ok(Page(CodeSearchPage {
500
        shell,
501
        repo: RepoShell::new(&app, &row, "code").with_role(role),
502
        q: q.q,
503
        r,
504
        path: q.path,
505
        regex,
506
        case,
507
        results,
508
        error,
509
    }))
510
}
511
512
#[cfg(test)]
513
mod tests {
514
    use super::remote_name;
515
516
    #[test]
517
    fn remote_names_come_from_the_host() {
518
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
519
        assert_eq!(remote_name("https://hub.example.org"), "hub");
520
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
521
        assert_eq!(remote_name("http://localhost:7300"), "hub");
522
        assert_eq!(remote_name("https://www.example.org"), "hub");
523
        assert_eq!(remote_name("https://My-Host.example"), "hub");
524
    }
525
}