index : gitrs
A lightweight web interface for browsing Git repositories, implemented in Rust
about summary refs log tree commit diff
author Yousef Al-Harbi <yo2w86@gmail.com> 2026-11-17 17:01:35 +0300
committer Yousef Al-Harbi <yo2w86@gmail.com> 2026-11-17 17:10:08 +0300
commit a3b50488e6962caa07ea3904c86d412de36ac901 [patch]
tree 7f02840ba93c582d3766feb39425b5a5684e02d6
parent 2e3401e55a47aeea1f4b1a4731f966538f9ee295
download a3b50488e6962caa07ea3904c86d412de36ac901.tar.gz

feat: Syntax highlighting and improvements

Diffstat

-rw-r--r-- src/main.rs 2
-rw-r--r-- src/markdown.rs 38
-rw-r--r-- src/syntax_highlight.rs 1125
-rw-r--r-- static/style.css 102
-rw-r--r-- templates/about.html 28
-rw-r--r-- templates/macros.html 8
-rw-r--r-- src/git/branch.rs 38
-rw-r--r-- src/git/commit.rs 40
-rw-r--r-- src/git/diff.rs 273
-rw-r--r-- src/git/repository.rs 116
-rw-r--r-- src/git/tag.rs 49
-rw-r--r-- src/git/tree.rs 158
-rw-r--r-- src/routes/git.rs 63
-rw-r--r-- src/routes/static.rs 1
-rw-r--r-- templates/repository/tree.html 2
 15 files changed, 1329 insertions(+), 714 deletions(-)

diff --git a/src/main.rs b/src/main.rs
index b7c227d..d6754e0 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -12,6 +12,7 @@
pub mod markdown;
pub mod prelude;
pub mod routes;
pub mod syntax_highlight;
pub mod time;

