diff --git a/pygittools/src/pygittools/formatting.py b/pygittools/src/pygittools/formatting.py
new file mode 100644
index 0000000..6f07e79
--- /dev/null
+++ b/pygittools/src/pygittools/formatting.py
@@ -0,0 +1,18 @@
+"""Shared text helpers used by git tooling and the web UI."""
+
+from __future__ import annotations
+
+# Fallback encoding when bytes are not valid UTF-8 (gitweb: $fallback_encoding)
+FALLBACK_ENCODING = "latin1"
+
+
+def to_utf8(s: str | bytes | None) -> str | None:
+    """Decode to UTF-8 string; use fallback encoding if not valid UTF-8. Port of to_utf8."""
+    if s is None:
+        return None
+    if isinstance(s, str):
+        return s
+    try:
+        return s.decode("utf-8")
+    except UnicodeDecodeError:
+        return s.decode(FALLBACK_ENCODING, errors="replace")
diff --git a/pygittools/src/pygittools/formatting_test.py b/pygittools/src/pygittools/formatting_test.py
new file mode 100644
index 0000000..e727db5
--- /dev/null
+++ b/pygittools/src/pygittools/formatting_test.py
@@ -0,0 +1,24 @@
+from __future__ import annotations
+
+from pygittools import formatting
+
+
+def test_to_utf8_returns_string_input_unchanged() -> None:
+    assert formatting.to_utf8("hello") == "hello"
+
+
+def test_to_utf8_decodes_utf8_bytes_successfully() -> None:
+    assert formatting.to_utf8("cafe".encode("utf-8")) == "cafe"  # noqa: UP012
+
+
+def test_to_utf8_uses_fallback_encoding_when_utf8_fails() -> None:
+    assert formatting.to_utf8(b"\xf1") == "ñ"
+
+
+def test_to_utf8_fallback_decode_uses_replace_for_invalid_bytes() -> None:
+    original: str = formatting.FALLBACK_ENCODING
+    formatting.FALLBACK_ENCODING = "ascii"
+    try:
+        assert formatting.to_utf8(b"\xffabc") == "\ufffdabc"
+    finally:
+        formatting.FALLBACK_ENCODING = original
diff --git a/pygittools/src/pygittools/git_helpers.py b/pygittools/src/pygittools/git_helpers.py
new file mode 100644
index 0000000..7dd9915
--- /dev/null
+++ b/pygittools/src/pygittools/git_helpers.py
@@ -0,0 +1,460 @@
+"""
+Git helpers via pygit2: config, refs, trees, blobs, history, diffs.
+Ported from gitweb/gitweb.perl. Callers pass an open Repository (and git_dir when
+filesystem paths under the project are needed).
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from contextlib import suppress
+from typing import Any
+
+import pygit2
+from pygit2 import Blob, Commit, Repository, Tag, Tree
+
+from pygittools.formatting import to_utf8
+
+_REPO_CONFIG_LEVELS = frozenset({5, 6})  # git_config_level_t local, worktree
+
+# Common README filenames to look for (order matters: prefer README.md)
+README_CANDIDATES = ["README.md", "README", "readme.md", "readme", "Readme.md"]
+
+# Per-repo cache for gitweb config (git_parse_project_config result)
+_config_cache: dict[str, tuple[str, dict[str, str | list[str]]]] = {}
+
+
+def clear_config_cache() -> None:
+    _config_cache.clear()
+
+
+def hash_set_multi(d: dict[str, str | list[str]], key: str, value: str) -> None:
+    """Store multi-value: first value direct, rest in list. Port of hash_set_multi."""
+    existing = d.get(key)
+    if existing is None:
+        d[key] = value
+    elif isinstance(existing, list):
+        existing.append(value)
+    else:
+        d[key] = [existing, value]
+
+
+def config_to_bool(val: str | None) -> bool:
+    """Config value to bool: true/yes/1. Port of config_to_bool."""
+    if val is None:
+        return True
+    val = (val or "").strip()
+    if re.match(r"^\d+$", val):
+        return int(val) != 0
+    return val.lower() in ("true", "yes")
+
+
+def config_to_int(val: str | None) -> int | str:
+    """Config value to int; k/m/g suffix. Port of config_to_int."""
+    if val is None:
+        return 0
+    val = (val or "").strip()
+    m = re.match(r"^([0-9]*)([kmg])$", val, re.I)
+    if m:
+        num, unit = m.group(1), m.group(2).lower()
+        mult = {"k": 1024, "m": 1048576, "g": 1073741824}.get(unit, 1)
+        return int(num or 0) * mult
+    return val
+
+
+def repo_git_signature(repo: Repository) -> pygit2.Signature | None:
+    by_name: dict[str, str] = {}
+    for entry in repo.config:
+        if entry.level not in _REPO_CONFIG_LEVELS:
+            continue
+        by_name[entry.name] = entry.value or ""
+    name = by_name.get("user.name", "").strip()
+    email = by_name.get("user.email", "").strip()
+    if name and email:
+        return pygit2.Signature(name, email)
+    return None
+
+
+def git_get_type(repo: Repository, ref: str) -> str | None:
+    """Object type: commit, tree, blob, tag. Port of git_get_type (pygit2 obj.type)."""
+    try:
+        obj = repo.revparse_single(ref)
+        return obj.type_str if obj else None
+    except (KeyError, pygit2.GitError, OSError):
+        return None
+
+
+def git_parse_project_config(repo: Repository, section_regexp: str | None = None) -> dict[str, str | list[str]]:
+    """All config key/values; optionally filter by section. Port of git_parse_project_config."""
+    try:
+        cfg = repo.config
+        result: dict[str, str | list[str]] = {}
+        for entry in cfg:
+            key = entry.name
+            if section_regexp and not re.search(rf"^(?:{section_regexp})\.", key):
+                continue
+            value = entry.value
+            if value is None:
+                continue
+            hash_set_multi(result, key, value)
+        return result
+    except (pygit2.GitError, OSError):
+        return {}
+
+
+def git_get_project_config(
+    repo: Repository,
+    key: str,
+    config_type: str | None = None,
+    *,
+    git_dir: str | None = None,
+) -> int | str | list[str] | bool | None:
+    """Single config value; gitweb.* section. Port of git_get_project_config."""
+    key = key.lower().replace("_", "")
+    if key.startswith("gitweb."):
+        key = key[7:]
+    if re.search(r"\W", key):
+        return None
+    full_key = f"gitweb.{key}"
+    cache_dir = git_dir if git_dir is not None else repo.path.rstrip("/\\")
+    cache_key = cache_dir
+    config_path = os.path.join(cache_dir, "config")
+    if cache_key not in _config_cache or _config_cache[cache_key][0] != config_path:
+        cfg = git_parse_project_config(repo, "gitweb")
+        _config_cache[cache_key] = (config_path, cfg)
+    _, cfg = _config_cache[cache_key]
+    raw = cfg.get(full_key)
+    if raw is None:
+        return None
+    if config_type == "bool" or config_type == "--bool":
+        return config_to_bool(raw[0] if isinstance(raw, list) else raw)
+    if config_type == "int" or config_type == "--int":
+        return config_to_int(raw[0] if isinstance(raw, list) else raw)
+    if isinstance(raw, list):
+        return raw[0] if len(raw) == 1 else raw
+    return raw
+
+
+def get_tree_at_ref_path(repo: Repository, ref: str | None, path: str | None) -> tuple[Tree, str] | None:
+    """
+    Resolve the tree at ref (commit or tree) and optional path.
+    Returns (tree, ref_oid) for listing, or None if not found.
+    ref_oid is the resolved OID to use in URLs (same revision).
+    """
+    try:
+        base_ref = ref or (str(repo.head.target) if repo.head else None)
+        if not base_ref:
+            return None
+        obj = repo.revparse_single(base_ref)
+        ref_oid = str(obj.id)
+        base_tree = obj.peel(Tree)
+        if not path or not path.strip("/"):
+            return (base_tree, ref_oid)
+        path_clean = path.strip("/")
+        entry = base_tree / path_clean
+        if not entry or entry.type_str != "tree":
+            return None
+        return (repo[entry.id].peel(Tree), ref_oid)
+    except (KeyError, pygit2.GitError, OSError):
+        return None
+
+
+def get_blob_at_ref_path(repo: Repository, ref: str | None, path: str | None) -> tuple[Blob, str] | None:
+    """
+    Resolve the blob at ref (commit or tree) and path.
+    Returns (blob, ref_oid) or None if not found or not a blob.
+    """
+    if not path or not path.strip("/"):
+        return None
+    try:
+        base_ref = ref or (str(repo.head.target) if repo.head else None)
+        if not base_ref:
+            return None
+        obj = repo.revparse_single(base_ref)
+        ref_oid = str(obj.id)
+        base_tree = obj.peel(Tree)
+        path_clean = path.strip("/")
+        entry = base_tree / path_clean
+        if not entry or entry.type_str != "blob":
+            return None
+        return (repo[entry.id].peel(Blob), ref_oid)
+    except (KeyError, pygit2.GitError, OSError):
+        return None
+
+
+def git_get_file_or_project_config(repo: Repository, name: str, *, git_dir: str) -> str | None:
+    """Value from $GIT_DIR/name file or gitweb.name config. Port of git_get_file_or_project_config."""
+    path = os.path.join(git_dir, name)
+    if os.path.isfile(path):
+        try:
+            with open(path) as f:
+                return f.read().strip()
+        except OSError:
+            pass
+    val = git_get_project_config(repo, name, git_dir=git_dir)
+    return val[0] if isinstance(val, list) else (val if isinstance(val, str) else None)
+
+
+def git_get_project_description(repo: Repository, *, git_dir: str) -> str | None:
+    """Content of description file or config. Port of git_get_project_description."""
+    return git_get_file_or_project_config(repo, "description", git_dir=git_dir)
+
+
+def git_get_references(repo: Repository, ref_prefix: str = "refs/heads") -> list[tuple[str, str]]:
+    """List (ref_name, oid) for prefix. Port of git_get_references (pygit2 references)."""
+    try:
+        prefix = ref_prefix + "/"
+        return [
+            (ref_name, str(repo.references[ref_name].resolve().target))
+            for ref_name in repo.references
+            if ref_name.startswith(prefix)
+        ]
+    except (pygit2.GitError, OSError):
+        return []
+
+
+def git_get_heads_list(repo: Repository) -> list[tuple[str, str, str]]:
+    """List (name, ref, oid) for heads. Port of git_get_heads_list."""
+    refs = git_get_references(repo, "refs/heads")
+    return [(ref.replace("refs/heads/", ""), ref, oid) for ref, oid in refs]
+
+
+def _tag_timestamp(repo: Repository, oid: str) -> int:
+    """Return tagger time for an annotated tag, or committer time for a lightweight tag (commit)."""
+    try:
+        obj = repo.revparse_single(oid)
+        if isinstance(obj, Tag) and obj.tagger:
+            return obj.tagger.time
+        if isinstance(obj, Commit):
+            return obj.committer.time
+    except (KeyError, pygit2.GitError):
+        pass
+    return 0
+
+
+def git_get_tags_list(repo: Repository) -> list[tuple[str, str, str]]:
+    """List (name, ref, oid) for tags. Sorted by tag creation time descending (newest first)."""
+    try:
+        result: list[tuple[str, str, str, int]] = []
+        for ref in repo.references.iterator(pygit2.enums.ReferenceFilter.TAGS):
+            oid = str(ref.resolve().target)
+            name = ref.name.replace("refs/tags/", "")
+            ts = _tag_timestamp(repo, oid)
+            result.append((name, ref.name, oid, ts))
+        result.sort(key=lambda x: (x[3], x[0]), reverse=True)
+        return [(name, ref_name, oid) for name, ref_name, oid, _ in result]
+    except (pygit2.GitError, OSError):
+        return []
+
+
+def git_get_remotes_info(repo: Repository) -> list[dict[str, Any]]:
+    """Remote info: name, url, push_url. Uses pygit2 Remote.url and Remote.push_url."""
+    try:
+        result: list[dict[str, Any]] = []
+        for name in repo.remotes.names():
+            if not name:
+                continue
+            remote = repo.remotes[name]
+            result.append({
+                "name": name,
+                "url": remote.url or "",
+                "push_url": remote.push_url or remote.url or "",
+            })
+        return result
+    except (pygit2.GitError, OSError):
+        return []
+
+
+def parse_commit(repo: Repository, oid: str) -> dict[str, Any]:
+    """Commit metadata dict. Port of parse_commit (pygit2 commit)."""
+    try:
+        obj = repo.revparse_single(oid)
+        if not isinstance(obj, Commit):
+            return {}
+        commit = obj
+        return {
+            "parent": [str(p) for p in commit.parent_ids],
+            "tree": str(commit.tree_id),
+            "author": commit.author.name,
+            "author_email": commit.author.email,
+            "author_epoch": commit.author.time,
+            "author_tz": commit.author.offset,
+            "committer": commit.committer.name,
+            "committer_email": commit.committer.email,
+            "committer_epoch": commit.committer.time,
+            "committer_tz": commit.committer.offset,
+            "subject": commit.message.split("\n")[0] if commit.message else "",
+            "body": commit.message or "",
+        }
+    except (KeyError, pygit2.GitError, OSError):
+        return {}
+
+
+def parse_tag(repo: Repository, oid: str) -> dict[str, Any]:
+    """Tag metadata. Port of parse_tag (pygit2 tag)."""
+    try:
+        obj = repo.revparse_single(oid)
+        if not isinstance(obj, Tag):
+            return {}
+        tag = obj
+        return {
+            "object": str(tag.target),
+            "type": tag.type_str,
+            "tagger": tag.tagger.name if tag.tagger else "",
+            "tagger_email": tag.tagger.email if tag.tagger else "",
+            "tagger_epoch": tag.tagger.time if tag.tagger else 0,
+            "tagger_tz": tag.tagger.offset if tag.tagger else 0,
+            "message": tag.message or "",
+        }
+    except (KeyError, pygit2.GitError, OSError):
+        return {}
+
+
+def get_commit_history(
+    repo: Repository,
+    ref: str | None = None,
+    path: str | None = None,
+    max_count: int = 100,
+    skip: int = 0,
+) -> list[dict[str, Any]]:
+    """
+    Get commit history, optionally filtered by path.
+    Returns list of commit dicts with oid and parsed commit data.
+    skip: number of matching commits to skip (for pagination).
+    """
+    try:
+        if ref:
+            try:
+                start_oid: pygit2.Oid | None = repo.revparse_single(ref).peel(Commit).id
+            except (KeyError, pygit2.GitError, ValueError):
+                start_oid = None
+        else:
+            try:
+                start_oid = repo.head.peel(Commit).id if repo.head else None
+            except (KeyError, pygit2.GitError, ValueError):
+                start_oid = None
+        if not start_oid:
+            return []
+
+        commits: list[dict[str, Any]] = []
+        skipped = 0
+        walker = repo.walk(
+            start_oid,
+            pygit2.enums.SortMode.TIME | pygit2.enums.SortMode.TOPOLOGICAL,
+        )
+
+        if path:
+            path_clean = path.strip("/")
+            path_prefix = path_clean + "/"
+
+            def touched_path(diff: pygit2.Diff) -> bool:
+                for delta in diff.deltas:
+                    old_p, new_p = delta.old_file.path, delta.new_file.path
+                    if old_p == path_clean or new_p == path_clean:
+                        return True
+                    if old_p.startswith(path_prefix) or new_p.startswith(path_prefix):
+                        return True
+                return False
+
+            for commit in walker:
+                if len(commits) >= max_count:
+                    break
+                try:
+                    if commit.parents:
+                        diff = repo.diff(commit.parents[0], commit)
+                        if not touched_path(diff):
+                            continue
+                    elif path_clean:
+                        try:
+                            commit.tree / path_clean
+                        except KeyError:
+                            continue
+                    if skipped < skip:
+                        skipped += 1
+                        continue
+                    commit_data = parse_commit(repo, str(commit.id))
+                    commit_data["oid"] = str(commit.id)
+                    commits.append(commit_data)
+                except (KeyError, AttributeError, pygit2.GitError):
+                    pass
+        else:
+            for commit in walker:
+                if skipped < skip:
+                    skipped += 1
+                    continue
+                if len(commits) >= max_count:
+                    break
+                commit_data = parse_commit(repo, str(commit.id))
+                commit_data["oid"] = str(commit.id)
+                commits.append(commit_data)
+
+        return commits
+    except (KeyError, pygit2.GitError, OSError):
+        return []
+
+
+def get_commits_in_range(repo: Repository, tip: str, base: str | None) -> list[str]:
+    """Return list of commit OIDs from tip back to (but not including) base. Newest first."""
+    try:
+        tip_commit = repo.revparse_single(tip).peel(Commit)
+        walker = repo.walk(
+            tip_commit.id,
+            pygit2.enums.SortMode.TIME | pygit2.enums.SortMode.TOPOLOGICAL,
+        )
+        if base:
+            with suppress(KeyError, pygit2.GitError, ValueError):
+                walker.hide(repo.revparse_single(base).peel(Commit).id)
+        return [str(c.id) for c in walker]
+    except (KeyError, pygit2.GitError, OSError, ValueError):
+        return []
+
+
+def get_blob_unified_diff(
+    repo: Repository,
+    ref_old: str,
+    path_old: str,
+    ref_new: str,
+    path_new: str,
+) -> str | None:
+    """
+    Return unified diff between blob at ref_old:path_old and ref_new:path_new using pygit2.
+    Returns None if either blob is not found; otherwise returns the diff string (possibly empty).
+    """
+    result_old = get_blob_at_ref_path(repo, ref_old, path_old)
+    result_new = get_blob_at_ref_path(repo, ref_new, path_new)
+    if not result_old or not result_new:
+        return None
+    old_blob, _ = result_old
+    new_blob, _ = result_new
+    patch = old_blob.diff(new_blob, old_as_path=path_old, new_as_path=path_new)
+    return patch.text if patch.text else ""
+
+
+def get_readme_at_ref_path(repo: Repository, ref: str | None, dir_path: str | None) -> tuple[str, str] | None:
+    """
+    If a README exists at ref in the given tree (dir_path), return (filename, utf8_content).
+    Otherwise None. dir_path is the tree path (e.g. '' for root, 'docs' for docs/).
+    """
+    if not ref:
+        return None
+    for name in README_CANDIDATES:
+        path = f"{dir_path.strip('/')}/{name}".strip("/") if dir_path else name
+        result = get_blob_at_ref_path(repo, ref, path)
+        if result:
+            blob, _ = result
+            text = to_utf8(blob.data) or ""
+            return (name, text)
+    return None
+
+
+def get_commit_unified_diff(repo: Repository, h: str) -> tuple[str, str]:
+    """
+    Return (unified_diff_text, oid_short) for commit h.
+    Raises KeyError, pygit2.GitError, OSError on error (caller should validate ref).
+    """
+    commit = repo.revparse_single(h).peel(Commit)
+    diff = repo.diff(commit.parents[0], commit) if commit.parents else commit.tree.diff_to_tree(swap=True)
+    body = diff.patch or ""
+    oid_short = commit.short_id[:7] if len(commit.short_id) >= 7 else commit.short_id
+    return body, oid_short
diff --git a/pygittools/src/pygittools/git_helpers_test.py b/pygittools/src/pygittools/git_helpers_test.py
new file mode 100644
index 0000000..865fec1
--- /dev/null
+++ b/pygittools/src/pygittools/git_helpers_test.py
@@ -0,0 +1,251 @@
+from __future__ import annotations
+
+import subprocess
+from collections.abc import Generator
+from pathlib import Path
+
+import pytest
+from pygit2 import Repository
+
+from pygittools.git_helpers import (
+    clear_config_cache,
+    config_to_bool,
+    config_to_int,
+    get_blob_at_ref_path,
+    get_blob_unified_diff,
+    get_commit_history,
+    get_commit_unified_diff,
+    get_commits_in_range,
+    get_readme_at_ref_path,
+    get_tree_at_ref_path,
+    git_get_file_or_project_config,
+    git_get_heads_list,
+    git_get_project_config,
+    git_get_project_description,
+    git_get_references,
+    git_get_remotes_info,
+    git_get_tags_list,
+    git_get_type,
+    git_parse_project_config,
+    hash_set_multi,
+    parse_commit,
+    parse_tag,
+)
+
+
+def _run_git(repo_dir: Path, *args: str) -> str:
+    completed: subprocess.CompletedProcess[str] = subprocess.run(
+        ["git", *args],
+        cwd=repo_dir,
+        capture_output=True,
+        text=True,
+        check=True,
+    )
+    return completed.stdout.strip()
+
+
+class TestGitHelpers:
+    class TestPure:
+        def test_hash_set_multi_promotes_to_list(self) -> None:
+            data: dict[str, str | list[str]] = {}
+            hash_set_multi(data, "k", "v1")
+            hash_set_multi(data, "k", "v2")
+            assert data["k"] == ["v1", "v2"]
+
+        @pytest.mark.parametrize(
+            ("value", "expected"),
+            [("true", True), ("0", False), (None, True)],
+        )
+        def test_config_to_bool(self, value: str | None, expected: bool) -> None:
+            assert config_to_bool(value) is expected
+
+        @pytest.mark.parametrize(
+            ("value", "expected"),
+            [("2k", 2048), ("3M", 3145728), ("123", "123"), (None, 0)],
+        )
+        def test_config_to_int(self, value: str | None, expected: int | str) -> None:
+            assert config_to_int(value) == expected
+
+    class TestRepoReadonly:
+        @pytest.fixture(scope="class")
+        def repo_ctx(self, tmp_path_factory: pytest.TempPathFactory) -> Generator[dict[str, object], None, None]:
+            project_root: Path = tmp_path_factory.mktemp("git-helpers")
+            repo_dir: Path = project_root / "sample"
+            repo_dir.mkdir()
+
+            _run_git(repo_dir, "init", "-b", "main")
+            _run_git(repo_dir, "config", "user.name", "Alice")
+            _run_git(repo_dir, "config", "user.email", "alice@example.com")
+            _run_git(repo_dir, "remote", "add", "origin", "https://example.com/repo.git")
+            _run_git(repo_dir, "remote", "set-url", "--push", "origin", "ssh://example.com/repo.git")
+            _run_git(repo_dir, "config", "gitweb.owner", "alice")
+            _run_git(repo_dir, "config", "--add", "gitweb.category", "infra")
+            _run_git(repo_dir, "config", "--add", "gitweb.category", "tools")
+
+            (repo_dir / "README.md").write_text("Root README\n", encoding="utf-8")
+            (repo_dir / "docs").mkdir()
+            (repo_dir / "docs" / "README").write_text("Docs README\n", encoding="utf-8")
+            (repo_dir / "docs" / "guide.txt").write_text("hello\n", encoding="utf-8")
+            (repo_dir / "src").mkdir()
+            (repo_dir / "src" / "app.py").write_text("print('v1')\n", encoding="utf-8")
+            _run_git(repo_dir, "add", ".")
+            _run_git(repo_dir, "commit", "-m", "initial commit")
+
+            first_commit: str = _run_git(repo_dir, "rev-parse", "HEAD")
+            (repo_dir / "docs" / "guide.txt").write_text("hello\nworld\n", encoding="utf-8")
+            (repo_dir / "src" / "app.py").write_text("print('v2')\n", encoding="utf-8")
+            _run_git(repo_dir, "add", ".")
+            _run_git(repo_dir, "commit", "-m", "update docs and app")
+            second_commit: str = _run_git(repo_dir, "rev-parse", "HEAD")
+
+            _run_git(
+                repo_dir,
+                "tag",
+                "-a",
+                "v1.0",
+                "-m",
+                "release v1.0",
+                second_commit,
+            )
+            _run_git(repo_dir, "tag", "lightweight", first_commit)
+            _run_git(repo_dir, "branch", "feature/readme", second_commit)
+
+            git_dir: Path = repo_dir / ".git"
+            (git_dir / "description").write_text("Repo description\n", encoding="utf-8")
+
+            clear_config_cache()
+            repo = Repository(str(git_dir))
+            yield {
+                "repo": repo,
+                "git_dir": str(git_dir),
+                "first_commit": first_commit,
+                "second_commit": second_commit,
+            }
+            clear_config_cache()
+
+        def test_git_get_type(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            assert isinstance(repo, Repository)
+            assert git_get_type(repo, "HEAD") == "commit"
+            assert git_get_type(repo, "HEAD^{tree}") == "tree"
+
+        def test_git_parse_and_get_project_config(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            git_dir = repo_ctx["git_dir"]
+            assert isinstance(repo, Repository)
+            assert isinstance(git_dir, str)
+            cfg: dict[str, object] = git_parse_project_config(repo, "gitweb")
+            assert cfg["gitweb.owner"] == "alice"
+            assert cfg["gitweb.category"] == ["infra", "tools"]
+            assert git_get_project_config(repo, "owner", git_dir=git_dir) == "alice"
+            assert git_get_project_config(repo, "category", git_dir=git_dir) == ["infra", "tools"]
+
+        def test_git_get_file_or_project_config_prefers_file(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            git_dir = repo_ctx["git_dir"]
+            assert isinstance(repo, Repository)
+            assert isinstance(git_dir, str)
+            assert git_get_file_or_project_config(repo, "description", git_dir=git_dir) == "Repo description"
+            assert git_get_project_description(repo, git_dir=git_dir) == "Repo description"
+
+        def test_references_heads_tags_and_remotes(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            assert isinstance(repo, Repository)
+            heads: list[tuple[str, str, str]] = git_get_heads_list(repo)
+            head_names: set[str] = {name for name, _ref, _oid in heads}
+            assert {"main", "feature/readme"} <= head_names
+
+            refs: list[tuple[str, str]] = git_get_references(repo)
+            assert any(name == "refs/heads/main" for name, _oid in refs)
+
+            tags: list[tuple[str, str, str]] = git_get_tags_list(repo)
+            tag_names: set[str] = {name for name, _ref, _oid in tags}
+            assert {"v1.0", "lightweight"} <= tag_names
+
+            remotes: list[dict[str, object]] = git_get_remotes_info(repo)
+            assert remotes == [
+                {
+                    "name": "origin",
+                    "url": "https://example.com/repo.git",
+                    "push_url": "ssh://example.com/repo.git",
+                }
+            ]
+
+        def test_parse_commit_and_parse_tag(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            second_commit = repo_ctx["second_commit"]
+            assert isinstance(repo, Repository)
+            assert isinstance(second_commit, str)
+            commit_data: dict[str, object] = parse_commit(repo, second_commit)
+            assert commit_data["subject"] == "update docs and app"
+            assert commit_data["author"] == "Alice"
+            assert isinstance(commit_data["parent"], list)
+
+            tag_oid: str = str(repo.references["refs/tags/v1.0"].target)
+            tag_data: dict[str, object] = parse_tag(repo, tag_oid)
+            assert tag_data["type"] == "tag"
+            assert tag_data["message"] == "release v1.0\n"
+
+        def test_tree_blob_and_readme_resolution(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            second_commit = repo_ctx["second_commit"]
+            assert isinstance(repo, Repository)
+            assert isinstance(second_commit, str)
+            tree_result = get_tree_at_ref_path(repo, "HEAD", "docs")
+            assert tree_result is not None
+            tree, ref_oid = tree_result
+            assert ref_oid == second_commit
+            assert tree["guide.txt"].type_str == "blob"
+
+            blob_result = get_blob_at_ref_path(repo, "HEAD", "docs/guide.txt")
+            assert blob_result is not None
+            blob, _resolved_ref = blob_result
+            assert blob.data.decode("utf-8") == "hello\nworld\n"
+
+            readme_root = get_readme_at_ref_path(repo, "HEAD", "")
+            assert readme_root == ("README.md", "Root README\n")
+            readme_docs = get_readme_at_ref_path(repo, "HEAD", "docs")
+            assert readme_docs == ("README", "Docs README\n")
+
+        def test_commit_history_and_ranges(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            first_commit = repo_ctx["first_commit"]
+            second_commit = repo_ctx["second_commit"]
+            assert isinstance(repo, Repository)
+            assert isinstance(first_commit, str)
+            assert isinstance(second_commit, str)
+            all_history: list[dict[str, object]] = get_commit_history(repo, max_count=10)
+            assert [entry["oid"] for entry in all_history] == [second_commit, first_commit]
+
+            path_history: list[dict[str, object]] = get_commit_history(
+                repo,
+                path="docs/guide.txt",
+                max_count=10,
+            )
+            assert [entry["oid"] for entry in path_history] == [second_commit, first_commit]
+
+            in_range: list[str] = get_commits_in_range(repo, "HEAD", first_commit)
+            assert in_range == [second_commit]
+
+        def test_blob_and_commit_unified_diff(self, repo_ctx: dict[str, object]) -> None:
+            repo = repo_ctx["repo"]
+            first_commit = repo_ctx["first_commit"]
+            second_commit = repo_ctx["second_commit"]
+            assert isinstance(repo, Repository)
+            assert isinstance(first_commit, str)
+            assert isinstance(second_commit, str)
+            blob_diff = get_blob_unified_diff(
+                repo,
+                first_commit,
+                "src/app.py",
+                second_commit,
+                "src/app.py",
+            )
+            assert blob_diff is not None
+            assert "-print('v1')" in blob_diff
+            assert "+print('v2')" in blob_diff
+
+            commit_diff, oid_short = get_commit_unified_diff(repo, "HEAD")
+            assert "docs/guide.txt" in commit_diff
+            assert "src/app.py" in commit_diff
+            assert oid_short == second_commit[:7]
diff --git a/pygitweb/src/pygitweb/formatting.py b/pygitweb/src/pygitweb/formatting.py
index bf72334..f09f9c9 100644
--- a/pygitweb/src/pygitweb/formatting.py
+++ b/pygitweb/src/pygitweb/formatting.py
@@ -10,8 +10,7 @@ import html
 import re
 from urllib.parse import quote, quote_plus
 
-# Fallback encoding when bytes are not valid UTF-8 (gitweb: $fallback_encoding)
-FALLBACK_ENCODING = "latin1"
+from pygittools.formatting import FALLBACK_ENCODING, to_utf8
 
 # Control character escape codes (CEC). Port of quot_cec.
 _CEC_MAP = {
@@ -26,17 +25,21 @@ _CEC_MAP = {
     "\0": r"\0",
 }
 
-
-def to_utf8(s: str | bytes | None) -> str | None:
-    """Decode to UTF-8 string; use fallback encoding if not valid UTF-8. Port of to_utf8."""
-    if s is None:
-        return None
-    if isinstance(s, str):
-        return s
-    try:
-        return s.decode("utf-8")
-    except UnicodeDecodeError:
-        return s.decode(FALLBACK_ENCODING, errors="replace")
+__all__ = [
+    "FALLBACK_ENCODING",
+    "age_class",
+    "age_string",
+    "esc_param",
+    "esc_path",
+    "esc_path_info",
+    "esc_url",
+    "quot_cec",
+    "quot_upr",
+    "sanitize",
+    "to_utf8",
+    "unquote",
+    "untabify",
+]
 
 
 def esc_param(s: str | None) -> str | None:
diff --git a/pygitweb/src/pygitweb/formatting_test.py b/pygitweb/src/pygitweb/formatting_test.py
index b36303b..ba43f11 100644
--- a/pygitweb/src/pygitweb/formatting_test.py
+++ b/pygitweb/src/pygitweb/formatting_test.py
@@ -14,12 +14,14 @@ def test_to_utf8_uses_fallback_encoding_when_utf8_fails() -> None:
 
 
 def test_to_utf8_fallback_decode_uses_replace_for_invalid_bytes() -> None:
-    original: str = formatting.FALLBACK_ENCODING
-    formatting.FALLBACK_ENCODING = "ascii"
+    import pygittools.formatting as tools_formatting
+
+    original: str = tools_formatting.FALLBACK_ENCODING
+    tools_formatting.FALLBACK_ENCODING = "ascii"
     try:
         assert formatting.to_utf8(b"\xffabc") == "\ufffdabc"
     finally:
-        formatting.FALLBACK_ENCODING = original
+        tools_formatting.FALLBACK_ENCODING = original
 
 
 def test_esc_param_encodes_space_and_slash() -> None:
diff --git a/pygitweb/src/pygitweb/git_helpers.py b/pygitweb/src/pygitweb/git_helpers.py
index e66cd01..9488222 100644
--- a/pygitweb/src/pygitweb/git_helpers.py
+++ b/pygitweb/src/pygitweb/git_helpers.py
@@ -1,29 +1,28 @@
 """
