OXYGENHUB
# 16cb2b3aa947 oxygenhub / crates / hub / src / web / repo.rs
16.0 KiB · Rust · last changed File view: tree sidebar, state permalinks (y, heads joined with +), line range bar with copy lines and copy permalink, blame age shading and blame before this change 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!("{}/file/{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!("{}/file/{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
    let limit = app.config.limits.render_limit.0;
260
    let want_blame = q.blame.is_some();
261
    let (spec, p) = (r.clone(), path.clone());
262
    let (f, blame) = app
263
        .repos
264
        .read(&repo, move |repo, cache| {
265
            let target = view::resolve(repo, cache, &spec)?;
266
            if want_blame {
267
                let b = view::blame(repo, cache, target, &p, limit)?;
268
                let rows = blame_rows(&b.lines, &b.before);
269
                Ok((b.file, Some(rows)))
270
            } else {
271
                Ok((view::file(repo, cache, target, &p, limit)?, None))
272
            }
273
        })
274
        .await
275
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
276
    if q.plain.is_some() {
277
        return Ok(super::raw(f.bytes, &f.name, true));
278
    }
279
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
280
    let is_image = super::mime_of(&f.name).starts_with("image/");
281
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
282
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
283
    let (lines, language, markdown_html) = match &f.body {
284
        FileBody::Text(text) if !is_image => {
285
            if is_markdown && !want_source {
286
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
287
                let base = format!("{}/file/{r}/{dir}", rs.url);
288
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &base)))
289
            } else {
290
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
291
            }
292
        }
293
        _ => (vec![], None, None),
294
    };
295
    let permalink = f.target.permalink();
296
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame, permalink }).into_response())
297
}
298
299
#[derive(Deserialize)]
300
pub struct LastQuery {
301
    /// Comma-separated paths.
302
    paths: String,
303
}
304
305
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
306
/// path, fetched by the tree page after it paints (hub spec §6.5).
307
pub async fn last_changes(
308
    State(app): State<Shared>,
309
    viewer: Viewer,
310
    Path((owner, name, r)): Path<(String, String, String)>,
311
    Query(q): Query<LastQuery>,
312
) -> Result<Response, Error> {
313
    let shell = Shell::new(&app, "", &viewer);
314
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
315
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
316
    let spec = r.clone();
317
    let found = app
318
        .repos
319
        .read(&repo, move |repo, cache| {
320
            let target = view::resolve(repo, cache, &spec)?;
321
            view::last_changes(repo, cache, &target.heads, &paths)
322
        })
323
        .await
324
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
325
    let now = crate::db::now_ms() as u64;
326
    let body: Vec<serde_json::Value> = found
327
        .into_iter()
328
        .map(|(p, c)| {
329
            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) })
330
        })
331
        .collect();
332
    Ok(axum::Json(body).into_response())
333
}
334
335
impl EntryKind {
336
    pub fn glyph(&self) -> &'static str {
337
        match self {
338
            EntryKind::Dir => "▸",
339
            EntryKind::File => "·",
340
            EntryKind::Symlink => "↪",
341
            EntryKind::Subrepo => "◫",
342
        }
343
    }
344
}
345
346
#[derive(Deserialize)]
347
pub struct CodeQuery {
348
    #[serde(default)]
349
    q: String,
350
    #[serde(default, rename = "ref")]
351
    r: Option<String>,
352
    #[serde(default)]
353
    path: String,
354
    #[serde(default)]
355
    re: Option<String>,
356
    #[serde(default)]
357
    case: Option<String>,
358
}
359
360
#[derive(Template)]
361
#[template(path = "code_search.html")]
362
pub struct CodeSearchPage {
363
    shell: Shell,
364
    repo: RepoShell,
365
    q: String,
366
    r: String,
367
    path: String,
368
    regex: bool,
369
    case: bool,
370
    results: crate::repos::search::Results,
371
    error: Option<String>,
372
}
373
374
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
375
pub async fn code_search(
376
    State(app): State<Shared>,
377
    viewer: Viewer,
378
    Path((owner, name)): Path<(String, String)>,
379
    Query(q): Query<CodeQuery>,
380
) -> Result<Page<CodeSearchPage>, Error> {
381
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
382
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
383
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
384
    let (regex, case) = (q.re.is_some(), q.case.is_some());
385
    let mut results = crate::repos::search::Results::default();
386
    let mut error = None;
387
    if !q.q.trim().is_empty() {
388
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
389
        let app2 = app.clone();
390
        let out = app
391
            .repos
392
            .read(&repo, move |repo, cache| {
393
                let target = view::resolve(repo, cache, &spec)?;
394
                let loaded = cache.load(repo, &target.heads)?;
395
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
396
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
397
                if let Some(hit) = app2.repos.searches.get(&key) {
398
                    return Ok(Ok(hit));
399
                }
400
                let res = crate::repos::search::run(
401
                    &loaded,
402
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
403
                );
404
                if let Ok(r) = &res {
405
                    app2.repos.searches.put(key, r.clone());
406
                }
407
                Ok(res)
408
            })
409
            .await
410
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
411
        match out {
412
            Ok(r) => results = r,
413
            Err(e) => error = Some(e),
414
        }
415
    }
416
    Ok(Page(CodeSearchPage {
417
        shell,
418
        repo: RepoShell::new(&app, &row, "code").with_role(role),
419
        q: q.q,
420
        r,
421
        path: q.path,
422
        regex,
423
        case,
424
        results,
425
        error,
426
    }))
427
}
428
429
#[cfg(test)]
430
mod tests {
431
    use super::remote_name;
432
433
    #[test]
434
    fn remote_names_come_from_the_host() {
435
        assert_eq!(remote_name("https://earth.andymccall.xyz:7343"), "earth");
436
        assert_eq!(remote_name("https://hub.example.org"), "hub");
437
        assert_eq!(remote_name("http://127.0.0.1:7300"), "hub");
438
        assert_eq!(remote_name("http://localhost:7300"), "hub");
439
        assert_eq!(remote_name("https://www.example.org"), "hub");
440
        assert_eq!(remote_name("https://My-Host.example"), "hub");
441
    }
442
}