#[actix_web::main]
@@ -25,7 +26,6 @@
            .service(routes::r#static::files)
            .service(routes::git::git_info_refs)
            .service(routes::git::git_upload_pack)
            .service(routes::git::git_receive_pack)
            .service(routes::repository::diff::patch)
            .service(routes::repository::snapshot::download)
            .service(routes::page)
diff --git a/src/markdown.rs b/src/markdown.rs
index e0cdb3c..b0baca6 100644
--- a/src/markdown.rs
+++ b/src/markdown.rs
@@ -1,14 +1,50 @@
use std::collections::HashMap;

use pulldown_cmark::{CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html};
use pulldown_cmark::{CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag, TagEnd, html};

use crate::syntax_highlight;

pub fn render(raw: &str) -> String {
    let events: Vec<Event> = Parser::new_ext(raw, Options::all()).collect();
    let events = link_headings(events);
    let events = highlight_code_blocks(events);

    let mut out = String::new();
    html::push_html(&mut out, events.into_iter());
    out
}

fn highlight_code_blocks(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
    let mut output = Vec::with_capacity(events.len());
    let mut code_lang: Option<String> = None;
    let mut code_buf = String::new();

    for event in events {
        match event {
            Event::Start(Tag::CodeBlock(kind)) => {
                let lang = match kind {
                    CodeBlockKind::Fenced(lang) => {
                        lang.split_whitespace().next().unwrap_or("").to_string()
                    }
                    CodeBlockKind::Indented => String::new(),
                };
                code_lang = Some(lang);
                code_buf.clear();
            }
            Event::Text(text) if code_lang.is_some() => {
                code_buf.push_str(&text);
            }
            Event::End(TagEnd::CodeBlock) => {
                if let Some(lang) = code_lang.take() {
                    let highlighted = syntax_highlight::highlight_block(&code_buf, &lang);
                    output.push(Event::Html(CowStr::from(highlighted)));
                }
            }
            other => output.push(other),
        }
    }

    output
}

fn link_headings(events: Vec<Event<'_>>) -> Vec<Event<'_>> {
diff --git a/src/syntax_highlight.rs b/src/syntax_highlight.rs
index 1a9d99f..bace1ed 100644
--- a/src/syntax_highlight.rs
+++ b/src/syntax_highlight.rs
@@ -1,284 +1,913 @@
use std::{
    cell::RefCell,
    collections::HashMap,
    fmt::Write as FmtWrite,
    io::{ErrorKind, Write as IoWrite},
    path::Path,
    sync::LazyLock,
};

use comrak::adapters::SyntaxHighlighterAdapter;
use tree_sitter_grammar_repository::{Grammar, Language};
use tree_sitter_highlight::{HighlightConfiguration, HighlightEvent, Highlighter};

thread_local! {
    static HIGHLIGHTER: RefCell<Highlighter> = RefCell::new(Highlighter::new());
}

macro_rules! count {
    () => (0);
    ($e:expr) => (1);
    ($e:expr, $($rest:expr),*) => (1 + count!($($rest),*));
}

macro_rules! define_classes {
    ($($name:literal => $class:literal),*,) => {
        static HIGHLIGHT_NAMES: [&str; count!($($name),*)] = [
            $($name),*
        ];

        static HIGHLIGHT_CLASSES: [&str; count!($($name),*)] = [
            $($class),*
        ];
    };
}

define_classes! {
"attribute" => "attribute",
"boolean" => "boolean",
"carriage-return" => "carriage-return",
"comment" => "comment",
"comment.documentation" => "comment documentation",
"constant" => "constant",
"constant.builtin" => "constant builtin",
"constructor" => "constructor",
"constructor.builtin" => "constructor builtin",
"embedded" => "embedded",
"error" => "error",
"escape" => "escape",
"function" => "function",
"function.builtin" => "function builtin",
"keyword" => "keyword",
"markup" => "markup",
"markup.bold" => "markup bold",
"markup.heading" => "markup heading",
"markup.italic" => "markup italic",
"markup.link" => "markup link",
"markup.link.url" => "markup link url",
"markup.list" => "markup list",
"markup.list.checked" => "markup list checked",
"markup.list.numbered" => "markup list numbered",
"markup.list.unchecked" => "markup list unchecked",
"markup.list.unnumbered" => "markup list unnumbered",
"markup.quote" => "markup quote",
"markup.raw" => "markup raw",
"markup.raw.block" => "markup raw block",
"markup.raw.inline" => "markup raw inline",
"markup.strikethrough" => "markup strikethrough",
"module" => "module",
"number" => "number",
"operator" => "operator",
"property" => "property",
"property.builtin" => "property builtin",
"punctuation" => "punctuation",
"punctuation.bracket" => "punctuation bracket",
"punctuation.delimiter" => "punctuation delimiter",
"punctuation.special" => "punctuation special",
"string" => "string",
"string.escape" => "string escape",
"string.regexp" => "string regexp",
"string.special" => "string special",
"string.special.symbol" => "string special symbol",
"tag" => "tag",
"type" => "type",
"type.builtin" => "type builtin",
"variable" => "variable",
"variable.builtin" => "variable builtin",
"variable.member" => "variable member",
"variable.parameter" => "variable parameter",}

pub fn prime_highlighters() {
    let _res = HIGHLIGHTER_CONFIGS.len();
}

static HIGHLIGHTER_CONFIGS: LazyLock<Vec<HighlightConfiguration>> = LazyLock::new(|| {
    Grammar::VARIANTS
        .iter()
        .copied()
        .map(Grammar::highlight_configuration_params)
        .map(|v| {
            let mut configuration = HighlightConfiguration::new(
                v.language.into(),
                v.name,
                v.highlights_query,
                v.injection_query,
                v.locals_query,
            )
            .unwrap_or_else(|e| panic!("bad query for {}: {e}", v.name));
            configuration.configure(&HIGHLIGHT_NAMES);
            configuration
        })
        .collect()
});
use std::path::Path;

const IMPORTS: &[&str] = &[
    "use", "mod", "extern", "import", "from", "export", "package", "require", "include",
];

const KEYWORDS: &[&str] = &[
    "fn",
    "let",
    "mut",
    "pub",
    "priv",
    "struct",
    "enum",
    "impl",
    "trait",
    "type",
    "where",
    "for",
    "in",
    "while",
    "loop",
    "if",
    "else",
    "match",
    "return",
    "break",
    "continue",
    "async",
    "await",
    "move",
    "ref",
    "static",
    "const",
    "unsafe",
    "dyn",
    "as",
    "local",
    "function",
    "then",
    "elseif",
    "end",
    "do",
    "repeat",
    "until",
    "and",
    "or",
    "not",
    "def",
    "class",
    "try",
    "except",
    "finally",
    "with",
    "yield",
    "lambda",
    "pass",
    "raise",
    "switch",
    "case",
    "default",
    "var",
    "interface",
    "go",
    "defer",
    "select",
    "chan",
    "fallthrough",
    "elif",
    "fi",
    "done",
    "esac",
];

const BOOLEANS: &[&str] = &["true", "false", "nil", "null", "undefined"];

const BUILTIN_TYPES: &[&str] = &[
    "u8", "u16", "u32", "u64", "u128", "usize", "i8", "i16", "i32", "i64", "i128", "isize", "f32",
    "f64", "bool", "str", "char", "int", "float", "double", "void", "auto", "string", "number",
    "boolean", "any",
];

const BUILTIN_CONSTS: &[&str] = &["Some", "None", "Ok", "Err"];

const BUILTIN_FUNCS: &[&str] = &[
    "drop", "print", "ipairs", "pairs", "pcall", "xpcall", "tonumber", "tostring", "assert",
    "error", "len", "range", "echo", "set",
];

const BUILTIN_VARS: &[&str] = &["self", "Self", "super", "crate", "this"];

#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
    Code {
        hash_comments: bool,
        dash_comments: bool,
        rust_like: bool,
    },
    Config,
    Style,
    Markup,
    Plain,
}

pub fn fetch_highlighter_config(file: &Path) -> Option<&'static HighlightConfiguration> {
    Language::from_file_name(file)
        .map(Language::grammar)
        .map(Grammar::idx)
        .map(|idx| &HIGHLIGHTER_CONFIGS[idx])
#[derive(Clone, Copy, PartialEq, Eq)]
enum State {
    Normal,
    BlockComment,
    LuaBlockComment,
    DoubleString,
    RawString(usize),
}

pub fn highlight_lines(source: &str, path_or_lang: &str) -> Vec<String> {
    let mode = detect_mode(path_or_lang, source);
    let mut state = State::Normal;

pub fn fetch_highlighter_config_by_token(token: &str) -> Option<&'static HighlightConfiguration> {
    Language::from_injection(token)
        .map(Language::grammar)
        .map(Grammar::idx)
        .map(|idx| &HIGHLIGHTER_CONFIGS[idx])
    source
        .lines()
        .map(|line| highlight_line(line, mode, &mut state))
        .collect()
}

pub struct ComrakHighlightAdapter;
pub fn highlight_block(source: &str, lang: &str) -> String {
    let lines = highlight_lines(source, lang);
    format!("<pre><code>{}</code></pre>", lines.join("\n"))
}

impl SyntaxHighlighterAdapter for ComrakHighlightAdapter {
    fn write_highlighted(
        &self,
        output: &mut dyn IoWrite,
        lang: Option<&str>,
        code: &str,
    ) -> std::io::Result<()> {
        let out = format_file(code, FileIdentifier::Token(lang.unwrap_or_default()))
            .map_err(|e| std::io::Error::new(ErrorKind::Other, e))?;
        output.write_all(out.as_bytes())
fn detect_mode(path_or_lang: &str, source: &str) -> Mode {
    let lower = path_or_lang.trim().to_ascii_lowercase();
    let file_name = Path::new(&lower)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(&lower);
    let ext = Path::new(file_name)
        .extension()
        .and_then(|s| s.to_str())
        .unwrap_or(file_name);

    if matches!(
        file_name,
        "justfile"
            | "makefile"
            | "gnumakefile"
            | "dockerfile"
            | "containerfile"
            | "pkgbuild"
            | ".bashrc"
            | ".zshrc"
            | ".profile"
    ) {
        return Mode::Code {
            hash_comments: true,
            dash_comments: false,
            rust_like: false,
        };
    }

    fn write_pre_tag(
        &self,
        output: &mut dyn IoWrite,
        _attributes: HashMap<String, String>,
    ) -> std::io::Result<()> {
        write!(output, "<pre>")
    if matches!(
        file_name,
        ".gitignore" | ".gitmodules" | ".gitattributes" | ".editorconfig" | "cargo.lock"
    ) {
        return Mode::Config;
    }

    fn write_code_tag(
        &self,
        _output: &mut dyn IoWrite,
        _attributes: HashMap<String, String>,
    ) -> std::io::Result<()> {
        Ok(())
    match ext {
        "rs" | "rust" | "ron" => Mode::Code {
            hash_comments: false,
            dash_comments: false,
            rust_like: true,
        },
        "lua" | "sql" => Mode::Code {
            hash_comments: false,
            dash_comments: true,
            rust_like: false,
        },
        "sh" | "bash" | "zsh" | "fish" | "py" | "python" | "rb" | "ruby" | "nix" | "pl" | "r"
        | "just" | "mk" | "cmake" => Mode::Code {
            hash_comments: true,
            dash_comments: false,
            rust_like: false,
        },
        "c" | "h" | "cpp" | "hpp" | "cc" | "cxx" | "go" | "golang" | "js" | "jsx" | "ts"
        | "tsx" | "javascript" | "typescript" | "java" | "cs" | "csharp" | "zig" | "kt"
        | "kotlin" | "swift" | "dart" | "php" | "glsl" | "wgsl" | "hlsl" => Mode::Code {
            hash_comments: false,
            dash_comments: false,
            rust_like: false,
        },
        "toml" | "ini" | "cfg" | "conf" | "yaml" | "yml" | "json" | "jsonc" | "kdl" | "service"
        | "timer" | "socket" | "target" | "mount" | "desktop" | "env" => Mode::Config,
        "css" | "scss" | "sass" | "less" => Mode::Style,
        "html" | "htm" | "xml" | "svg" | "xhtml" => Mode::Markup,
        _ if source.starts_with("#!") => Mode::Code {
            hash_comments: true,
            dash_comments: false,
            rust_like: false,
        },
        _ => Mode::Plain,
    }
}

#[derive(Copy, Clone, Debug)]
pub enum FileIdentifier<'a> {
    Path(&'a Path),
    Token(&'a str),
fn highlight_line(line: &str, mode: Mode, state: &mut State) -> String {
    match mode {
        Mode::Plain => escape_html(line),
        Mode::Config => highlight_config_line(line),
        Mode::Style => highlight_style_line(line, state),
        Mode::Markup => highlight_markup_line(line, state),
        Mode::Code {
            hash_comments,
            dash_comments,
            rust_like,
        } => highlight_code_line(line, hash_comments, dash_comments, rust_like, state),
    }
}

fn render_line_prefix(tag: bool, line_number: usize) -> String {
    if !tag {
        return "".to_string();
fn highlight_code_line(
    line: &str,
    hash_comments: bool,
    dash_comments: bool,
    rust_like: bool,
    state: &mut State,
) -> String {
    let bytes = line.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut out = String::with_capacity(len * 2);
    let mut prev_keyword = "";
    let mut prev_was_dot = false;
    let mut in_fn_params = false;
    let mut paren_depth: usize = 0;

    while i < len {
        match *state {
            State::BlockComment => {
                if let Some(pos) = line[i..].find("*/") {
                    let end = i + pos + 2;
                    push_span(&mut out, "hl-comment", &line[i..end]);
                    i = end;
                    *state = State::Normal;
                } else {
                    push_span(&mut out, "hl-comment", &line[i..]);
                    return out;
                }
                continue;
            }
            State::LuaBlockComment => {
                if let Some(pos) = line[i..].find("]]") {
                    let end = i + pos + 2;
                    push_span(&mut out, "hl-comment", &line[i..end]);
                    i = end;
                    *state = State::Normal;
                } else {
                    push_span(&mut out, "hl-comment", &line[i..]);
                    return out;
                }
                continue;
            }
            State::DoubleString => {
                i = scan_double_string(line, i, &mut out, state);
                continue;
            }
            State::RawString(hashes) => {
                i = scan_raw_string(line, i, hashes, &mut out, state);
                continue;
            }
            State::Normal => {}
        }

        let b = bytes[i];

        if b.is_ascii_whitespace() {
            let start = i;
            while i < len && bytes[i].is_ascii_whitespace() {
                i += 1;
            }
            out.push_str(&line[start..i]);
            continue;
        }

        // `//` and `/*` comments
        if b == b'/' && i + 1 < len {
            if bytes[i + 1] == b'/' {
                push_span(&mut out, "hl-comment", &line[i..]);
                break;
            }
            if bytes[i + 1] == b'*' {
                *state = State::BlockComment;
                continue;
            }
        }

        // Lua `--` and `--[[` comments
        if dash_comments && b == b'-' && i + 1 < len && bytes[i + 1] == b'-' {
            if line[i + 2..].starts_with("[[") {
                *state = State::LuaBlockComment;
                continue;
            }
            push_span(&mut out, "hl-comment", &line[i..]);
            break;
        }

        // `#` attributes, comments, or preprocessor directives
        if b == b'#' {
            if rust_like
                && i + 1 < len
                && (bytes[i + 1] == b'[' || bytes[i + 1] == b'!')
                && let Some(close) = line[i..].find(']')
            {
                let end = i + close + 1;
                push_span(&mut out, "hl-attribute", &line[i..end]);
                i = end;
                continue;
            }
            if hash_comments || (i == 0 && line.starts_with("#!")) {
                push_span(&mut out, "hl-comment", &line[i..]);
                break;
            }
            if !rust_like {
                let start = i;
                i += 1;
                while i < len && bytes[i].is_ascii_whitespace() {
                    i += 1;
                }
                while i < len && bytes[i].is_ascii_alphabetic() {
                    i += 1;
                }
                push_span(&mut out, "hl-macro", &line[start..i]);
                continue;
            }
        }

        // Rust raw strings `r"..."`, `r#"..."#`
        if rust_like && b == b'r' && i + 1 < len && (bytes[i + 1] == b'"' || bytes[i + 1] == b'#') {
            let mut hashes = 0;
            let mut j = i + 1;
            while j < len && bytes[j] == b'#' {
                hashes += 1;
                j += 1;
            }
            if j < len && bytes[j] == b'"' {
                push_span(&mut out, "hl-string", &line[i..=j]);
                *state = State::RawString(hashes);
                i = j + 1;
                continue;
            }
        }

        if b == b'"' {
            push_span(&mut out, "hl-string", "\"");
            *state = State::DoubleString;
            i = scan_double_string(line, i + 1, &mut out, state);
            prev_was_dot = false;
            continue;
        }

        if b == b'\'' {
            if rust_like {
                if let Some((end, is_lifetime)) = scan_rust_quote(line, i) {
                    let class = if is_lifetime { "hl-label" } else { "hl-escape" };
                    push_span(&mut out, class, &line[i..end]);
                    i = end;
                    prev_was_dot = false;
                    continue;
                }
            } else {
                let end = scan_single_string(line, i);
                push_span(&mut out, "hl-string", &line[i..end]);
                i = end;
                prev_was_dot = false;
                continue;
            }
        }

        if b.is_ascii_digit() {
            let start = i;
            i += 1;
            while i < len
                && (bytes[i].is_ascii_alphanumeric()
                    || bytes[i] == b'_'
                    || (bytes[i] == b'.' && i + 1 < len && bytes[i + 1].is_ascii_digit()))
            {
                i += 1;
            }
            push_span(&mut out, "hl-number", &line[start..i]);
            prev_was_dot = false;
            continue;
        }

        if is_ident_start(b) {
            let start = i;
            i += 1;
            while i < len && is_ident_continue(bytes[i]) {
                i += 1;
            }
            let ident = &line[start..i];
            let rest = &line[i..];

            if rest.starts_with('!') && !rest.starts_with("!=") {
                i += 1;
                push_span(&mut out, "hl-macro", &line[start..i]);
                prev_was_dot = false;
                continue;
            }

            let class = classify_ident(
                ident,
                rest.trim_start(),
                prev_keyword,
                prev_was_dot,
                in_fn_params && paren_depth == 1,
            );
            push_span(&mut out, class, ident);

            if matches!(ident, "fn" | "function" | "def") {
                in_fn_params = true;
            }
            prev_keyword = if matches!(class, "hl-keyword" | "hl-include") {
                ident
            } else {
                ""
            };
            prev_was_dot = false;
            continue;
        }

        if matches!(b, b'(' | b')' | b'[' | b']' | b'{' | b'}' | b',' | b';') {
            match b {
                b'(' => paren_depth += 1,
                b')' => {
                    paren_depth = paren_depth.saturating_sub(1);
                    if paren_depth == 0 {
                        in_fn_params = false;
                    }
                }
                b'{' | b';' => in_fn_params = false,
                _ => {}
            }
            push_span(&mut out, "hl-punctuation", &line[i..=i]);
            prev_was_dot = false;
            i += 1;
            continue;
        }

        if b == b':' {
            let len_colon = if i + 1 < len && bytes[i + 1] == b':' {
                2
            } else {
                1
            };
            push_span(&mut out, "hl-punctuation", &line[i..i + len_colon]);
            prev_was_dot = false;
            i += len_colon;
            continue;
        }

        if b == b'.' {
            if i + 1 < len && bytes[i + 1] == b'.' {
                let end = if i + 2 < len && bytes[i + 2] == b'=' {
                    i + 3
                } else {
                    i + 2
                };
                push_span(&mut out, "hl-operator", &line[i..end]);
                prev_was_dot = false;
                i = end;
            } else {
                push_span(&mut out, "hl-punctuation", ".");
                prev_was_dot = true;
                i += 1;
            }
            continue;
        }

        if is_operator_byte(b) {
            let start = i;
            i += 1;
            while i < len && is_operator_byte(bytes[i]) {
                i += 1;
            }
            push_span(&mut out, "hl-operator", &line[start..i]);
            prev_was_dot = false;
            continue;
        }

        let ch = line[i..].chars().next().unwrap();
        let end = i + ch.len_utf8();
        escape_into(&mut out, &line[i..end]);
        prev_was_dot = false;
        i = end;
    }
    format!("<span class='lnb'><a id='n{0}' href='#n{0}'>{0}</a></span><code>", line_number)

    out
}

fn classify_ident(
    ident: &str,
    trimmed_rest: &str,
    prev_keyword: &str,
    prev_was_dot: bool,
    in_fn_params: bool,
) -> &'static str {
    if !prev_was_dot {
        if IMPORTS.contains(&ident) {
            return "hl-include";
        }
        if KEYWORDS.contains(&ident) {
            return "hl-keyword";
        }
        if BOOLEANS.contains(&ident) {
            return "hl-boolean";
        }
        if BUILTIN_TYPES.contains(&ident) {
            return "hl-type-builtin";
        }
        if BUILTIN_CONSTS.contains(&ident) {
            return "hl-constant";
        }
        if BUILTIN_FUNCS.contains(&ident) {
            return "hl-function-builtin";
        }
        if BUILTIN_VARS.contains(&ident) {
            return "hl-variable";
        }
    }

    if matches!(prev_keyword, "fn" | "function" | "def") {
        return "hl-function";
    }
    if matches!(
        prev_keyword,
        "struct" | "enum" | "trait" | "type" | "class" | "interface"
    ) {
        return "hl-type";
    }
    if prev_keyword == "mod" {
        return "hl-module";
    }

    if ident.as_bytes()[0].is_ascii_uppercase() {
        let is_const = ident.len() > 1
            && ident
                .bytes()
                .all(|b| b.is_ascii_uppercase() || b.is_ascii_digit() || b == b'_');
        return if is_const { "hl-constant" } else { "hl-type" };
    }

fn render_line_suffix(tag: bool, line_number: usize) -> String {
    if !tag {
        return "\n".to_string();
    if trimmed_rest.starts_with("::") && !trimmed_rest.starts_with("::<") {
        return "hl-module";
    }
    "</code>\n".to_string()
    if trimmed_rest.starts_with('(') || trimmed_rest.starts_with("::<") {
        return "hl-function";
    }
    if prev_was_dot {
        return "hl-property";
    }
    if trimmed_rest.starts_with(':') && !trimmed_rest.starts_with("::") {
        return if in_fn_params {
            "hl-parameter"
        } else {
            "hl-property"
        };
    }

    "hl-variable"
}

fn highlight_config_line(line: &str) -> String {
    let trimmed = line.trim_start();
    if trimmed.starts_with('#') || trimmed.starts_with("//") || trimmed.starts_with(';') {
        let mut out = String::new();
        push_span(&mut out, "hl-comment", line);
        return out;
    }

    if trimmed.starts_with('[') && trimmed.ends_with(']') {
        let indent = &line[..line.len() - trimmed.len()];
        let mut out = String::from(indent);
        let open_len = if trimmed.starts_with("[[") { 2 } else { 1 };
        let close_len = if trimmed.ends_with("]]") { 2 } else { 1 };
        push_span(&mut out, "hl-punctuation", &trimmed[..open_len]);
        push_span(
            &mut out,
            "hl-property",
            &trimmed[open_len..trimmed.len() - close_len],
        );
        push_span(
            &mut out,
            "hl-punctuation",
            &trimmed[trimmed.len() - close_len..],
        );
        return out;
    }

    if let Some(sep_idx) = find_config_sep(line) {
        let key_part = &line[..sep_idx];
        let sep = &line[sep_idx..=sep_idx];
        let val_part = &line[sep_idx + 1..];

        let mut out = String::new();
        let key_trim = key_part.trim();
        if !key_trim.is_empty() {
            let lead = key_part.len() - key_part.trim_start().len();
            let trail = key_part.len() - key_part.trim_end().len();
            out.push_str(&key_part[..lead]);
            push_span(&mut out, "hl-property", key_trim);
            out.push_str(&key_part[key_part.len() - trail..]);
        } else {
            escape_into(&mut out, key_part);
        }

        let sep_class = if sep == "=" {
            "hl-operator"
        } else {
            "hl-punctuation"
        };
        push_span(&mut out, sep_class, sep);

        let mut state = State::Normal;
        out.push_str(&highlight_code_line(
            val_part, true, false, false, &mut state,
        ));
        return out;
    }

    let mut state = State::Normal;
    highlight_code_line(line, true, false, false, &mut state)
}

pub fn format_file(content: &str, identifier: FileIdentifier<'_>) -> Result<String. Error> {
    let mut out = String::new();
    format_file_inner(&mut out, content, identifier, true)?;
    Ok(out)
fn find_config_sep(line: &str) -> Option<usize> {
    let mut in_quotes = false;
    for (i, &b) in line.as_bytes().iter().enumerate() {
        if b == b'"' {
            in_quotes = !in_quotes;
        } else if !in_quotes && (b == b'=' || b == b':') {
            return Some(i);
        }
    }
    None
}

pub fn format_file_inner(
    out: &mut String,
    content: &str,
    identifier: FileIdentifier<'_>,
    code_tag: bool,
) -> anyhow::Result<()> {
    let config = match identifier {
        FileIdentifier::Path(v) => fetch_highlighter_config(v),
        FileIdentifier::Token(v) => fetch_highlighter_config_by_token(v),
    };

    let Some(config) = config else {
        for (i, line) in content.lines().enumerate() {
            out.push_str(&render_line_prefix(code_tag, i));
            v_htmlescape::b_escape(line.as_bytes(), out);
            out.push_str(&render_line_suffix(code_tag, i));
        }

        return Ok(());
    };

    let mut line_number = 0;
    HIGHLIGHTER.with_borrow_mut(|highlighter| {
        highlighter.parser().reset();

        let spans = highlighter.highlight(config, content.as_bytes(), None, |injection| {
            debug!(injection, "Highlighter switch requested");
            fetch_highlighter_config_by_token(injection)
        });

        let mut spans = match spans {
            Ok(v) => v,
            Err(error) => {
                error!(
                    ?error,
                    "Failed to run highlighter, falling back to plaintext"
                );

                for line in content.lines() {
                    line_number = line_number + 1;
                    out.push_str(&render_line_prefix(code_tag, line_number));
                    v_htmlescape::b_escape(line.as_bytes(), out);
                    out.push_str(&render_line_suffix(code_tag, line_number));
                }
fn highlight_style_line(line: &str, state: &mut State) -> String {
    let trimmed = line.trim_start();
    if *state == State::BlockComment || trimmed.starts_with("/*") {
        return highlight_code_line(line, false, false, false, state);
    }

    if let Some(colon) = line.find(':')
        && !trimmed.starts_with(['.', '#', '@'])
        && !line[..colon].contains('{')
    {
        let prop = &line[..colon];
        let rest = &line[colon + 1..];
        let mut out = String::new();
        let lead = prop.len() - prop.trim_start().len();
        out.push_str(&prop[..lead]);
        push_span(&mut out, "hl-property", prop.trim_start());
        push_span(&mut out, "hl-punctuation", ":");
        out.push_str(&highlight_code_line(rest, false, false, false, state));
        return out;
    }

    highlight_code_line(line, false, false, false, state)
}

                return Ok(());
fn highlight_markup_line(line: &str, state: &mut State) -> String {
    let bytes = line.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    let mut out = String::with_capacity(len * 2);

    while i < len {
        if *state == State::BlockComment {
            if let Some(pos) = line[i..].find("-->") {
                let end = i + pos + 3;
                push_span(&mut out, "hl-comment", &line[i..end]);
                i = end;
                *state = State::Normal;
            } else {
                push_span(&mut out, "hl-comment", &line[i..]);
                return out;
            }
        };
            continue;
        }

        let mut tag_open = true;
        line_number = line_number + 1;
        out.push_str(&render_line_prefix(code_tag, line_number));

        while let Some(span) = spans.next().transpose()? {
            if !tag_open {
                line_number = line_number + 1;
                out.push_str(&render_line_prefix(code_tag, line_number));
                tag_open = true;
            }

            match span {
                HighlightEvent::Source { start, end } => {
                    let content = &content[start..end];

                    for (i, line) in content.lines().enumerate() {
                        if i != 0 {
                            out.push_str(&render_line_suffix(code_tag, line_number));
                            line_number = line_number + 1;
                            out.push_str(&render_line_prefix(code_tag, line_number));
                        }
                        v_htmlescape::b_escape(line.as_bytes(), out);
                    }
        if line[i..].starts_with("<!--") {
            *state = State::BlockComment;
            continue;
        }

        if bytes[i] == b'<' {
            let start = i;
            i += 1;
            if i < len && matches!(bytes[i], b'/' | b'!' | b'?') {
                i += 1;
            }
            push_span(&mut out, "hl-tag-delimiter", &line[start..i]);

            let tag_start = i;
            while i < len && (bytes[i].is_ascii_alphanumeric() || matches!(bytes[i], b'-' | b':')) {
                i += 1;
            }
            if i > tag_start {
                push_span(&mut out, "hl-tag", &line[tag_start..i]);
            }

                    if content.ends_with('\n') {
                        out.push_str(&render_line_suffix(code_tag, line_number));
                        tag_open = false;
            while i < len && bytes[i] != b'>' {
                if bytes[i].is_ascii_whitespace() {
                    out.push(bytes[i] as char);
                    i += 1;
                } else if matches!(bytes[i], b'"' | b'\'') {
                    let quote = bytes[i];
                    let s_start = i;
                    i += 1;
                    while i < len && bytes[i] != quote {
                        i += 1;
                    }
                }
                HighlightEvent::HighlightStart(highlight) => {
                    write!(
                        out,
                        r#"<span class="highlight {}">"#,
                        HIGHLIGHT_CLASSES[highlight.0]
                    )?;
                }
                HighlightEvent::HighlightEnd => {
                    out.push_str("</span>");
                    if i < len {
                        i += 1;
                    }
                    push_span(&mut out, "hl-string", &line[s_start..i]);
                } else if bytes[i] == b'=' {
                    push_span(&mut out, "hl-operator", "=");
                    i += 1;
                } else if bytes[i] == b'/' && i + 1 < len && bytes[i + 1] == b'>' {
                    push_span(&mut out, "hl-tag-delimiter", "/>");
                    i += 2;
                    break;
                } else {
                    let attr_start = i;
                    while i < len
                        && !bytes[i].is_ascii_whitespace()
                        && !matches!(bytes[i], b'=' | b'>' | b'/' | b'"' | b'\'')
                    {
                        i += 1;
                    }
                    if i > attr_start {
                        push_span(&mut out, "hl-label", &line[attr_start..i]);
                    } else {
                        escape_into(&mut out, &line[i..=i]);
                        i += 1;
                    }
                }
            }

            if i < len && bytes[i] == b'>' {
                push_span(&mut out, "hl-tag-delimiter", ">");
                i += 1;
            }
            continue;
        }

        if tag_open {
            out.push_str(&render_line_suffix(code_tag, line_number));
        let next_lt = line[i..].find('<').map(|p| i + p).unwrap_or(len);
        escape_into(&mut out, &line[i..next_lt]);
        i = next_lt;
    }

    out
}

fn scan_double_string(line: &str, mut i: usize, out: &mut String, state: &mut State) -> usize {
    let bytes = line.as_bytes();
    let len = bytes.len();
    let mut seg_start = i;

    while i < len {
        if bytes[i] == b'\\' && i + 1 < len {
            if i > seg_start {
                push_span(out, "hl-string", &line[seg_start..i]);
            }
            let esc_end = (i + 2).min(len);
            push_span(out, "hl-escape", &line[i..esc_end]);
            i = esc_end;
            seg_start = i;
        } else if bytes[i] == b'"' {
            push_span(out, "hl-string", &line[seg_start..=i]);
            *state = State::Normal;
            return i + 1;
        } else {
            i += line[i..].chars().next().unwrap().len_utf8();
        }
    }

    if seg_start < len {
        push_span(out, "hl-string", &line[seg_start..len]);
    }
    len
}

fn scan_raw_string(
    line: &str,
    mut i: usize,
    hashes: usize,
    out: &mut String,
    state: &mut State,
) -> usize {
    let bytes = line.as_bytes();
    let len = bytes.len();
    let start = i;

    while i < len {
        if bytes[i] == b'"' {
            let mut h = 0;
            while i + 1 + h < len && bytes[i + 1 + h] == b'#' && h < hashes {
                h += 1;
            }
            if h == hashes {
                let end = i + 1 + hashes;
                push_span(out, "hl-string", &line[start..end]);
                *state = State::Normal;
                return end;
            }
        }
        i += 1;
    }

    if start < len {
        push_span(out, "hl-string", &line[start..len]);
    }
    len
}

fn scan_single_string(line: &str, start: usize) -> usize {
    let bytes = line.as_bytes();
    let len = bytes.len();
    let mut i = start + 1;
    while i < len {
        if bytes[i] == b'\\' && i + 1 < len {
            i += 2;
        } else if bytes[i] == b'\'' {
            return i + 1;
        } else {
            i += 1;
        }
    }
    len
}

fn scan_rust_quote(line: &str, start: usize) -> Option<(usize, bool)> {
    let rest = &line[start + 1..];
    if let Some(escaped) = rest.strip_prefix('\\')
        && let Some(close) = escaped.find('\'')
    {
        return Some((start + 2 + close + 1, false));
    }
    let mut chars = rest.char_indices();
    if let Some((_, first)) = chars.next() {
        if let Some((next_idx, '\'')) = chars.next() {
            return Some((start + 1 + next_idx + 1, false));
        }
        if first.is_ascii_alphabetic() || first == '_' {
            let mut end = first.len_utf8();
            for (idx, ch) in rest[end..].char_indices() {
                if ch.is_ascii_alphanumeric() || ch == '_' {
                    end = first.len_utf8() + idx + ch.len_utf8();
                } else {
                    break;
                }
            }
            return Some((start + 1 + end, true));
        }
    }
    None
}

        Ok::<_, anyhow::Error>(())
    })?;
fn is_ident_start(b: u8) -> bool {
    b.is_ascii_alphabetic() || b == b'_'
}

fn is_ident_continue(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

fn is_operator_byte(b: u8) -> bool {
    matches!(
        b,
        b'=' | b'+'
            | b'-'
            | b'*'
            | b'/'
            | b'%'
            | b'&'
            | b'|'
            | b'^'
            | b'!'
            | b'<'
            | b'>'
            | b'?'
            | b'~'
            | b'@'
    )
}

fn push_span(out: &mut String, class: &str, text: &str) {
    if text.is_empty() {
        return;
    }
    out.push_str("<span class=\"");
    out.push_str(class);
    out.push_str("\">");
    escape_into(out, text);
    out.push_str("</span>");
}

fn escape_html(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    escape_into(&mut out, text);
    out
}

    Ok(())
fn escape_into(out: &mut String, text: &str) {
    v_htmlescape::b_escape(text.as_bytes(), out);
}
diff --git a/static/style.css b/static/style.css
index 08cf526..2e7440d 100644
--- a/static/style.css
+++ b/static/style.css
@@ -90,8 +90,8 @@
a:hover,
a:active,
a.active {
  color: var(--crust);
  background: var(--peach);
  color: var(--crust) !important;
  background: var(--peach) !important;
}

a:focus-visible,
@@ -276,6 +276,13 @@
  color: var(--text);
  padding: 0.25rem 0.6rem;
  margin-right: 0.15rem;
}

.tabs a:hover,
.tabs a:active,
.tabs a.active {
  color: var(--crust);
  background: var(--peach);
}

.tree-breadcrumb {
@@ -697,4 +704,95 @@
.readme hr {
  border: none;
  border-top: 1px solid var(--surface1);
}

/* ==========================================================================
   10. Syntax Highlighting (Catppuccin Mocha — ~/.config/nvim/lua/themes/)
   ========================================================================== */
.hl-comment {
  color: var(--surface2);
  font-style: italic;
}

.hl-keyword {
  color: var(--mauve);
  font-style: italic;
}

.hl-include {
  color: var(--blue);
  font-style: italic;
}

.hl-function {
  color: var(--blue);
  font-weight: bold;
}

.hl-function-builtin {
  color: var(--peach);
  font-weight: bold;
}

.hl-macro {
  color: var(--pink);
  font-weight: bold;
}

.hl-type {
  color: var(--yellow);
  font-weight: bold;
}

.hl-type-builtin {
  color: var(--mauve);
}

.hl-module {
  color: var(--yellow);
  font-style: italic;
}

.hl-constant,
.hl-number,
.hl-boolean,
.hl-attribute {
  color: var(--peach);
}

.hl-string {
  color: var(--green);
}

.hl-escape {
  color: var(--pink);
}

.hl-label {
  color: var(--yellow);
}

.hl-property {
  color: var(--lavender);
}

.hl-parameter {
  color: var(--maroon);
}

.hl-variable,
.hl-punctuation {
  color: var(--red);
}

.hl-operator {
  color: var(--sky);
}

.hl-tag {
  color: var(--blue);
}

.hl-tag-delimiter {
  color: var(--teal);
}
diff --git a/templates/about.html b/templates/about.html
index 8152090..15bde82 100644
--- a/templates/about.html
+++ b/templates/about.html
@@ -1,6 +1,6 @@
{% extends "base.html" %}

{% block title %}y2w8 Repos{% endblock %}
{% block title %}y2w8 Repos — about{% endblock %}

{% block header %}
  {{ macros::header() }}
@@ -16,5 +16,29 @@
{% endblock %}

{% block content %}
Hello!
<div class="readme">
  <h2>About</h2>
  <p>
    This is my personal Git server where I host my projects and experiments.
    All repositories here are public and can be cloned over HTTPS:
  </p>
  <pre><code>git clone https://git.y2w8.online/&lt;repo&gt;</code></pre>

  <h2>Contributing</h2>
  <p>
    If you find a bug or want to send a change, you can generate a patch with Git
    and email it to <a href="mailto:yo2w86@gmail.com">yo2w86@gmail.com</a>:
  </p>
  <pre><code>git clone https://git.y2w8.online/&lt;repo&gt;
cd &lt;repo&gt;
# make your changes and commit them
git commit -am "describe your change"
git format-patch origin/main</code></pre>
  <p>
    Then email the generated <code>.patch</code> file to
    <a href="mailto:yo2w86@gmail.com">yo2w86@gmail.com</a>.
    Some repositories are also mirrored on <a href="https://github.com/y2w8">GitHub</a>,
    so you can open a pull request or issue there if you prefer.
  </p>
</div>
{% endblock %}
diff --git a/templates/macros.html b/templates/macros.html
index 676959a..b172639 100644
--- a/templates/macros.html
+++ b/templates/macros.html
@@ -110,8 +110,8 @@
            </span>
            {{ branch.author.name }}
          </td>
          {% let time = branch.author.time.format_relative() %}
          <td class="{{ time.1 }}" title="{{ branch.author.time.format() }}">{{ time.0 }}</td>
          {% let time = branch.last_commit.committer.time.format_relative() %}
          <td class="{{ time.1 }}" title="{{ branch.last_commit.committer.time.format() }}">{{ time.0 }}</td>
        </tr>
      {% endfor %}
    <tr class="no-background">
@@ -205,8 +205,8 @@
    <tbody>
      {% for commit in commits %}
        <tr>
          {% let time = commit.author.time.format_relative() %}
          <td class="{{ time.1 }}" title="{{ commit.author.time.format() }}">{{ time.0 }}</td>
          {% let time = commit.committer.time.format_relative() %}
          <td class="{{ time.1 }}" title="{{ commit.committer.time.format() }}">{{ time.0 }}</td>
          <td>
            <a href="/{{ repo.name }}/commit/?id={{ commit.id }}">{{ commit.summary()? | truncate(80)}}</a>
            {% if commit.is_head(repo)? %}<a href="/{{ repo.name }}/commit/?id={{ commit.id }}" class="badge_head">HEAD</a>{% endif %}
diff --git a/src/git/branch.rs b/src/git/branch.rs
index a23f9a5..eed7aca 100644
--- a/src/git/branch.rs
+++ b/src/git/branch.rs
@@ -1,33 +1,24 @@
use crate::{git::GitSignature, prelude::*, time::Time};
use crate::{git::GitSignature, prelude::*};
use gix::Reference;

pub struct Branch<'repo> {
    pub name: String,
    pub last_commit: Commit<'repo>,
    pub author: GitSignature,
    pub time: Time,
    pub gix: Reference<'repo>,
}

impl<'repo> Branch<'repo> {
    pub fn from_gix(mut reference: Reference<'repo>) -> Result<Branch<'repo>, Error> {
        let commit = reference.peel_to_commit()?;
        let author = GitSignature::from_gix(commit.author()?);
        let time = Time::new(commit.time()?);
        let last_commit = Commit::from_gix(commit)?;
        let name = reference.name().shorten().to_string();
        let last_commit = Commit::from_gix(reference.peel_to_commit()?)?;
        let author = last_commit.author.clone();

        Ok(Branch {
            name: reference.name().shorten().to_string(),
            name,
            last_commit,
            author,
            time,
            gix: reference,
        })
    }

    pub fn is_head(&self, repo: &Repository) -> Result<bool, Error> {
        Ok(repo.head_branch_name()? == self.name)
    }
}

impl Repository {
@@ -50,7 +41,7 @@
        let references = gix_repo.references()?;
        let gix_branches = references.local_branches()?;

        let mut branches: Vec<Branch> = Vec::new();
        let mut branches = Vec::new();
        let mut has_next = false;

        for (i, branch) in gix_branches.skip(offset).enumerate() {
@@ -58,9 +49,7 @@
                has_next = true;
                break;
            }

            let branch = branch?;
            branches.push(Branch::from_gix(branch)?);
            branches.push(Branch::from_gix(branch?)?);
        }
        Ok((branches, has_next))
    }
@@ -68,14 +57,9 @@
    pub fn branch_names(&self) -> Result<Vec<String>, Error> {
        let gix_repo = self.gix();
        let references = gix_repo.references()?;
        let gix_branches = references.local_branches()?;

        let mut names: Vec<String> = Vec::new();

        for branch in gix_branches {
            let branch = branch?;
            names.push(branch.name().shorten().to_string());
        }
        Ok(names)
        references
            .local_branches()?
            .map(|b| Ok(b?.name().shorten().to_string()))
            .collect()
    }
}
diff --git a/src/git/commit.rs b/src/git/commit.rs
index 52e6602..e446207 100644
--- a/src/git/commit.rs
+++ b/src/git/commit.rs
@@ -1,5 +1,4 @@
use std::str::FromStr;
use std::{borrow::Cow, collections::HashMap};
use std::{borrow::Cow, collections::HashMap, str::FromStr};

use gix::{bstr::BStr, utils::AsBStr};

@@ -12,24 +11,18 @@
    pub author: GitSignature,
    pub committer: GitSignature,
    pub time: Time,

    pub gix: gix::Commit<'repo>,
}

impl<'repo> Commit<'repo> {
    pub fn from_gix(gix: gix::Commit<'_>) -> Result<Commit<'_>, Error> {
        let commit_id = gix.id().to_string();

        let tree_id = gix.tree_id()?.to_string();
        let parents = gix.parent_ids().map(|id| id.to_string()).collect();
        Ok(Commit {
            id: commit_id,
            tree_id,
            parents,
            id: gix.id().to_string(),
            tree_id: gix.tree_id()?.to_string(),
            parents: gix.parent_ids().map(|id| id.to_string()).collect(),
            author: GitSignature::from_gix(gix.author()?),
            committer: GitSignature::from_gix(gix.committer()?),
            time: Time::new(gix.time()?),

            gix,
        })
    }
@@ -52,14 +45,12 @@
    }

    pub fn is_head(&self, repo: &Repository) -> Result<bool, Error> {
        let head_commit_id: Option<String> =
            repo.gix().head_commit().ok().map(|c| c.id().to_string());
        Ok(head_commit_id.as_deref() == Some(&self.id))
        let head_id = repo.gix().head_id().ok().map(|id| id.to_string());
        Ok(head_id.as_deref() == Some(&self.id))
    }
}

impl Repository {
    /// Looks up a Commit by its 40-character hex SHA-1 hash.
    pub fn find_commit<'repo>(
        &self,
        gix_repo: &'repo gix::Repository,
@@ -69,8 +60,6 @@
        Commit::from_gix(gix_repo.find_commit(oid)?)
    }

    /// Resolves a Commit either from an explicit `?id=<sha>` query parameter,
    /// or by peeling the active branch/tag reference (`current_ref`) to its latest commit.
    pub fn resolve_commit<'repo>(
        &self,
        gix_repo: &'repo gix::Repository,
@@ -85,7 +74,6 @@
        }
    }

    /// Returns the latest commit on `HEAD` (or falls back to the first valid reference in the repo).
    pub fn last_commit<'repo>(
        &self,
        gix_repo: &'repo gix::Repository,
@@ -101,14 +89,12 @@
        Ok(None)
    }

    /// Builds a map of `commit_sha -> [branch_names]` for every local branch (`refs/heads/*`).
    pub fn branch_tips_by_commit(&self) -> Result<HashMap<String, Vec<String>>, Error> {
        let gix_repo = self.gix();
        let references = gix_repo.references()?;
        let local_branches = references.local_branches()?;

        let mut map: HashMap<String, Vec<String>> = HashMap::new();
        for branch in local_branches {

        for branch in references.local_branches()? {
            let mut branch = branch?;
            let commit_id = branch.peel_to_commit()?.id().to_string();
            map.entry(commit_id)
@@ -118,8 +104,6 @@
        Ok(map)
    }

    /// Walks the commit graph backwards starting from `current_ref` (like `git log`),
    /// sorted newest-first by commit timestamp, with optional filtering and pagination.
    pub fn commits<'repo>(
        &self,
        gix_repo: &'repo gix::Repository,
@@ -128,9 +112,7 @@
        limit: usize,
        filter: Option<&dyn Fn(&Commit) -> bool>,
    ) -> Result<(Vec<Commit<'repo>>, bool), Error> {
        // 1. Parse the branch/tag name (e.g. "main") into its starting commit ObjectId
        let start = gix_repo.rev_parse_single(current_ref.name.as_bstr())?;
        // 2. Walk parent links backwards from `start`, ordered by commit time
        let revwalk = gix_repo
            .rev_walk([start])
            .sorting(gix::revision::walk::Sorting::ByCommitTime(
@@ -138,14 +120,12 @@
            ))
            .all()?;

        let mut commits: Vec<Commit> = Vec::new();
        let mut commits = Vec::new();
        let mut has_next = false;
        let mut matched = 0usize;

        for rev in revwalk {
            let rev = rev?;
            let object = rev.object()?;
            let commit = Commit::from_gix(object)?;
            let commit = Commit::from_gix(rev?.object()?)?;
            if let Some(f) = filter
                && !f(&commit)
            {
diff --git a/src/git/diff.rs b/src/git/diff.rs
index a4b5b7d..d246b42 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -5,17 +5,13 @@
    diff::blob::platform::prepare_diff::Operation,
};

use crate::prelude::*;
use crate::{git::tree::format_mode, prelude::*};

#[derive(Default)]
pub struct Diff {
    pub file_diffs: Vec<FileDiff>,
    pub output: String,
    pub stats: String,
    pub files_changed: usize,
    pub insertions: usize,
    pub deletions: usize,
    pub total: usize,
}

#[derive(Default)]
@@ -53,6 +49,98 @@
pub enum DiffFormat {
    Plain,
    Patch,
}

impl Diff {
    fn finalize(&mut self, is_patch: bool) -> fmt::Result {
        let files_changed = self.file_diffs.len();
        let insertions: usize = self.file_diffs.iter().map(|f| f.insertions).sum();
        let deletions: usize = self.file_diffs.iter().map(|f| f.deletions).sum();
        let total = deletions.saturating_add(insertions);

        if is_patch {
            self.write_patch_stat_bars(insertions, total)?;
        }
        self.write_summary_line(files_changed, insertions, deletions)?;
        self.compute_percentages(total);
        Ok(())
    }

    fn write_patch_stat_bars(
        &mut self,
        total_insertions: usize,
        total_changes: usize,
    ) -> fmt::Result {
        const WIDTH: usize = 80;

        let (max_name_len, max_change_len) =
            self.file_diffs
                .iter()
                .fold((0, 0), |(max_name, max_change), f| {
                    let digits = ((f.insertions + f.deletions + 1).ilog10() + 1) as usize;
                    (max_name.max(f.path.len()), max_change.max(digits))
                });

        for f in &self.file_diffs {
            let local_changes = f.insertions + f.deletions;
            let width = WIDTH.min(local_changes);

            let add_w = (width * f.insertions) / total_changes;
            let del_w = (width * f.deletions) / total_changes;
            let rem_w = width - (add_w + del_w);

            let plus_str = "+".repeat(add_w + rem_w.min(total_insertions));
            let minus_str = "-".repeat(del_w + (rem_w - rem_w.min(total_insertions)));

            writeln!(
                self.stats,
                " {:max_name_len$} | {:max_change_len$} {plus_str}{minus_str}",
                f.path, local_changes
            )?;
        }
        Ok(())
    }

    fn write_summary_line(
        &mut self,
        files_changed: usize,
        insertions: usize,
        deletions: usize,
    ) -> fmt::Result {
        for (i, (singular, plural, amount)) in [
            ("file changed", "files changed", files_changed),
            ("insertion(+)", "insertions(+)", insertions),
            ("deletion(-)", "deletions(-)", deletions),
        ]
        .into_iter()
        .enumerate()
        {
            if amount == 0 {
                continue;
            }
            let prefix = if i == 0 { "" } else { "," };
            let desc = if amount == 1 { singular } else { plural };
            write!(self.stats, "{prefix} {amount} {desc}")?;
        }
        writeln!(self.stats)
    }

    fn compute_percentages(&mut self, total_changes: usize) {
        for f in &mut self.file_diffs {
            f.total_percentage = if total_changes == 0 {
                0.0
            } else if total_changes < 100 {
                total_changes as f64
            } else {
                (f.total as f64) * 100.0 / (total_changes as f64)
            };

            if f.total > 0 {
                f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
                f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
            }
        }
    }
}

impl<'repo> Commit<'repo> {
@@ -68,19 +156,15 @@
        }
    }

    /// Computes the diff between this commit and its first parent commit (or an empty tree if this is the initial commit).
    fn diff_with<F: DiffFormatter>(
        &self,
        repo: &Repository,
        limit_file: Option<&str>,
        formatter: F,
    ) -> Result<Diff, Error> {
        const WIDTH: usize = 80;
        let mut diff = Diff::default();
        let gix_repo = repo.gix();

        // Phase 1: Get this commit's root directory Tree and its first parent's root directory Tree.
        // If the commit has no parents (the very first commit in the repo), compare against an empty Tree.
        let current_tree = self.gix.tree()?;
        let first_parent = self.gix.parent_ids().next();
        let parent_tree = match first_parent {
@@ -90,8 +174,6 @@
        let parent_id = first_parent.map(|id| id.to_string());
        let commit_id = self.gix.id.to_string();

        // `tree_diff_cache` is held by the tree-walker while iterating directory changes;
        // `blob_diff_cache` is used inside the callback to diff individual file contents (Blobs).
        let mut tree_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;
        let mut blob_diff_cache = gix_repo.diff_resource_cache_for_tree_diff()?;

@@ -112,104 +194,16 @@
                .handle(change, repo, parent_id.as_deref(), &commit_id, limit_file)
            },
        )?;

        let files_changed = diff.file_diffs.len();
        let insertions: usize = diff.file_diffs.iter().map(|f| f.insertions).sum();
        let deletions: usize = diff.file_diffs.iter().map(|f| f.deletions).sum();
        diff.files_changed = files_changed;
        diff.insertions = insertions;
        diff.deletions = deletions;
        diff.total = diff.deletions.saturating_add(diff.insertions);

        if formatter.format() == DiffFormat::Patch {
            let (max_file_name_length, max_change_length) = diff.file_diffs.iter().fold(
                (0, 0),
                |(max_file_name_length, max_change_length), stats| {
                    (
                        max_file_name_length.max(stats.path.len()),
                        max_change_length
                            .max(((stats.insertions + stats.deletions + 1).ilog10() + 1) as usize),
                    )
                },
            );

            for file_diff in &diff.file_diffs {
                let local_changes = file_diff.insertions + file_diff.deletions;
                let width = WIDTH.min(local_changes);

                let addition_width = (width * file_diff.insertions) / diff.total;
                let deletion_width = (width * file_diff.deletions) / diff.total;

                // Handle edge case where total width is less than total changes
                let remaining_width = width - (addition_width + deletion_width);
                let adjusted_addition_width = addition_width + remaining_width.min(diff.insertions);
                let adjusted_deletion_width =
                    deletion_width + (remaining_width - remaining_width.min(diff.insertions));

                // Generate the string representation
                let plus_str = "+".repeat(adjusted_addition_width);
                let minus_str = "-".repeat(adjusted_deletion_width);

                let file = file_diff.path.as_str();
                writeln!(diff.stats, " {file:max_file_name_length$} | {local_changes:max_change_length$} {plus_str}{minus_str}").unwrap();
            }
        }

        for (i, (singular_desc, plural_desc, amount)) in [
            ("file changed", "files changed", files_changed),
            ("insertion(+)", "insertions(+)", insertions),
            ("deletion(-)", "deletions(-)", deletions),
        ]
        .into_iter()
        .enumerate()
        {
            if amount == 0 {
                continue;
            }

            let prefix = if i == 0 { "" } else { "," };
            let desc = if amount == 1 {
                singular_desc
            } else {
                plural_desc
            };
            write!(diff.stats, "{prefix} {amount} {desc}")?;
        }
        writeln!(diff.stats)?;

        for f in &mut diff.file_diffs {
            f.total_percentage = if diff.total < 100 && diff.total > 0 {
                diff.total as f64
            } else if diff.total > 0 {
                (f.total as f64) * 100.0 / (diff.total as f64)
            } else {
                0.0
            };

            if f.total > 0 {
                f.insertions_percentage = (f.insertions as f64) * 100.0 / (f.total as f64);
                f.deletions_percentage = (f.deletions as f64) * 100.0 / (f.total as f64);
            }
        }

        diff.finalize(formatter.format() == DiffFormat::Patch)?;
        Ok(diff)
    }
}

trait DiffFormatter {
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>);

    fn write(&self, output: &mut String, class: &str, data: &str);

    fn binary(
        &self,
        output: &mut String,
        left: &str,
        right: &str,
        left_content: &[u8],
        right_content: &[u8],
    );

    fn binary(&self, output: &mut String, left: &str, right: &str);
    fn path_line(
        &self,
        prefix: char,
@@ -219,7 +213,6 @@
        rela_path: &BStr,
        rev_id: &str,
    ) -> String;

    fn format(&self) -> DiffFormat;
}

@@ -245,11 +238,12 @@

        let path = change.location().to_string();
        if let Some(limit_file) = limit_file
            && limit_file != path
            && !limit_file.is_empty()
            && limit_file != path
        {
            return Ok(gix::object::tree::diff::Action::Continue(()));
        }

        let mut diff = FileDiff {
            path,
            ..Default::default()
@@ -288,7 +282,6 @@
            );
        }

        // mode shown in the diffstat table: whichever side still exists
        let mode_source = if matches!(diff.state, FileState::Removed) {
            prep.old.mode
        } else {
@@ -296,9 +289,6 @@
        };
        let raw_mode = u32::from_str_radix(mode_source.as_octal_str().to_str()?, 8)?;
        diff.mode = format_mode(raw_mode);

        // copy from / copy to / rename old / rename new / rename from /
        // rename to / similarity index / dissimilarity index — TODO

        let (index_suffix_sep, index_suffix) = if prep.old.mode == prep.new.mode {
            (" ", prep.new.mode.as_octal_str())
@@ -362,19 +352,11 @@
                        prep.old.id, prep.new.id,
                    ),
                );

                self.formatter.binary(
                    self.output,
                    old_path.as_ref(),
                    new_path.as_ref(),
                    prep.old.data.as_slice().unwrap_or_default(),
                    prep.new.data.as_slice().unwrap_or_default(),
                );
                self.formatter.binary(self.output, &old_path, &new_path);
            }
        }

        self.diffs.push(diff);

        self.resource_cache.clear_resource_cache_keep_allocation();
        Ok(gix::object::tree::diff::Action::Continue(()))
    }
@@ -425,14 +407,12 @@
            );

            let mut before_pos = before_start;
            let mut _after_pos = after_start;

            for hunk in &hunks[start..end] {
                while before_pos < hunk.before.start {
                    let line = input.interner[input.before[before_pos as usize]];
                    formatter.write(output, "context", line);
                    before_pos += 1;
                    _after_pos += 1;
                }

                for pos in hunk.before.clone() {
@@ -445,27 +425,23 @@
                    let line = input.interner[input.after[pos as usize]];
                    formatter.write(output, "addition", line);
                }
                _after_pos = hunk.after.end;
            }

            while before_pos < before_end {
                let line = input.interner[input.before[before_pos as usize]];
                formatter.write(output, "context", line);
                before_pos += 1;
                _after_pos += 1;
            }
        }
    }
}

// ---- unchanged, per your request ----
struct PlainDiffFormatter;

impl DiffFormatter for PlainDiffFormatter {
    fn file_header(&self, output: &mut String, data: fmt::Arguments<'_>) {
        write!(output, r#"<span class="diff-file-header">"#).unwrap();
        write!(output, "{data}").unwrap();
        output.push_str("</span>\n");
        write!(output, r#"<span class="diff-file-header">{data}</span>"#).unwrap();
        output.push('\n');
    }

    fn write(&self, output: &mut String, class: &str, data: &str) {
@@ -474,15 +450,7 @@
        output.push_str("</span>");
    }

    fn binary(
        &self,
        output: &mut String,
        left: &str,
        right: &str,
        _left_content: &[u8],
        _right_content: &[u8],
    ) {
        // todo: actually perform the diff and write a `GIT binary patch` out
    fn binary(&self, output: &mut String, left: &str, right: &str) {
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
    }

@@ -509,7 +477,6 @@
    }
}

// ---- new: plain unified diff, git-apply compatible ----
struct PatchDiffFormatter;

impl DiffFormatter for PatchDiffFormatter {
@@ -518,28 +485,17 @@
    }

    fn write(&self, output: &mut String, class: &str, data: &str) {
        // unified diff requires a literal leading +/-/space on every
        // content line — this is what the Plain (CSS-classed) formatter
        // can skip but a real patch cannot.
        let prefix = match class {
            "addition" => "+",
            "deletion" => "-",
            "context" => " ",
            _ => "", // hunk header line, no prefix
            _ => "",
        };
        output.push_str(prefix);
        output.push_str(data);
    }

    fn binary(
        &self,
        output: &mut String,
        left: &str,
        right: &str,
        _left_content: &[u8],
        _right_content: &[u8],
    ) {
        // todo: emit an actual `GIT binary patch` block
    fn binary(&self, output: &mut String, left: &str, right: &str) {
        writeln!(output, "Binary files {left} and {right} differ").unwrap();
    }

@@ -561,28 +517,5 @@

    fn format(&self) -> DiffFormat {
        DiffFormat::Patch
    }
}

pub fn format_mode(mode: u32) -> String {
    let file_type = match mode & 0o170000 {
        0o040000 => 'd',
        0o120000 => 'l',
        0o160000 => 'm',
        0o100000 => '-',
        _ => '?',
    };

    let perms = mode & 0o777;
    let mut out = String::with_capacity(10);
    out.push(file_type);

    for &shift in &[6, 3, 0] {
        let bits = (perms >> shift) & 0o7;
        out.push(if bits & 0o4 != 0 { 'r' } else { '-' });
        out.push(if bits & 0o2 != 0 { 'w' } else { '-' });
        out.push(if bits & 0o1 != 0 { 'x' } else { '-' });
    }

    out
}
diff --git a/src/git/repository.rs b/src/git/repository.rs
index 914a60e..9fc99b1 100644
--- a/src/git/repository.rs
+++ b/src/git/repository.rs
@@ -11,9 +11,8 @@
use crate::{
    error::Error,
    git::{
        commit::Commit,
        refs::Ref,
        tree::{Blob, PathView},
        tree::{self, Blob, PathView},
    },
};

@@ -22,11 +21,7 @@
    pub name: String,
    pub description: String,
    pub owner: Option<String>,

    // Path on disk (not exposed to clients)
    pub path: PathBuf,
    // ThreadSafeRepository holds shared repo state so it can live across web worker threads.
    // Call `self.gix()` on a worker thread to get a thread-local `gix::Repository` with object caches.
    pub gix: gix::ThreadSafeRepository,
}

@@ -45,7 +40,6 @@
        };

        let gix = gix::ThreadSafeRepository::open(path).map_err(|_| Error::Failed)?;

        let owner = gix
            .to_thread_local()
            .config_snapshot()
@@ -61,29 +55,21 @@
        })
    }

    /// Converts the shared `ThreadSafeRepository` handle into a thread-local `gix::Repository`
    /// that caches decoded Git objects in memory for the current request.
    pub fn gix(&self) -> gix::Repository {
        self.gix.to_thread_local()
    }

    /// Looks for a `README*` file in the root folder (`Tree`) of the `HEAD` commit.
    pub fn readme(&self) -> Option<String> {
        let gix_repo = self.gix();
        // 1. Follow HEAD -> branch -> latest Commit object
        let commit = gix_repo.head().ok()?.peel_to_commit().ok()?;
        // 2. Get the root directory snapshot (Tree) of that Commit
        let tree = commit.tree().ok()?;

        // 3. Find the first entry whose filename starts with "readme" (case-insensitive)
        let tree = gix_repo.head().ok()?.peel_to_commit().ok()?.tree().ok()?;

        for entry in tree.iter().flatten() {
            if entry
                .filename()
                .to_string()
                .to_lowercase()
                .to_ascii_lowercase()
                .starts_with("readme")
            {
                // Load the file contents (Blob) from Git's object database
                let blob = entry.object().ok()?.into_blob();
                return Some(String::from_utf8_lossy(&blob.data).into_owned());
            }
@@ -91,14 +77,12 @@
        None
    }

    /// Streams a commit or branch's directory tree into an in-memory `.tar.gz` archive.
    pub fn archive(
        &self,
        current_ref: &Ref,
        commit: &Option<String>,
    ) -> Result<(Vec<u8>, String), anyhow::Error> {
        let gix_repo = self.gix();
        // Resolve the root directory Tree either from a specific commit hash or from a branch/tag ref
        let (tree, filename) = if let Some(commit) = commit {
            (
                self.find_commit(&gix_repo, commit)?.gix.tree()?,
@@ -106,7 +90,7 @@
            )
        } else {
            (
                gix_repo.find_reference(&current_ref.name)?.peel_to_tree()?,
                Self::root_tree(&gix_repo, current_ref)?,
                format!("{}.tar.gz", current_ref.name.replace('/', "-")),
            )
        };
@@ -116,9 +100,7 @@

        Self::add_tree_to_archive(&tree, "", &mut builder)?;

        // Flush the tar footer, then finish the gzip stream to get the final compressed bytes.
        let encoder = builder.into_inner()?;
        let bytes = encoder.finish()?;
        let bytes = builder.into_inner()?.finish()?;
        Ok((bytes, filename))
    }

@@ -151,73 +133,47 @@

                builder.append_data(&mut header, &path, &data[..])?;
            }
            // symlinks (mode.is_link()) intentionally skipped here — add
            // handling if you need them (header.set_entry_type(EntryType::Symlink)
            // + set_link_name to the blob content as the target path).
        }
        Ok(())
    }

    /// Resolves a relative repository path on `current_ref` to either a folder listing (`PathView::Tree`)
    /// or a file view (`PathView::Blob`).
    pub fn resolve_path(&self, current_ref: &Ref, path: &str) -> anyhow::Result<PathView> {
        let gix_repo = self.gix();
        let commit = Commit::from_gix(
            gix_repo
                .find_reference(&current_ref.name)?
                .peel_to_commit()?,
        )?;
        let root_tree = Self::root_tree(&gix_repo, current_ref)?;
        let path = path.trim_matches('/');

        if path.is_empty() {
            return Ok(PathView::Tree(commit.tree("")?));
            return Ok(PathView::Tree(tree::read_entries(&root_tree, "")?));
        }

        let root_tree = commit.gix.tree().context("failed to get root tree")?;
        let entry = root_tree
            .lookup_entry_by_path(path)
            .with_context(|| format!("failed lookup for path: {path}"))?
            .with_context(|| format!("path not found: {path}"))?;

        let entry = Self::lookup_entry(&root_tree, path)?;
        let mode = entry.mode();

        match mode.kind() {
            EntryKind::Tree => {
                let entries = commit.tree(path)?;
                Ok(PathView::Tree(entries))
                let subtree = entry.object()?.into_tree();
                Ok(PathView::Tree(tree::read_entries(&subtree, path)?))
            }
            EntryKind::Blob | EntryKind::BlobExecutable => {
                let blob = entry
                    .object()
                    .context("failed to load blob object")?
                    .try_into_blob()
                    .map_err(|_| anyhow::anyhow!("entry is not a blob"))?;

                let id = entry.oid().to_string();
                let size = blob.data.len() as u64;

                // Try decoding as UTF-8 text; if it contains non-UTF-8 bytes, treat it as binary (None).
                let blob = entry.object()?.into_blob();
                let lines = std::str::from_utf8(&blob.data)
                    .ok()
                    .map(|s| s.lines().map(str::to_string).collect());
                    .map(|s| crate::syntax_highlight::highlight_lines(s, path));

                Ok(PathView::Blob(Blob {
                    id,
                    id: entry.oid().to_string(),
                    mode: mode.value() as u32,
                    size,
                    size: blob.data.len() as u64,
                    lines,
                }))
            }
            EntryKind::Link => {
                anyhow::bail!("symlinks are not yet supported for direct viewing")
            }
            EntryKind::Link => anyhow::bail!("symlinks are not yet supported for direct viewing"),
            EntryKind::Commit => {
                anyhow::bail!("path resolves to a submodule, not a viewable file/dir")
            }
        }
    }

    /// Reads the raw bytes of a file (`Blob`) at `path` without splitting lines or cloning buffers.
    /// Returns `Ok(None)` if `path` points to a directory (`Tree`).
    pub fn read_raw_blob(&self, current_ref: &Ref, path: &str) -> anyhow::Result<Option<Vec<u8>>> {
        let path = path.trim_matches('/');
        if path.is_empty() {
@@ -225,25 +181,13 @@
        }

        let gix_repo = self.gix();
        let root_tree = gix_repo
            .find_reference(&current_ref.name)?
            .peel_to_tree()
            .context("failed to get root tree")?;
        let root_tree = Self::root_tree(&gix_repo, current_ref)?;
        let entry = Self::lookup_entry(&root_tree, path)?;

        let entry = root_tree
            .lookup_entry_by_path(path)
            .with_context(|| format!("failed lookup for path: {path}"))?
            .with_context(|| format!("path not found: {path}"))?;

        match entry.mode().kind() {
            EntryKind::Tree => Ok(None),
            EntryKind::Blob | EntryKind::BlobExecutable => {
                let blob = entry
                    .object()
                    .context("failed to load blob object")?
                    .try_into_blob()
                    .map_err(|_| anyhow::anyhow!("entry is not a blob"))?;
                // `.detach().data` moves the underlying Vec<u8> out of the gix Blob without cloning.
                let blob = entry.object()?.into_blob();
                Ok(Some(blob.detach().data))
            }
            EntryKind::Link => anyhow::bail!("symlinks are not yet supported for direct viewing"),
@@ -251,5 +195,25 @@
                anyhow::bail!("path resolves to a submodule, not a viewable file/dir")
            }
        }
    }

    fn root_tree<'a>(
        gix_repo: &'a gix::Repository,
        current_ref: &Ref,
    ) -> anyhow::Result<gix::Tree<'a>> {
        gix_repo
            .find_reference(&current_ref.name)?
            .peel_to_tree()
            .context("failed to get root tree")
    }

    fn lookup_entry<'a>(
        root_tree: &gix::Tree<'a>,
        path: &str,
    ) -> anyhow::Result<gix::object::tree::Entry<'a>> {
        root_tree
            .lookup_entry_by_path(path)
            .with_context(|| format!("failed lookup for path: {path}"))?
            .with_context(|| format!("path not found: {path}"))
    }
}
diff --git a/src/git/tag.rs b/src/git/tag.rs
index 259c161..54f4b78 100644
--- a/src/git/tag.rs
+++ b/src/git/tag.rs
@@ -28,53 +28,39 @@
}

