OXYGENHUB
# bf1ab3458db1 oxygenhub / crates / hub / src / web / repo.rs
11.2 KiB · Rust · last changed Milestone 0.6: releases, Git mirror, code search, anchored API comments 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
}
23
24
pub async fn overview(
25
    State(app): State<Shared>,
26
    viewer: Viewer,
27
    Path((owner, name)): Path<(String, String)>,
28
) -> Result<Page<OverviewPage>, Error> {
29
    let shell = Shell::new(&app, &format!("/{owner}/{name}"), &viewer);
30
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
31
    let default = row.default_bookmark.clone();
32
    let o =
33
        app.repos.read(&repo, move |r, cache| view::overview(r, cache, &default)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
34
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
35
    let readme_html = o.readme_html(&rs, &o.tree.target.label);
36
    let watching = match viewer.account() {
37
        Some(a) => crate::db::notify::watching(&app.db, a.id, row.id).await.unwrap_or(false),
38
        None => false,
39
    };
40
    let latest_release = crate::db::releases::latest(&app.db, row.id).await.ok().flatten();
41
    Ok(Page(OverviewPage { shell, repo: rs, o, readme_html, watching, latest_release }))
42
}
43
44
impl view::Overview {
45
    fn readme_html(&self, rs: &RepoShell, r: &str) -> Option<String> {
46
        self.tree.readme.as_ref().map(|md| {
47
            let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
48
            render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/file/{r}/{dir}", rs.url))
49
        })
50
    }
51
}
52
53
#[derive(Template)]
54
#[template(path = "tree.html")]
55
pub struct TreePage {
56
    shell: Shell,
57
    repo: RepoShell,
58
    t: view::Tree,
59
    readme_html: Option<String>,
60
}
61
62
pub async fn tree_root(
63
    State(app): State<Shared>,
64
    viewer: Viewer,
65
    Path((owner, name, r)): Path<(String, String, String)>,
66
) -> Result<Page<TreePage>, Error> {
67
    tree(State(app), viewer, Path((owner, name, r, String::new()))).await
68
}
69
70
pub async fn tree(
71
    State(app): State<Shared>,
72
    viewer: Viewer,
73
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
74
) -> Result<Page<TreePage>, Error> {
75
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tree/{r}/{path}"), &viewer);
76
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
77
    let (spec, dir) = (r.clone(), path.clone());
78
    let t = app
79
        .repos
80
        .read(&repo, move |repo, cache| {
81
            let target = view::resolve(repo, cache, &spec)?;
82
            view::tree(repo, cache, target, &dir)
83
        })
84
        .await
85
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
86
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
87
    let readme_html = t.readme.as_ref().map(|md| {
88
        let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
89
        render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/file/{r}/{dir}", rs.url))
90
    });
91
    Ok(Page(TreePage { shell, repo: rs, t, readme_html }))
92
}
93
94
#[derive(Deserialize)]
95
pub struct FileQuery {
96
    plain: Option<String>,
97
    blame: Option<String>,
98
    /// `source` shows a Markdown file's text instead of rendering it.
99
    view: Option<String>,
100
}
101
102
#[derive(Template)]
103
#[template(path = "file.html")]
104
pub struct FilePage {
105
    shell: Shell,
106
    repo: RepoShell,
107
    f: view::FileView,
108
    /// Highlighted lines when text.
109
    lines: Vec<String>,
110
    language: Option<&'static str>,
111
    markdown_html: Option<String>,
112
    is_image: bool,
113
    is_markdown: bool,
114
    blame: Option<Vec<BlameRow>>,
115
}
116
117
/// A blame gutter entry: shown only on the first line of a run.
118
pub struct BlameRow {
119
    pub first: bool,
120
    pub hash: String,
121
    pub short: String,
122
    pub author: String,
123
    pub when_ms: u64,
124
    pub run: usize,
125
}
126
127
pub async fn file(
128
    State(app): State<Shared>,
129
    viewer: Viewer,
130
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
131
    Query(q): Query<FileQuery>,
132
) -> Result<Response, Error> {
133
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
134
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
135
    let limit = app.config.limits.render_limit.0;
136
    let want_blame = q.blame.is_some();
137
    let (spec, p) = (r.clone(), path.clone());
138
    let (f, blame) = app
139
        .repos
140
        .read(&repo, move |repo, cache| {
141
            let target = view::resolve(repo, cache, &spec)?;
142
            if want_blame {
143
                let b = view::blame(repo, cache, target, &p, limit)?;
144
                Ok((b.file, Some(b.lines)))
145
            } else {
146
                Ok((view::file(repo, cache, target, &p, limit)?, None))
147
            }
148
        })
149
        .await
150
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
151
    if q.plain.is_some() {
152
        return Ok(super::raw(f.bytes, &f.name, true));
153
    }
154
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
155
    let is_image = super::mime_of(&f.name).starts_with("image/");
156
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
157
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
158
    let (lines, language, markdown_html) = match &f.body {
159
        FileBody::Text(text) if !is_image => {
160
            if is_markdown && !want_source {
161
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
162
                let base = format!("{}/file/{r}/{dir}", rs.url);
163
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &base)))
164
            } else {
165
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
166
            }
167
        }
168
        _ => (vec![], None, None),
169
    };
