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