impl Tag {
    /// Builds a `Tag` from a `refs/tags/*` Git reference.
    ///
    /// Git has two types of tags:
    /// 1. **Annotated tags** (`git tag -a`): store a dedicated Tag object with a tagger, date, and message.
    /// 2. **Lightweight tags** (`git tag`): just a reference pointing directly at a Commit (no Tag object).
    pub fn from_gix(mut gix: gix::Reference<'_>) -> anyhow::Result<Tag> {
        let name = gix.name().shorten().to_string();
        let id = gix.id().to_string();

        if let Ok(tag_obj) = gix.peel_to_tag() {
            // Case 1: Annotated tag
        let (message, tagger, tagged_object, time) = if let Ok(tag_obj) = gix.peel_to_tag() {
            let tag_ref = tag_obj.decode()?;
            let message = tag_ref.message.to_string();
            let tagged_object =
                TaggedObject::from_kind_and_id(tag_ref.target_kind, tag_ref.target.to_string());
            let tagger = tag_ref.tagger()?.map(GitSignature::from_gix);

            let time = match &tagger {
                Some(t) => t.time.clone(),
                None => Self::commit_time(&mut gix)?,
            };

            Ok(Tag {
                name,
                id: gix.id().to_string(),
                message,
                tagger,
                tagged_object,
                time,
            })
            (message, tagger, tagged_object, time)
        } else {
            // Case 2: Lightweight tag (points directly to a Commit or Tree)
            let target = gix
                .follow_to_object()
                .context("Failed to resolve lightweight tag target")?;
            let target_kind = target.header()?.kind();
            let tagged_object = TaggedObject::from_kind_and_id(target_kind, target.to_string());
            let tagged_object =
                TaggedObject::from_kind_and_id(target.header()?.kind(), target.to_string());
            let time = Self::commit_time(&mut gix)?;

            Ok(Tag {
                name,
                id: gix.id().to_string(),
                message: String::new(),
                tagger: None,
                tagged_object,
                time,
            })
        }
            (String::new(), None, tagged_object, time)
        };

        Ok(Tag {
            name,
            id,
            message,
            tagger,
            tagged_object,
            time,
        })
    }