170
    let blame = blame.map(|lines| {
171
        let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
172
        let mut i = 0;
173
        while i < lines.len() {
174
            let mut run = 1;
175
            while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
176
                run += 1;
177
            }
178
            for k in 0..run {
179
                let l = &lines[i + k];
180
                rows.push(BlameRow {
181
                    first: k == 0,
182
                    hash: l.hash.to_hex(),
183
                    short: l.hash.short(8),
184
                    author: l.author.clone(),
185
                    when_ms: l.when_ms,
186
                    run,
187
                });
188
            }
189
            i += run;
190
        }
191
        rows
192
    });
193
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame }).into_response())
194
}
195
196
#[derive(Deserialize)]
197
pub struct LastQuery {
198
    /// Comma-separated paths.
199
    paths: String,
200
}
201
202
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
203
/// path, fetched by the tree page after it paints (hub spec §6.5).
204
pub async fn last_changes(
205
    State(app): State<Shared>,
206
    viewer: Viewer,
207
    Path((owner, name, r)): Path<(String, String, String)>,
208
    Query(q): Query<LastQuery>,
209
) -> Result<Response, Error> {
210
    let shell = Shell::new(&app, "", &viewer);
211
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
212
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
213
    let spec = r.clone();
214
    let found = app
215
        .repos
216
        .read(&repo, move |repo, cache| {
217
            let target = view::resolve(repo, cache, &spec)?;
218
            view::last_changes(repo, cache, &target.heads, &paths)
219
        })
220
        .await
221
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
222
    let now = crate::db::now_ms() as u64;
223
    let body: Vec<serde_json::Value> = found
224
        .into_iter()
225
        .map(|(p, c)| {
226
            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) })
227
        })
228
        .collect();
229
    Ok(axum::Json(body).into_response())
230
}
231
232
impl EntryKind {
233
    pub fn glyph(&self) -> &'static str {
234
        match self {
235
            EntryKind::Dir => "▸",
236
            EntryKind::File => "·",
237
            EntryKind::Symlink => "↪",
238
            EntryKind::Subrepo => "◫",
239
        }
240
    }
241
}
242
243
#[derive(Deserialize)]
244
pub struct CodeQuery {
245
    #[serde(default)]
246
    q: String,
247
    #[serde(default, rename = "ref")]
248
    r: Option<String>,
249
    #[serde(default)]
250
    path: String,
251
    #[serde(default)]
252
    re: Option<String>,
253
    #[serde(default)]
254
    case: Option<String>,
255
}
256
257
#[derive(Template)]
258
#[template(path = "code_search.html")]
259
pub struct CodeSearchPage {
260
    shell: Shell,
261
    repo: RepoShell,
262
    q: String,
263
    r: String,
264
    path: String,
265
    regex: bool,
266
    case: bool,
267
    results: crate::repos::search::Results,
268
    error: Option<String>,
269
}
270
271
/// `GET /{owner}/{name}/search?q=…&ref=…&re=1&case=1&path=…` (hub spec §11).
272
pub async fn code_search(
273
    State(app): State<Shared>,
274
    viewer: Viewer,
275
    Path((owner, name)): Path<(String, String)>,
276
    Query(q): Query<CodeQuery>,
277
) -> Result<Page<CodeSearchPage>, Error> {
278
    let shell = Shell::new(&app, &format!("/{owner}/{name}/search"), &viewer);
279
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
280
    let r = q.r.clone().filter(|x| !x.is_empty()).unwrap_or_else(|| row.default_bookmark.clone());
281
    let (regex, case) = (q.re.is_some(), q.case.is_some());
282
    let mut results = crate::repos::search::Results::default();
283
    let mut error = None;
284
    if !q.q.trim().is_empty() {
285
        let (text, spec, prefix) = (q.q.clone(), r.clone(), q.path.trim_matches('/').to_string());
286
        let app2 = app.clone();
287
        let out = app
288
            .repos
289
            .read(&repo, move |repo, cache| {
290
                let target = view::resolve(repo, cache, &spec)?;
291
                let loaded = cache.load(repo, &target.heads)?;
292
                let state = oxy_core::objects::StateObject::new(loaded.heads.clone()).hash().to_hex();
293
                let key = format!("{state}\0{text}\0{regex}\0{case}\0{prefix}");
294
                if let Some(hit) = app2.repos.searches.get(&key) {
295
                    return Ok(Ok(hit));
296
                }
297
                let res = crate::repos::search::run(
298
                    &loaded,
299
                    &crate::repos::search::Query { text: &text, regex, case_sensitive: case, path_prefix: &prefix },
300
                );
301
                if let Ok(r) = &res {
302
                    app2.repos.searches.put(key, r.clone());
303
                }
304
                Ok(res)
305
            })
306
            .await
307
            .map_err(|e| Error::from_repo(shell.clone(), e))?;
308
        match out {
309
            Ok(r) => results = r,
310
            Err(e) => error = Some(e),
311
        }
312
    }
313
    Ok(Page(CodeSearchPage {
314
        shell,
315
        repo: RepoShell::new(&app, &row, "code").with_role(role),
316
        q: q.q,
317
        r,
318
        path: q.path,
319
        regex,
320
        case,
321
        results,
322
        error,
323
    }))
324
}