Parent [>]
1mod archive;
2mod branch;
3mod commit;
4mod raw;
5mod repo;
6mod tag;
7mod tree;
8
9use std::collections::HashMap;
10use std::path::{Component, PathBuf};
11
12use axum::Router;
13use axum::extract::{FromRequestParts, Path, State};
14use axum::http::header;
15use axum::http::request::Parts;
16use axum::response::IntoResponse;
17use axum::routing::get;
18use jiff::Timestamp;
19use jiff::tz::{Offset, TimeZone};
20
21use crate::error::{Error, Result};
22
23/// Formats a commit's author date as a `YYYY-MM-DD` string in the commit's
24/// local timezone, returning `None` if the time cannot be parsed.
25pub(super) fn commit_date(commit: &gix::Commit) -> Option<String> {
26    let time = commit.time().ok()?;
27    let zone = TimeZone::fixed(Offset::from_seconds(time.offset).ok()?);
28
29    Timestamp::from_second(time.seconds)
30        .map(|ts| ts.to_zoned(zone).date().to_string())
31        .ok()
32}
33
34/// Axum extractor that pulls the `{repo}` path parameter and validates it
35/// contains no path traversal components before passing it to handlers.
36pub struct RepoName(pub String);
37
38impl<S: Send + Sync> FromRequestParts<S> for RepoName {
39    type Rejection = Error;
40
41    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self> {
42        let Path(params) = Path::<HashMap<String, String>>::from_request_parts(parts, state)
43            .await
44            .map_err(|e| Error::BadRequest(e.to_string()))?;
45
46        let name = params
47            .get("repo")
48            .ok_or_else(|| Error::BadRequest("missing repo parameter".to_string()))?
49            .clone();
50
51        // Reject names containing non-normal components (e.g. `..`) to prevent
52        // directory traversal.
53        if std::path::Path::new(&name)
54            .components()
55            .any(|c| !matches!(c, Component::Normal(_)))
56        {
57            return Err(Error::BadRequest("invalid repository name".to_string()));
58        }
59
60        Ok(RepoName(name))
61    }
62}
63
64/// Shared application state passed to all route handlers.
65#[derive(Clone)]
66pub struct AppState {
67    /// Path to the directory containing bare git repositories.
68    pub root: PathBuf,
69    /// Concatenated CSS served at `/style.css`.
70    pub css: String,
71}
72
73/// Serves the concatenated stylesheet.
74async fn style(State(state): State<AppState>) -> impl IntoResponse {
75    (
76        [(header::CONTENT_TYPE, "text/css; charset=utf-8")],
77        state.css,
78    )
79}
80
81/// Builds the application router with all routes and shared state attached.
82pub fn router(state: AppState) -> Router {
83    Router::new()
84        .route("/style.css", get(style))
85        .route("/", get(repo::list))
86        .route("/{repo}", get(repo::detail))
87        .route("/{repo}/tags", get(tag::list))
88        .route("/{repo}/tags/{*tag}", get(tag::detail))
89        .route("/{repo}/branches", get(branch::list))
90        .route("/{repo}/branches/{*branch}", get(branch::detail))
91        .route("/{repo}/commits", get(commit::list))
92        .route("/{repo}/commits/{sha}", get(commit::detail))
93        .route("/{repo}/commits/{sha}/tree", get(tree::handler))
94        .route("/{repo}/commits/{sha}/tree/{*path}", get(tree::handler))
95        .route("/{repo}/commits/{sha}/raw/{*path}", get(raw::handler))
96        .route("/{repo}/archive/{format}/{*ref}", get(archive::handler))
97        .with_state(state)
98}