    fn commit_time(gix: &mut gix::Reference<'_>) -> anyhow::Result<Time> {
@@ -97,7 +83,7 @@
        let references = gix_repo.references()?;
        let gix_tags = references.tags()?;

        let mut tags: Vec<Tag> = Vec::new();
        let mut tags = Vec::new();
        let mut has_next = false;

        for (i, rev) in gix_tags.skip(offset).enumerate() {
@@ -105,7 +91,6 @@
                has_next = true;
                break;
            }

            let rev = rev.map_err(|e| anyhow::anyhow!(e))?;
            tags.push(Tag::from_gix(rev)?);
        }
diff --git a/src/git/tree.rs b/src/git/tree.rs
index 60de1e2..4b8680a 100644
--- a/src/git/tree.rs
+++ b/src/git/tree.rs
@@ -1,4 +1,3 @@
use crate::prelude::*;
use anyhow::Context;
use gix::objs::tree::EntryKind;
use serde::Serialize;
@@ -6,9 +5,9 @@
#[derive(Clone)]
pub struct TreeEntry {
    pub name: String,
    pub path: String, // full path from repo root, for building links
    pub path: String,
    pub kind: EntryKind,
    pub size: Option<u64>, // only set for files
    pub size: Option<u64>,
    pub mode: u32,
    pub id: String,
}
@@ -22,76 +21,21 @@
    }

    pub fn mode_display(&self) -> String {
        format_mode(self.mode, &self.kind)
        format_entry_mode(self.mode, &self.kind)
    }
}