-Git helpers via pygit2: open repo, rev_parse, config, refs, ls_tree, cat_file, etc.
-Ported from gitweb/gitweb.perl (git_cmd, git_get_type, git_parse_project_config, config_to_bool,
-config_to_int, git_get_project_config, git_get_file_or_project_config, git_get_project_description,
-git_get_references, git_get_heads_list, git_get_tags_list, git_get_remotes_info, parse_commit,
-parse_tag, etc.).
+Project-scoped git helpers for the web app: open repos under PROJECTROOT and
+adapt pygittools.git_helpers to project names. Auth/signature helpers that depend
+on PermissionPrincipal stay here.
 """
 
 from __future__ import annotations
 
 import os
-import re
-from contextlib import suppress
 from typing import Any
 
 import pygit2
-
+from pygittools.git_helpers import (
+    clear_config_cache,
+    config_to_bool,
+    config_to_int,
+    hash_set_multi,
+    repo_git_signature,
+)
+
+from pygittools import git_helpers as _gh
 from pygitweb.config import settings
-from pygitweb.formatting import to_utf8
 from pygitweb.permissions import PermissionPrincipal
 
 _DEFAULT_MR_OPENER = pygit2.Signature("PyGitWeb", "noreply@pygitweb.local")
-_REPO_CONFIG_LEVELS = frozenset({5, 6})  # git_config_level_t local, worktree
-
-# Common README filenames to look for (order matters: prefer README.md)
-README_CANDIDATES = ["README.md", "README", "readme.md", "readme", "Readme.md"]
 
 
 def _repo_path(project: str) -> str:
@@ -32,8 +31,7 @@ def _repo_path(project: str) -> str:
 
 def open_repo(project: str) -> pygit2.Repository:
     """Open pygit2.Repository for project. Replaces git_cmd + --git-dir."""
-    path = _repo_path(project)
-    return pygit2.Repository(path)
+    return pygit2.Repository(_repo_path(project))
 
 
 def signature_from_principal_email(principal: PermissionPrincipal | None) -> pygit2.Signature | None:
@@ -46,19 +44,6 @@ def signature_from_principal_email(principal: PermissionPrincipal | None) -> pyg
     return pygit2.Signature(name, email)
 
 
-def repo_git_signature(repo: pygit2.Repository) -> pygit2.Signature | None:
-    by_name: dict[str, str] = {}
-    for entry in repo.config:
-        if entry.level not in _REPO_CONFIG_LEVELS:
-            continue
-        by_name[entry.name] = entry.value or ""
-    name = by_name.get("user.name", "").strip()
-    email = by_name.get("user.email", "").strip()
-    if name and email:
-        return pygit2.Signature(name, email)
-    return None
-
-
 def signature_from_user_credentials(principal: PermissionPrincipal | None) -> pygit2.Signature | None:
     if principal is None:
         return None
@@ -92,281 +77,102 @@ def resolve_mr_opener(
 
 
 def git_get_type(project: str, ref: str) -> str | None:
-    """Object type: commit, tree, blob, tag. Port of git_get_type (pygit2 obj.type)."""
     try:
-        repo = open_repo(project)
-        obj = repo.revparse_single(ref)
-        return obj.type_str if obj else None
-    except (KeyError, pygit2.GitError, OSError):
+        return _gh.git_get_type(open_repo(project), ref)
+    except (pygit2.GitError, OSError):
         return None
 
 
-def hash_set_multi(d: dict[str, str | list[str]], key: str, value: str) -> None:
-    """Store multi-value: first value direct, rest in list. Port of hash_set_multi."""
-    existing = d.get(key)
-    if existing is None:
-        d[key] = value
-    elif isinstance(existing, list):
-        existing.append(value)
-    else:
-        d[key] = [existing, value]
-
-
 def git_parse_project_config(project: str, section_regexp: str | None = None) -> dict[str, str | list[str]]:
-    """All config key/values; optionally filter by section. Port of git_parse_project_config."""
     try:
-        repo = open_repo(project)
-        cfg = repo.config
-        result: dict[str, str | list[str]] = {}
-        for entry in cfg:
-            key = entry.name
-            if section_regexp and not re.search(rf"^(?:{section_regexp})\.", key):
-                continue
-            value = entry.value
-            if value is None:
-                continue
-            hash_set_multi(result, key, value)
-        return result
+        return _gh.git_parse_project_config(open_repo(project), section_regexp)
     except (pygit2.GitError, OSError):
         return {}
 
 
-def config_to_bool(val: str | None) -> bool:
-    """Config value to bool: true/yes/1. Port of config_to_bool."""
-    if val is None:
-        return True
-    val = (val or "").strip()
-    if re.match(r"^\d+$", val):
-        return int(val) != 0
-    return val.lower() in ("true", "yes")
-
-
-def config_to_int(val: str | None) -> int | str:
-    """Config value to int; k/m/g suffix. Port of config_to_int."""
-    if val is None:
-        return 0
-    val = (val or "").strip()
-    m = re.match(r"^([0-9]*)([kmg])$", val, re.I)
-    if m:
-        num, unit = m.group(1), m.group(2).lower()
-        mult = {"k": 1024, "m": 1048576, "g": 1073741824}.get(unit, 1)
-        return int(num or 0) * mult
-    return val
-
-
-# Per-repo cache for gitweb config (git_parse_project_config result)
-_config_cache: dict[str, tuple[str, dict[str, str | list[str]]]] = {}
-
-
 def git_get_project_config(
     project: str,
     key: str,
     config_type: str | None = None,
 ) -> int | str | list[str] | bool | None:
-    """Single config value; gitweb.* section. Port of git_get_project_config."""
-    key = key.lower().replace("_", "")
-    if key.startswith("gitweb."):
-        key = key[7:]
-    if re.search(r"\W", key):
-        return None
-    full_key = f"gitweb.{key}"
-    git_dir = _repo_path(project)
-    cache_key = git_dir
-    if cache_key not in _config_cache or _config_cache[cache_key][0] != os.path.join(git_dir, "config"):
-        cfg = git_parse_project_config(project, "gitweb")
-        _config_cache[cache_key] = (os.path.join(git_dir, "config"), cfg)
-    _, cfg = _config_cache[cache_key]
-    raw = cfg.get(full_key)
-    if raw is None:
+    try:
+        return _gh.git_get_project_config(
+            open_repo(project),
+            key,
+            config_type,
+            git_dir=_repo_path(project),
+        )
+    except (pygit2.GitError, OSError):
         return None
-    if config_type == "bool" or config_type == "--bool":
-        return config_to_bool(raw[0] if isinstance(raw, list) else raw)
-    if config_type == "int" or config_type == "--int":
-        return config_to_int(raw[0] if isinstance(raw, list) else raw)
-    if isinstance(raw, list):
-        return raw[0] if len(raw) == 1 else raw
-    return raw
 
 
 def get_tree_at_ref_path(project: str, ref: str | None, path: str | None) -> tuple[pygit2.Tree, str] | None:
-    """
-    Resolve the tree at ref (commit or tree) and optional path.
-    Returns (tree, ref_oid) for listing, or None if not found.
-    ref_oid is the resolved OID to use in URLs (same revision).
-    """
     try:
-        repo = open_repo(project)
-        base_ref = ref or (str(repo.head.target) if repo.head else None)
-        if not base_ref:
-            return None
-        obj = repo.revparse_single(base_ref)
-        ref_oid = str(obj.id)
-        base_tree = obj.peel(pygit2.Tree)
-        if not path or not path.strip("/"):
-            return (base_tree, ref_oid)
-        path_clean = path.strip("/")
-        entry = base_tree / path_clean
-        if not entry or entry.type_str != "tree":
-            return None
-        return (repo[entry.id].peel(pygit2.Tree), ref_oid)
-    except (KeyError, pygit2.GitError, OSError):
+        return _gh.get_tree_at_ref_path(open_repo(project), ref, path)
+    except (pygit2.GitError, OSError):
         return None
 
 
 def get_blob_at_ref_path(project: str, ref: str | None, path: str | None) -> tuple[pygit2.Blob, str] | None:
-    """
-    Resolve the blob at ref (commit or tree) and path.
-    Returns (blob, ref_oid) or None if not found or not a blob.
-    """
-    if not path or not path.strip("/"):
-        return None
     try:
-        repo = open_repo(project)
-        base_ref = ref or (str(repo.head.target) if repo.head else None)
-        if not base_ref:
-            return None
-        obj = repo.revparse_single(base_ref)
-        ref_oid = str(obj.id)
-        base_tree = obj.peel(pygit2.Tree)
-        path_clean = path.strip("/")
-        entry = base_tree / path_clean
-        if not entry or entry.type_str != "blob":
-            return None
-        return (repo[entry.id].peel(pygit2.Blob), ref_oid)
-    except (KeyError, pygit2.GitError, OSError):
+        return _gh.get_blob_at_ref_path(open_repo(project), ref, path)
+    except (pygit2.GitError, OSError):
         return None
 
 
 def git_get_file_or_project_config(project: str, name: str) -> str | None:
-    """Value from $GIT_DIR/name file or gitweb.name config. Port of git_get_file_or_project_config."""
-    path = os.path.join(_repo_path(project), name)
-    if os.path.isfile(path):
-        try:
-            with open(path) as f:
-                return f.read().strip()
-        except OSError:
-            pass
-    val = git_get_project_config(project, name)
-    return val[0] if isinstance(val, list) else (val if isinstance(val, str) else None)
+    try:
+        return _gh.git_get_file_or_project_config(open_repo(project), name, git_dir=_repo_path(project))
+    except (pygit2.GitError, OSError):
+        return None
 
 
 def git_get_project_description(project: str) -> str | None:
-    """Content of description file or config. Port of git_get_project_description."""
-    return git_get_file_or_project_config(project, "description")
+    try:
+        return _gh.git_get_project_description(open_repo(project), git_dir=_repo_path(project))
+    except (pygit2.GitError, OSError):
+        return None
 
 
 def git_get_references(project: str, ref_prefix: str = "refs/heads") -> list[tuple[str, str]]:
-    """List (ref_name, oid) for prefix. Port of git_get_references (pygit2 references)."""
     try:
-        repo = open_repo(project)
-        prefix = ref_prefix + "/"
-        return [
-            (ref_name, str(repo.references[ref_name].resolve().target))
-            for ref_name in repo.references
-            if ref_name.startswith(prefix)
-        ]
+        return _gh.git_get_references(open_repo(project), ref_prefix)
     except (pygit2.GitError, OSError):
         return []
 
 
 def git_get_heads_list(project: str) -> list[tuple[str, str, str]]:
-    """List (name, ref, oid) for heads. Port of git_get_heads_list."""
-    refs = git_get_references(project, "refs/heads")
-    return [(ref.replace("refs/heads/", ""), ref, oid) for ref, oid in refs]
-
-
-def _tag_timestamp(repo: pygit2.Repository, oid: str) -> int:
-    """Return tagger time for an annotated tag, or committer time for a lightweight tag (commit)."""
     try:
-        obj = repo.revparse_single(oid)
-        if isinstance(obj, pygit2.Tag) and obj.tagger:
-            return obj.tagger.time
-        if isinstance(obj, pygit2.Commit):
-            return obj.committer.time
-    except (KeyError, pygit2.GitError):
-        pass
-    return 0
+        return _gh.git_get_heads_list(open_repo(project))
+    except (pygit2.GitError, OSError):
+        return []
 
 
 def git_get_tags_list(project: str) -> list[tuple[str, str, str]]:
-    """List (name, ref, oid) for tags. Sorted by tag creation time descending (newest first)."""
     try:
-        repo = open_repo(project)
-        result = []
-        for ref in repo.references.iterator(pygit2.enums.ReferenceFilter.TAGS):
-            oid = str(ref.resolve().target)
-            name = ref.name.replace("refs/tags/", "")
-            ts = _tag_timestamp(repo, oid)
-            result.append((name, ref.name, oid, ts))
-        result.sort(key=lambda x: (x[3], x[0]), reverse=True)
-        return [(name, ref_name, oid) for name, ref_name, oid, _ in result]
+        return _gh.git_get_tags_list(open_repo(project))
     except (pygit2.GitError, OSError):
         return []
 
 
 def git_get_remotes_info(project: str) -> list[dict[str, Any]]:
-    """Remote info: name, url, push_url. Uses pygit2 Remote.url and Remote.push_url."""
     try:
-        repo = open_repo(project)
-        result = []
-        for name in repo.remotes.names():
-            if not name:
-                continue
-            remote = repo.remotes[name]
-            result.append({
-                "name": name,
-                "url": remote.url or "",
-                "push_url": remote.push_url or remote.url or "",
-            })
-        return result
+        return _gh.git_get_remotes_info(open_repo(project))
     except (pygit2.GitError, OSError):
         return []
 
 
 def parse_commit(project: str, oid: str) -> dict[str, Any]:
-    """Commit metadata dict. Port of parse_commit (pygit2 commit)."""
     try:
-        repo = open_repo(project)
-        obj = repo.revparse_single(oid)
-        if not isinstance(obj, pygit2.Commit):
-            return {}
-        commit = obj
-        return {
-            "parent": [str(p) for p in commit.parent_ids],
-            "tree": str(commit.tree_id),
-            "author": commit.author.name,
-            "author_email": commit.author.email,
-            "author_epoch": commit.author.time,
-            "author_tz": commit.author.offset,
-            "committer": commit.committer.name,
-            "committer_email": commit.committer.email,
-            "committer_epoch": commit.committer.time,
-            "committer_tz": commit.committer.offset,
-            "subject": commit.message.split("\n")[0] if commit.message else "",
-            "body": commit.message or "",
-        }
-    except (KeyError, pygit2.GitError, OSError):
+        return _gh.parse_commit(open_repo(project), oid)
+    except (pygit2.GitError, OSError):
         return {}
 
 
 def parse_tag(project: str, oid: str) -> dict[str, Any]:
-    """Tag metadata. Port of parse_tag (pygit2 tag)."""
     try:
-        repo = open_repo(project)
-        obj = repo.revparse_single(oid)
-        if not isinstance(obj, pygit2.Tag):
-            return {}
-        tag = obj
-        return {
-            "object": str(tag.target),
-            "type": tag.type_str,
-            "tagger": tag.tagger.name if tag.tagger else "",
-            "tagger_email": tag.tagger.email if tag.tagger else "",
-            "tagger_epoch": tag.tagger.time if tag.tagger else 0,
-            "tagger_tz": tag.tagger.offset if tag.tagger else 0,
-            "message": tag.message or "",
-        }
-    except (KeyError, pygit2.GitError, OSError):
+        return _gh.parse_tag(open_repo(project), oid)
+    except (pygit2.GitError, OSError):
         return {}
 
 
@@ -377,102 +183,22 @@ def get_commit_history(
     max_count: int = 100,
     skip: int = 0,
 ) -> list[dict[str, Any]]:
-    """
-    Get commit history for a project, optionally filtered by path.
-    Returns list of commit dicts with oid and parsed commit data.
-    Port of git log functionality.
-    skip: number of matching commits to skip (for pagination).
-    """
     try:
-        repo = open_repo(project)
-        if ref:
-            try:
-                start_oid: pygit2.Oid | None = repo.revparse_single(ref).peel(pygit2.Commit).id
-            except (KeyError, pygit2.GitError, ValueError):
-                start_oid = None
-        else:
-            try:
-                start_oid = repo.head.peel(pygit2.Commit).id if repo.head else None
-            except (KeyError, pygit2.GitError, ValueError):
-                start_oid = None
-        if not start_oid:
-            return []
-
-        commits: list[dict[str, Any]] = []
-        skipped = 0
-        walker = repo.walk(
-            start_oid,
-            pygit2.enums.SortMode.TIME | pygit2.enums.SortMode.TOPOLOGICAL,
+        return _gh.get_commit_history(
+            open_repo(project),
+            ref=ref,
+            path=path,
+            max_count=max_count,
+            skip=skip,
         )
-
-        if path:
-            # Filter by path: only commits that touched this path (or a file under it)
-            path_clean = path.strip("/")
-            path_prefix = path_clean + "/"
-
-            def touched_path(diff: pygit2.Diff) -> bool:
-                for delta in diff.deltas:
-                    old_p, new_p = delta.old_file.path, delta.new_file.path
-                    if old_p == path_clean or new_p == path_clean:
-                        return True
-                    if old_p.startswith(path_prefix) or new_p.startswith(path_prefix):
-                        return True
-                return False
-
-            for commit in walker:
-                if len(commits) >= max_count:
-                    break
-                try:
-                    if commit.parents:
-                        diff = repo.diff(commit.parents[0], commit)
-                        if not touched_path(diff):
-                            continue
-                    else:
-                        # Root commit: include if path is root or path exists in tree
-                        if path_clean:
-                            try:
-                                commit.tree / path_clean
-                            except KeyError:
-                                continue
-                    if skipped < skip:
-                        skipped += 1
-                        continue
-                    commit_data = parse_commit(project, str(commit.id))
-                    commit_data["oid"] = str(commit.id)
-                    commits.append(commit_data)
-                except (KeyError, AttributeError, pygit2.GitError):
-                    pass
-        else:
-            # No path filter, get all commits
-            for commit in walker:
-                if skipped < skip:
-                    skipped += 1
-                    continue
-                if len(commits) >= max_count:
-                    break
-                commit_data = parse_commit(project, str(commit.id))
-                commit_data["oid"] = str(commit.id)
-                commits.append(commit_data)
-
-        return commits
-    except (KeyError, pygit2.GitError, OSError):
+    except (pygit2.GitError, OSError):
         return []
 
 
 def get_commits_in_range(project: str, tip: str, base: str | None) -> list[str]:
-    """Return list of commit OIDs from tip back to (but not including) base. Newest first."""
     try:
-        repo = open_repo(project)
-        tip_commit = repo.revparse_single(tip).peel(pygit2.Commit)
-        walker = repo.walk(
-            tip_commit.id,
-            pygit2.enums.SortMode.TIME | pygit2.enums.SortMode.TOPOLOGICAL,
-        )
-        if base:
-            with suppress(KeyError, pygit2.GitError, ValueError):
-                walker.hide(repo.revparse_single(base).peel(pygit2.Commit).id)
-        return [str(c.id) for c in walker]
-    except (KeyError, pygit2.GitError, OSError, ValueError):
+        return _gh.get_commits_in_range(open_repo(project), tip, base)
+    except (pygit2.GitError, OSError):
         return []
 
 
@@ -483,45 +209,49 @@ def get_blob_unified_diff(
     ref_new: str,
     path_new: str,
 ) -> str | None:
-    """
-    Return unified diff between blob at ref_old:path_old and ref_new:path_new using pygit2.
-    Returns None if either blob is not found; otherwise returns the diff string (possibly empty).
-    """
-    result_old = get_blob_at_ref_path(project, ref_old, path_old)
-    result_new = get_blob_at_ref_path(project, ref_new, path_new)
-    if not result_old or not result_new:
+    try:
+        return _gh.get_blob_unified_diff(open_repo(project), ref_old, path_old, ref_new, path_new)
+    except (pygit2.GitError, OSError):
         return None
-    old_blob, _ = result_old
-    new_blob, _ = result_new
-    patch = old_blob.diff(new_blob, old_as_path=path_old, new_as_path=path_new)
-    return patch.text if patch.text else ""
 
 
 def get_readme_at_ref_path(project: str, ref: str | None, dir_path: str | None) -> tuple[str, str] | None:
-    """
-    If a README exists at ref in the given tree (dir_path), return (filename, utf8_content).
-    Otherwise None. dir_path is the tree path (e.g. '' for root, 'docs' for docs/).
-    """
-    if not ref:
+    try:
+        return _gh.get_readme_at_ref_path(open_repo(project), ref, dir_path)
+    except (pygit2.GitError, OSError):
         return None
-    for name in README_CANDIDATES:
-        path = f"{dir_path.strip('/')}/{name}".strip("/") if dir_path else name
-        result = get_blob_at_ref_path(project, ref, path)
-        if result:
-            blob, _ = result
-            text = to_utf8(blob.data) or ""
-            return (name, text)
-    return None
 
 
 def get_commit_unified_diff(project: str, h: str) -> tuple[str, str]:
-    """
-    Return (unified_diff_text, oid_short) for commit h.
-    Raises KeyError, pygit2.GitError, OSError on error (caller should validate ref and map to HTTPException).
-    """
-    repo = open_repo(project)
-    commit = repo.revparse_single(h).peel(pygit2.Commit)
-    diff = repo.diff(commit.parents[0], commit) if commit.parents else commit.tree.diff_to_tree(swap=True)
-    body = diff.patch or ""
-    oid_short = commit.short_id[:7] if len(commit.short_id) >= 7 else commit.short_id
-    return body, oid_short
+    return _gh.get_commit_unified_diff(open_repo(project), h)
+
+
+__all__ = [
+    "clear_config_cache",
+    "config_to_bool",
+    "config_to_int",
+    "get_blob_at_ref_path",
+    "get_blob_unified_diff",
+    "get_commit_history",
+    "get_commit_unified_diff",
+    "get_commits_in_range",
+    "get_readme_at_ref_path",
+    "get_tree_at_ref_path",
+    "git_get_file_or_project_config",
+    "git_get_heads_list",
+    "git_get_project_config",
+    "git_get_project_description",
+    "git_get_references",
+    "git_get_remotes_info",
+    "git_get_tags_list",
+    "git_get_type",
+    "git_parse_project_config",
+    "hash_set_multi",
+    "open_repo",
+    "parse_commit",
+    "parse_tag",
+    "repo_git_signature",
+    "resolve_mr_opener",
+    "signature_from_principal_email",
+    "signature_from_user_credentials",
+]
diff --git a/pygitweb/src/pygitweb/git_helpers_test.py b/pygitweb/src/pygitweb/git_helpers_test.py
index ab7fe89..add518e 100644
--- a/pygitweb/src/pygitweb/git_helpers_test.py
+++ b/pygitweb/src/pygitweb/git_helpers_test.py
@@ -1,229 +1,34 @@
 from __future__ import annotations
 
-import subprocess
-from collections.abc import Generator
 from pathlib import Path
 from unittest.mock import patch
 
 import pygit2
-import pytest
 
 from pygitweb.config import settings
 from pygitweb.git_helpers import (
-    _config_cache,
-    config_to_bool,
-    config_to_int,
-    get_blob_at_ref_path,
-    get_blob_unified_diff,
-    get_commit_history,
-    get_commit_unified_diff,
-    get_commits_in_range,
-    get_readme_at_ref_path,
-    get_tree_at_ref_path,
-    git_get_file_or_project_config,
-    git_get_heads_list,
-    git_get_project_config,
-    git_get_project_description,
-    git_get_references,
-    git_get_remotes_info,
-    git_get_tags_list,
+    clear_config_cache,
     git_get_type,
-    git_parse_project_config,
-    hash_set_multi,
-    parse_commit,
-    parse_tag,
     resolve_mr_opener,
     signature_from_principal_email,
 )
 from pygitweb.permissions import PermissionPrincipal
 
 
-def _run_git(repo_dir: Path, *args: str) -> str:
-    completed: subprocess.CompletedProcess[str] = subprocess.run(
-        ["git", *args],
-        cwd=repo_dir,
-        capture_output=True,
-        text=True,
-        check=True,
-    )
-    return completed.stdout.strip()
-
-
-class TestGitHelpers:
-    class TestPure:
-        def test_hash_set_multi_promotes_to_list(self) -> None:
-            data: dict[str, object] = {}
-            hash_set_multi(data, "k", "v1")
-            hash_set_multi(data, "k", "v2")
-            assert data["k"] == ["v1", "v2"]
-
-        @pytest.mark.parametrize(
-            ("value", "expected"),
-            [("true", True), ("0", False), (None, True)],
-        )
-        def test_config_to_bool(self, value: str | None, expected: bool) -> None:
-            assert config_to_bool(value) is expected
-
-        @pytest.mark.parametrize(
-            ("value", "expected"),
-            [("2k", 2048), ("3M", 3145728), ("123", "123"), (None, 0)],
-        )
-        def test_config_to_int(self, value: str | None, expected: int | str) -> None:
-            assert config_to_int(value) == expected
-
-    class TestRepoReadonly:
-        @pytest.fixture(scope="class")
-        def repo_ctx(self, tmp_path_factory: pytest.TempPathFactory) -> Generator[dict[str, str], None, None]:
-            project_root: Path = tmp_path_factory.mktemp("git-helpers")
-            repo_dir: Path = project_root / "sample"
-            repo_dir.mkdir()
-
-            _run_git(repo_dir, "init", "-b", "main")
-            _run_git(repo_dir, "config", "user.name", "Alice")
-            _run_git(repo_dir, "config", "user.email", "alice@example.com")
-            _run_git(repo_dir, "remote", "add", "origin", "https://example.com/repo.git")
-            _run_git(repo_dir, "remote", "set-url", "--push", "origin", "ssh://example.com/repo.git")
-            _run_git(repo_dir, "config", "gitweb.owner", "alice")
-            _run_git(repo_dir, "config", "--add", "gitweb.category", "infra")
-            _run_git(repo_dir, "config", "--add", "gitweb.category", "tools")
-
-            (repo_dir / "README.md").write_text("Root README\n", encoding="utf-8")
-            (repo_dir / "docs").mkdir()
-            (repo_dir / "docs" / "README").write_text("Docs README\n", encoding="utf-8")
-            (repo_dir / "docs" / "guide.txt").write_text("hello\n", encoding="utf-8")
-            (repo_dir / "src").mkdir()
-            (repo_dir / "src" / "app.py").write_text("print('v1')\n", encoding="utf-8")
-            _run_git(repo_dir, "add", ".")
-            _run_git(repo_dir, "commit", "-m", "initial commit")
-
-            first_commit: str = _run_git(repo_dir, "rev-parse", "HEAD")
-            (repo_dir / "docs" / "guide.txt").write_text("hello\nworld\n", encoding="utf-8")
-            (repo_dir / "src" / "app.py").write_text("print('v2')\n", encoding="utf-8")
-            _run_git(repo_dir, "add", ".")
-            _run_git(repo_dir, "commit", "-m", "update docs and app")
-            second_commit: str = _run_git(repo_dir, "rev-parse", "HEAD")
-
-            _run_git(
-                repo_dir,
-                "tag",
-                "-a",
-                "v1.0",
-                "-m",
-                "release v1.0",
-                second_commit,
-            )
-            _run_git(repo_dir, "tag", "lightweight", first_commit)
-            _run_git(repo_dir, "branch", "feature/readme", second_commit)
-
-            git_dir: Path = repo_dir / ".git"
-            (git_dir / "description").write_text("Repo description\n", encoding="utf-8")
-
-            ctx: dict[str, str] = {
-                "project": "sample/.git",
-                "first_commit": first_commit,
-                "second_commit": second_commit,
-            }
-
-            _config_cache.clear()
-            with patch.object(settings, "PROJECTROOT", str(project_root)):
-                yield ctx
-            _config_cache.clear()
-
-        def test_git_get_type(self, repo_ctx: dict[str, str]) -> None:
-            assert git_get_type(repo_ctx["project"], "HEAD") == "commit"
-            assert git_get_type(repo_ctx["project"], "HEAD^{tree}") == "tree"
-
-        def test_git_parse_and_get_project_config(self, repo_ctx: dict[str, str]) -> None:
-            cfg: dict[str, object] = git_parse_project_config(repo_ctx["project"], "gitweb")
-            assert cfg["gitweb.owner"] == "alice"
-            assert cfg["gitweb.category"] == ["infra", "tools"]
-            assert git_get_project_config(repo_ctx["project"], "owner") == "alice"
-            assert git_get_project_config(repo_ctx["project"], "category") == ["infra", "tools"]
-
-        def test_git_get_file_or_project_config_prefers_file(self, repo_ctx: dict[str, str]) -> None:
-            assert git_get_file_or_project_config(repo_ctx["project"], "description") == "Repo description"
-            assert git_get_project_description(repo_ctx["project"]) == "Repo description"
-
-        def test_references_heads_tags_and_remotes(self, repo_ctx: dict[str, str]) -> None:
-            heads: list[tuple[str, str, str]] = git_get_heads_list(repo_ctx["project"])
-            head_names: set[str] = {name for name, _ref, _oid in heads}
-            assert {"main", "feature/readme"} <= head_names
-
-            refs: list[tuple[str, str]] = git_get_references(repo_ctx["project"])
-            assert any(name == "refs/heads/main" for name, _oid in refs)
-
-            tags: list[tuple[str, str, str]] = git_get_tags_list(repo_ctx["project"])
-            tag_names: set[str] = {name for name, _ref, _oid in tags}
-            assert {"v1.0", "lightweight"} <= tag_names
-
-            remotes: list[dict[str, object]] = git_get_remotes_info(repo_ctx["project"])
-            assert remotes == [
-                {
-                    "name": "origin",
-                    "url": "https://example.com/repo.git",
-                    "push_url": "ssh://example.com/repo.git",
-                }
-            ]
-
-        def test_parse_commit_and_parse_tag(self, repo_ctx: dict[str, str]) -> None:
-            commit_data: dict[str, object] = parse_commit(repo_ctx["project"], repo_ctx["second_commit"])
-            assert commit_data["subject"] == "update docs and app"
-            assert commit_data["author"] == "Alice"
-            assert isinstance(commit_data["parent"], list)
-
-            repo = pygit2.Repository(str(Path(settings.PROJECTROOT) / repo_ctx["project"]))
-            tag_oid: str = str(repo.references["refs/tags/v1.0"].target)
-            tag_data: dict[str, object] = parse_tag(repo_ctx["project"], tag_oid)
-            assert tag_data["type"] == "tag"
-            assert tag_data["message"] == "release v1.0\n"
-
-        def test_tree_blob_and_readme_resolution(self, repo_ctx: dict[str, str]) -> None:
-            tree_result = get_tree_at_ref_path(repo_ctx["project"], "HEAD", "docs")
-            assert tree_result is not None
-            tree, ref_oid = tree_result
-            assert ref_oid == repo_ctx["second_commit"]
-            assert tree["guide.txt"].type_str == "blob"
-
-            blob_result = get_blob_at_ref_path(repo_ctx["project"], "HEAD", "docs/guide.txt")
-            assert blob_result is not None
-            blob, _resolved_ref = blob_result
-            assert blob.data.decode("utf-8") == "hello\nworld\n"
-
-            readme_root = get_readme_at_ref_path(repo_ctx["project"], "HEAD", "")
-            assert readme_root == ("README.md", "Root README\n")
-            readme_docs = get_readme_at_ref_path(repo_ctx["project"], "HEAD", "docs")
-            assert readme_docs == ("README", "Docs README\n")
-
-        def test_commit_history_and_ranges(self, repo_ctx: dict[str, str]) -> None:
-            all_history: list[dict[str, object]] = get_commit_history(repo_ctx["project"], max_count=10)
-            assert [entry["oid"] for entry in all_history] == [repo_ctx["second_commit"], repo_ctx["first_commit"]]
-
-            path_history: list[dict[str, object]] = get_commit_history(
-                repo_ctx["project"],
-                path="docs/guide.txt",
-                max_count=10,
-            )
-            assert [entry["oid"] for entry in path_history] == [repo_ctx["second_commit"], repo_ctx["first_commit"]]
-
-            in_range: list[str] = get_commits_in_range(repo_ctx["project"], "HEAD", repo_ctx["first_commit"])
-            assert in_range == [repo_ctx["second_commit"]]
-
-        def test_blob_and_commit_unified_diff(self, repo_ctx: dict[str, str]) -> None:
-            blob_diff = get_blob_unified_diff(
-                repo_ctx["project"],
-                repo_ctx["first_commit"],
-                "src/app.py",
-                repo_ctx["second_commit"],
-                "src/app.py",
-            )
-            assert blob_diff is not None
-            assert "-print('v1')" in blob_diff
-            assert "+print('v2')" in blob_diff
-
-            commit_diff, oid_short = get_commit_unified_diff(repo_ctx["project"], "HEAD")
-            assert "docs/guide.txt" in commit_diff
-            assert "src/app.py" in commit_diff
-            assert oid_short == repo_ctx["second_commit"][:7]
+class TestProjectWrappers:
+    def test_git_get_type_via_project_name(self, tmp_path: Path) -> None:
+        root = tmp_path / "root"
+        project = root / "demo"
+        project.mkdir(parents=True)
+        repo = pygit2.init_repository(str(project), bare=False)
+        tb = repo.TreeBuilder()
+        tree = tb.write()
+        sig = pygit2.Signature("t", "t@example.com")
+        repo.create_commit("HEAD", sig, sig, "init", tree, [])
+        clear_config_cache()
+        with patch.object(settings, "PROJECTROOT", str(root)):
+            assert git_get_type("demo", "HEAD") == "commit"
+        clear_config_cache()
 
 
 class TestResolveMrOpener:
