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