impl<'repo> Commit<'repo> {
    pub fn tree(&self, dir_path: &str) -> anyhow::Result<Vec<TreeEntry>> {
        let mut entries: Vec<TreeEntry> = Vec::new();

        let base_tree = if dir_path.is_empty() {
            self.gix.tree().context("failed to get root tree")?
        } else {
            self.gix
                .tree()
                .context("failed to get root tree")?
                .lookup_entry_by_path(dir_path)
                .with_context(|| format!("failed lookup for path: {dir_path}"))?
                .with_context(|| format!("path not found: {dir_path}"))?
                .object()
                .context("failed to load object")?
                .try_into_tree()
                .context("path did not resolve to a tree")?
        };

        for entry in base_tree.iter() {
            let entry = entry.context("failed to read tree entry")?;
            let name = entry.filename().to_string();
            let full_path = if dir_path.is_empty() {
                name.clone()
            } else {
                format!("{dir_path}/{name}")
            };
            let id = entry.oid().to_string();
            let mode = entry.mode();
            let kind = mode.kind();

            let size = if matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
                self.gix
                    .repo
                    .find_header(entry.oid())
                    .ok()
                    .map(|h| h.size())
            } else {
                None
            };

            entries.push(TreeEntry {
                name,
                path: full_path,
                kind,
                size,
                mode: mode.value() as u32,
                id,
            });
        }

