gitscope
← rgit / 0.1.2 / src/methods/repo/tree.rs
https://dev.kronoz.win/r/rgit.git
src/methods/repo/tree.rs · Rust
Blame Raw
 1use std::{
 2    fmt::{Display, Formatter},
 3    sync::Arc,
 4};
 5
 6use askama::Template;
 7use axum::{extract::Query, http, response::IntoResponse, response::Response, Extension};
 8use serde::Deserialize;
 9
10use crate::{
11    git::{FileWithContent, PathDestination, TreeItem},
12    into_response,
13    methods::{
14        filters,
15        repo::{ChildPath, Repository, RepositoryPath, Result},
16    },
17    Git,
18};
19
20#[derive(Deserialize)]
21pub struct UriQuery {
22    id: Option<String>,
23    #[serde(rename = "h")]
24    branch: Option<String>,
25    #[serde(default)]
26    raw: bool,
27}
28
29impl Display for UriQuery {
30    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
31        let mut prefix = "?";
32
33        if let Some(id) = self.id.as_deref() {
34            write!(f, "{prefix}id={id}")?;
35            prefix = "&";
36        }
37
38        if let Some(branch) = self.branch.as_deref() {
39            write!(f, "{prefix}h={branch}")?;
40        }
41
42        Ok(())
43    }
44}
45
46#[derive(Template)]
47#[template(path = "repo/tree.html")]
48#[allow(clippy::module_name_repetitions)]
49pub struct TreeView {
50    pub repo: Repository,
51    pub items: Vec<TreeItem>,
52    pub query: UriQuery,
53}
54
55#[derive(Template)]
56#[template(path = "repo/file.html")]
57pub struct FileView {
58    pub repo: Repository,
59    pub file: FileWithContent,
60}
61
62pub async fn handle(
63    Extension(repo): Extension<Repository>,
64    Extension(RepositoryPath(repository_path)): Extension<RepositoryPath>,
65    Extension(ChildPath(child_path)): Extension<ChildPath>,
66    Extension(git): Extension<Arc<Git>>,
67    Query(query): Query<UriQuery>,
68) -> Result<Response> {
69    let open_repo = git.repo(repository_path).await?;
70
71    Ok(
72        match open_repo
73            .path(
74                child_path,
75                query.id.as_deref(),
76                query.branch.clone(),
77                !query.raw,
78            )
79            .await?
80        {
81            PathDestination::Tree(items) => into_response(&TreeView { repo, items, query }),
82            PathDestination::File(file) if query.raw => {
83                let headers = [(
84                    http::header::CONTENT_TYPE,
85                    http::HeaderValue::from_static("text/plain"),
86                )];
87
88                (headers, file.content).into_response()
89            }
90            PathDestination::File(file) => into_response(&FileView { repo, file }),
91        },
92    )
93}