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