        Ok(entries)
    }
}

#[derive(Clone, Serialize)]
pub struct Blob {
    pub id: String,
    pub mode: u32,
    pub size: u64,
    pub lines: Option<Vec<String>>, // None => binary, can't show as text
    pub lines: Option<Vec<String>>,
}

impl Blob {
    pub fn mode_display(&self) -> String {
        format_mode(self.mode, &EntryKind::Blob)
        format_entry_mode(self.mode, &EntryKind::Blob)
    }
}

@@ -103,9 +47,56 @@
#[derive(Clone, Serialize)]
pub struct Breadcrumb {
    pub name: String,
    pub path: String, // cumulative path up to and including this segment
    pub path: String,
}

pub fn read_entries(base_tree: &gix::Tree<'_>, dir_path: &str) -> anyhow::Result<Vec<TreeEntry>> {
    let mut entries = Vec::new();

    for entry in base_tree.iter() {
        let entry = entry.context("failed to read tree entry")?;
        let name = entry.filename().to_string();
        let path = if dir_path.is_empty() {
            name.clone()
        } else {
            format!("{dir_path}/{name}")
        };
        let mode = entry.mode();
        let kind = mode.kind();

        let size = if matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
            base_tree
                .repo
                .find_header(entry.oid())
                .ok()
                .map(|h| h.size())
        } else {
            None
        };

        entries.push(TreeEntry {
            name,
            path,
            kind,
            size,
            mode: mode.value() as u32,
            id: entry.oid().to_string(),
        });
    }

    // Directories first (right under `..`), then alphabetical by name
    entries.sort_by(|a, b| {
        let a_is_dir = matches!(a.kind, EntryKind::Tree);
        let b_is_dir = matches!(b.kind, EntryKind::Tree);
        b_is_dir
            .cmp(&a_is_dir)
            .then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase()))
            .then_with(|| a.name.cmp(&b.name))
    });

    Ok(entries)
}

