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