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