pub fn build_breadcrumbs(path: &str) -> Vec<Breadcrumb> {
    let mut crumbs = Vec::new();
    let mut acc = String::new();
@@ -129,27 +120,42 @@
    }
    match path.rsplit_once('/') {
        Some((parent, _)) => Some(parent.to_string()),
        None => Some(String::new()), // one level deep -> parent is root
        None => Some(String::new()),
    }
}

pub fn format_mode(mode: u32, kind: &EntryKind) -> String {
pub fn format_entry_mode(mode: u32, kind: &EntryKind) -> String {
    match kind {
        EntryKind::Tree => "drwxr-xr-x".to_string(),
        EntryKind::Link => "lrwxrwxrwx".to_string(),
        EntryKind::Commit => "m---------".to_string(), // submodule / gitlink
        EntryKind::Blob | EntryKind::BlobExecutable => {
            let perm = mode & 0o777;
            let mut s = String::from("-");
            for shift in [6, 3, 0] {
                let bits = (perm >> shift) & 0o7;
                s.push(if bits & 0o4 != 0 { 'r' } else { '-' });
                s.push(if bits & 0o2 != 0 { 'w' } else { '-' });
                s.push(if bits & 0o1 != 0 { 'x' } else { '-' });
            }
            s
        }
        EntryKind::Commit => "m---------".to_string(),
        EntryKind::Blob | EntryKind::BlobExecutable => format_rwx('-', mode),
    }
}

pub fn format_mode(mode: u32) -> String {
    let file_type = match mode & 0o170000 {
        0o040000 => 'd',
        0o120000 => 'l',
        0o160000 => 'm',
        0o100000 => '-',
        _ => '?',
    };
    format_rwx(file_type, mode)
}

fn format_rwx(file_type: char, mode: u32) -> String {
    let perms = mode & 0o777;
    let mut out = String::with_capacity(10);
    out.push(file_type);

    for shift in [6, 3, 0] {
        let bits = (perms >> shift) & 0o7;
        out.push(if bits & 0o4 != 0 { 'r' } else { '-' });
        out.push(if bits & 0o2 != 0 { 'w' } else { '-' });
        out.push(if bits & 0o1 != 0 { 'x' } else { '-' });
    }
    out
}

fn format_size(bytes: u64) -> String {
diff --git a/src/routes/git.rs b/src/routes/git.rs
index d94b7e4..e37ba99 100644
--- a/src/routes/git.rs
+++ b/src/routes/git.rs
@@ -19,22 +19,20 @@
        None => return Ok(HttpResponse::BadRequest().body("Missing service parameter")),
    };

    if service != "git-upload-pack" && service != "git-receive-pack" {
        return Ok(HttpResponse::BadRequest().body("Unsupported service"));
    // Only allow `git-upload-pack` (read-only clone/fetch/pull).
    // `git-receive-pack` (push) is disabled over HTTP so pushes are only possible over SSH.
    if service != "git-upload-pack" {
        return Ok(HttpResponse::Forbidden().body("Push over HTTP is disabled; use SSH"));
    }

    let name = path.into_inner();
    let repo = match data.find_repo(&name) {
        Some(r) => r,
        None => return Ok(HttpResponse::NotFound().body("Repo not found")),
    };

    let first_line = format!("# service={}\n", service);
    let pkt_line = format!("{:04x}{}", first_line.len() + 4, first_line);
    let repo = data.get_repo(&path)?;

    let first_line = "# service=git-upload-pack\n";
    let pkt_line = format!("{:04x}{first_line}", first_line.len() + 4);
    let zero_line = "0000";

    let output = Command::new("git")
        .arg(service.strip_prefix("git-").unwrap())
        .arg("upload-pack")
        .arg("--stateless-rpc")
        .arg("--advertise-refs")
        .arg(&repo.path)
@@ -48,7 +46,7 @@
            body.extend_from_slice(&out.stdout);

            Ok(HttpResponse::Ok()
                .content_type(format!("application/x-{}-advertisement", service))
                .content_type("application/x-git-upload-pack-advertisement")
                .body(body))
        }
        Err(_) => Ok(HttpResponse::InternalServerError().body("Git command failed")),
@@ -60,48 +58,25 @@
    path: web::Path<String>,
    data: web::Data<App>,
    body: Bytes,
) -> ActixResult<HttpResponse> {
    let name = path.into_inner();
    let repo = match data.find_repo(&name) {
        Some(r) => r,
        None => return Ok(HttpResponse::NotFound().body("Repo not found")),
    };

    Ok(handle_git_rpc("upload-pack", repo, body).await)
}

