OXYGENHUB
# c0fac31d36fd oxygenhub / crates / hub / src / web / repo.rs
8.4 KiB · Rust · last changed Milestone 0.4: issues and notifications 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
}
22
23
pub async fn overview(
24
    State(app): State<Shared>,
25
    viewer: Viewer,
26
    Path((owner, name)): Path<(String, String)>,
27
) -> Result<Page<OverviewPage>, Error> {
28
    let shell = Shell::new(&app, &format!("/{owner}/{name}"), &viewer);
29
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
30
    let default = row.default_bookmark.clone();
31
    let o =
32
        app.repos.read(&repo, move |r, cache| view::overview(r, cache, &default)).await.map_err(|e| Error::from_repo(shell.clone(), e))?;
33
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
34
    let readme_html = o.readme_html(&rs, &o.tree.target.label);
35
    let watching = match viewer.account() {
36
        Some(a) => crate::db::notify::watching(&app.db, a.id, row.id).await.unwrap_or(false),
37
        None => false,
38
    };
39
    Ok(Page(OverviewPage { shell, repo: rs, o, readme_html, watching }))
40
}
41
42
impl view::Overview {
43
    fn readme_html(&self, rs: &RepoShell, r: &str) -> Option<String> {
44
        self.tree.readme.as_ref().map(|md| {
45
            let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
46
            render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/file/{r}/{dir}", rs.url))
47
        })
48
    }
49
}
50
51
#[derive(Template)]
52
#[template(path = "tree.html")]
53
pub struct TreePage {
54
    shell: Shell,
55
    repo: RepoShell,
56
    t: view::Tree,
57
    readme_html: Option<String>,
58
}
59
60
pub async fn tree_root(
61
    State(app): State<Shared>,
62
    viewer: Viewer,
63
    Path((owner, name, r)): Path<(String, String, String)>,
64
) -> Result<Page<TreePage>, Error> {
65
    tree(State(app), viewer, Path((owner, name, r, String::new()))).await
66
}
67
68
pub async fn tree(
69
    State(app): State<Shared>,
70
    viewer: Viewer,
71
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
72
) -> Result<Page<TreePage>, Error> {
73
    let shell = Shell::new(&app, &format!("/{owner}/{name}/tree/{r}/{path}"), &viewer);
74
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
75
    let (spec, dir) = (r.clone(), path.clone());
76
    let t = app
77
        .repos
78
        .read(&repo, move |repo, cache| {
79
            let target = view::resolve(repo, cache, &spec)?;
80
            view::tree(repo, cache, target, &dir)
81
        })
82
        .await
83
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
84
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
85
    let readme_html = t.readme.as_ref().map(|md| {
86
        let dir = md.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
87
        render::markdown::render(&md.text, &format!("{}/file/{r}/{dir}", rs.url), &format!("{}/file/{r}/{dir}", rs.url))
88
    });
89
    Ok(Page(TreePage { shell, repo: rs, t, readme_html }))
90
}
91
92
#[derive(Deserialize)]
93
pub struct FileQuery {
94
    plain: Option<String>,
95
    blame: Option<String>,
96
    /// `source` shows a Markdown file's text instead of rendering it.
97
    view: Option<String>,
98
}
99
100
#[derive(Template)]
101
#[template(path = "file.html")]
102
pub struct FilePage {
103
    shell: Shell,
104
    repo: RepoShell,
105
    f: view::FileView,
106
    /// Highlighted lines when text.
107
    lines: Vec<String>,
108
    language: Option<&'static str>,
109
    markdown_html: Option<String>,
110
    is_image: bool,
111
    is_markdown: bool,
112
    blame: Option<Vec<BlameRow>>,
113
}
114
115
/// A blame gutter entry: shown only on the first line of a run.
116
pub struct BlameRow {
117
    pub first: bool,
118
    pub hash: String,
119
    pub short: String,
120
    pub author: String,
121
    pub when_ms: u64,
122
    pub run: usize,
123
}
124
125
pub async fn file(
126
    State(app): State<Shared>,
127
    viewer: Viewer,
128
    Path((owner, name, r, path)): Path<(String, String, String, String)>,
129
    Query(q): Query<FileQuery>,
130
) -> Result<Response, Error> {
131
    let shell = Shell::new(&app, &format!("/{owner}/{name}/file/{r}/{path}"), &viewer);
132
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
133
    let limit = app.config.limits.render_limit.0;
134
    let want_blame = q.blame.is_some();
135
    let (spec, p) = (r.clone(), path.clone());
136
    let (f, blame) = app
137
        .repos
138
        .read(&repo, move |repo, cache| {
139
            let target = view::resolve(repo, cache, &spec)?;
140
            if want_blame {
141
                let b = view::blame(repo, cache, target, &p, limit)?;
142
                Ok((b.file, Some(b.lines)))
143
            } else {
144
                Ok((view::file(repo, cache, target, &p, limit)?, None))
145
            }
146
        })
147
        .await
148
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
149
    if q.plain.is_some() {
150
        return Ok(super::raw(f.bytes, &f.name, true));
151
    }
152
    let rs = RepoShell::new(&app, &row, "code").with_role(role);
153
    let is_image = super::mime_of(&f.name).starts_with("image/");
154
    let is_markdown = f.name.to_lowercase().ends_with(".md") || f.name.to_lowercase() == "readme";
155
    let want_source = q.view.as_deref() == Some("source") || blame.is_some();
156
    let (lines, language, markdown_html) = match &f.body {
157
        FileBody::Text(text) if !is_image => {
158
            if is_markdown && !want_source {
159
                let dir = f.path.rsplit_once('/').map(|(d, _)| format!("{d}/")).unwrap_or_default();
160
                let base = format!("{}/file/{r}/{dir}", rs.url);
161
                (vec![], highlight::language(&f.path), Some(render::markdown::render(text, &base, &base)))
162
            } else {
163
                (highlight::lines(&f.path, text), highlight::language(&f.path), None)
164
            }
165
        }
166
        _ => (vec![], None, None),
167
    };
168
    let blame = blame.map(|lines| {
169
        let mut rows: Vec<BlameRow> = Vec::with_capacity(lines.len());
170
        let mut i = 0;
171
        while i < lines.len() {
172
            let mut run = 1;
173
            while i + run < lines.len() && lines[i + run].hash == lines[i].hash {
174
                run += 1;
175
            }
176
            for k in 0..run {
177
                let l = &lines[i + k];
178
                rows.push(BlameRow {
179
                    first: k == 0,
180
                    hash: l.hash.to_hex(),
181
                    short: l.hash.short(8),
182
                    author: l.author.clone(),
183
                    when_ms: l.when_ms,
184
                    run,
185
                });
186
            }
187
            i += run;
188
        }
189
        rows
190
    });
191
    Ok(Page(FilePage { shell, repo: rs, f, lines, language, markdown_html, is_image, is_markdown, blame }).into_response())
192
}
193
194
#[derive(Deserialize)]
195
pub struct LastQuery {
196
    /// Comma-separated paths.
197
    paths: String,
198
}
199
200
/// `GET /{owner}/{name}/last/{ref}?paths=a,b` → JSON of last change per
201
/// path, fetched by the tree page after it paints (hub spec §6.5).
202
pub async fn last_changes(
203
    State(app): State<Shared>,
204
    viewer: Viewer,
205
    Path((owner, name, r)): Path<(String, String, String)>,
206
    Query(q): Query<LastQuery>,
207
) -> Result<Response, Error> {
208
    let shell = Shell::new(&app, "", &viewer);
209
    let (repo, _, _role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
210
    let paths: Vec<String> = q.paths.split(',').filter(|p| !p.is_empty()).take(500).map(String::from).collect();
211
    let spec = r.clone();
212
    let found = app
213
        .repos
214
        .read(&repo, move |repo, cache| {
215
            let target = view::resolve(repo, cache, &spec)?;
216
            view::last_changes(repo, cache, &target.heads, &paths)
217
        })
218
        .await
219
        .map_err(|e| Error::from_repo(shell.clone(), e))?;
220
    let now = crate::db::now_ms() as u64;
221
    let body: Vec<serde_json::Value> = found
222
        .into_iter()
223
        .map(|(p, c)| {
224
            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) })
225
        })
226
        .collect();
227
    Ok(axum::Json(body).into_response())
228
}
229
230
impl EntryKind {
231
    pub fn glyph(&self) -> &'static str {
232
        match self {
233
            EntryKind::Dir => "▸",
234
            EntryKind::File => "·",
235
            EntryKind::Symlink => "↪",
236
            EntryKind::Subrepo => "◫",
237
        }
238
    }
239
}