#[post("/{repo}/git-receive-pack")]
pub async fn git_receive_pack(
    path: web::Path<String>,
    data: web::Data<App>,
    body: Bytes,
) -> ActixResult<HttpResponse> {
    let name = path.into_inner();
    let repo = match data.find_repo(&name) {
        Some(r) => r,
        None => return Ok(HttpResponse::NotFound().body("Repo not found")),
    };

    Ok(handle_git_rpc("receive-pack", repo, body).await)
}
) -> Result<HttpResponse, Error> {
    let repo = data.get_repo(&path)?;

async fn handle_git_rpc(service: &str, repo: Repository, body: Bytes) -> HttpResponse {
    let mut child = Command::new("git")
        .arg(service)
        .arg("upload-pack")
        .arg("--stateless-rpc")
        .arg(&repo.path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
        .map_err(|e| anyhow::anyhow!(e))?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin.write_all(&body).unwrap();
        stdin.write_all(&body).map_err(|e| anyhow::anyhow!(e))?;
    }

    let output = child.wait_with_output().unwrap();
    let output = child.wait_with_output().map_err(|e| anyhow::anyhow!(e))?;

    HttpResponse::Ok()
        .content_type(format!("application/x-{}-result", service))
        .body(output.stdout)
    Ok(HttpResponse::Ok()
        .content_type("application/x-git-upload-pack-result")
        .body(output.stdout))
}
diff --git a/src/routes/static.rs b/src/routes/static.rs
index 0b4fe73..cb0e0b1 100644
--- a/src/routes/static.rs
+++ b/src/routes/static.rs
@@ -19,6 +19,7 @@
            let mime_type = mime_guess::from_path(&path).first_or_octet_stream();
            Ok(HttpResponse::Ok()
                .content_type(mime_type.as_ref())
                .insert_header(("Cache-Control", "no-cache, must-revalidate"))
                .body(content.data.into_owned()))
        }
        None => Ok(HttpResponse::NotFound().body("Not Found")),
diff --git a/templates/repository/tree.html b/templates/repository/tree.html
index abea3e3..66f3624 100644
--- a/templates/repository/tree.html
+++ b/templates/repository/tree.html
@@ -77,7 +77,7 @@
            {% for line in lines %}
              <tr>
                <td class="line-no">{{ loop.index }}</td>
                <td class="line-content"><pre>{{ line }}</pre></td>
                <td class="line-content"><pre>{{ line|safe }}</pre></td>
              </tr>
            {% endfor %}
          </tbody>