Files
fiona-assistant/src/fiona/gittool/diff_report.py
T

1023 lines
34 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Generate a constellation-themed HTML report from ``git diff``.
Generated by AI/LLM: 2026-10-19 - fiona-assistant git diff; wiki tmp/ output.
"""
from __future__ import annotations
import argparse
import datetime
import html
import importlib.resources
import pathlib
import re
import subprocess
import sys
from fiona.librarian.toc_generator import find_wiki_root
from fiona.wiki.graph_generator import (
_opening_theme,
load_constellation_themes,
load_graph_settings,
)
_BASE_REF_CANDIDATES = ("origin/main", "origin/master", "main", "master")
def find_git_root(start_path: pathlib.Path | None = None) -> pathlib.Path:
"""Find the root git repository directory from a starting path.
Walks up from the starting path until it finds a .git directory.
Args:
start_path: Path to start searching from. Defaults to current working directory.
Returns:
Absolute path to the git repository root directory.
Raises:
RuntimeError: When no git repository is found.
"""
if start_path is None:
start_path = pathlib.Path.cwd()
else:
start_path = pathlib.Path(start_path)
# Resolve to absolute path
current = start_path.resolve()
# Check if current directory is a git repo
while True:
git_dir = current / ".git"
# Verify it's actually a git directory by checking for HEAD
if git_dir.is_dir() and (git_dir / "HEAD").is_file():
return current
# Move up one level
parent = current.parent
if parent == current:
# Reached the root filesystem directory
break
current = parent
message = f"No git repository found starting from {start_path}"
raise RuntimeError(message)
def run_git(repo: pathlib.Path, *args: str) -> str:
"""Run a git command in ``repo`` and return stdout.
Generated by AI/LLM: 2026-10-19 - subprocess wrapper for diff report.
Args:
repo: Git repository root.
*args: Git arguments after the ``git`` executable name.
Returns:
Stripped stdout on success.
Raises:
RuntimeError: When git exits non-zero.
"""
result = subprocess.run(
["git", *args],
capture_output=True,
text=True,
cwd=repo,
check=False,
)
if result.returncode != 0:
message = (result.stderr or result.stdout or "git failed").strip()
raise RuntimeError(message)
return result.stdout
def ref_exists(repo: pathlib.Path, ref: str) -> bool:
"""Return whether ``ref`` resolves in ``repo``.
Generated by AI/LLM: 2026-10-19 - pick default base branch.
Args:
repo: Git repository root.
ref: Revision name to test.
Returns:
True when ``git rev-parse`` succeeds.
"""
result = subprocess.run(
["git", "rev-parse", "--verify", ref],
capture_output=True,
text=True,
cwd=repo,
check=False,
)
return result.returncode == 0
def resolve_default_base(repo: pathlib.Path) -> str:
"""Return the first usable default base ref for branch comparisons.
Generated by AI/LLM: 2026-10-19 - origin/main then main/master fallbacks.
Args:
repo: Git repository root.
Returns:
A ref that exists in the repository.
Raises:
RuntimeError: When no candidate ref exists.
"""
for candidate in _BASE_REF_CANDIDATES:
if ref_exists(repo, candidate):
return candidate
message = (
"No default base ref found "
f"(tried {', '.join(_BASE_REF_CANDIDATES)}). Use --base."
)
raise RuntimeError(message)
def resolve_base_head(
repo: pathlib.Path,
base: str | None,
head: str,
) -> tuple[str, str]:
"""Return (base, head) refs to compare.
Generated by AI/LLM: 2026-10-19 - default base is tracking branch tip.
Args:
repo: Git repository root.
base: Optional base ref; when omitted, use resolve_default_base.
head: Head ref (default HEAD).
Returns:
The pair of refs passed to ``git diff``.
"""
if base:
return base, head
return resolve_default_base(repo), head
def wiki_root_for_repo(repo: pathlib.Path) -> pathlib.Path:
"""Return the llm-wiki root used for tmp/ output and constellation themes.
Generated by AI/LLM: 2026-10-19 - nearest fiona-settings.json per toc_generator.
For git diff, when the git root is not a wiki, use the git root itself.
Args:
repo: Git repository root (usually the wiki root).
Returns:
Wiki root directory (may equal ``repo`` when no settings file exists).
"""
# Check if the repo itself is a wiki (has fiona-settings.json)
settings_file = repo / "fiona-settings.json"
if settings_file.is_file():
return find_wiki_root(repo)
# If the git repo is not a wiki, use the git root for tmp/ output
return repo
def is_wiki_repo(repo: pathlib.Path) -> bool:
"""Check if a directory is a wiki repository (has fiona-settings.json).
Args:
repo: Path to check.
Returns:
True if the directory contains fiona-settings.json.
"""
return (repo / "fiona-settings.json").is_file()
def theme_toggle_html(is_wiki: bool) -> str:
"""Generate HTML for the theme toggle button.
Args:
is_wiki: Whether this is a wiki repository.
Returns:
HTML string for the theme toggle button, or empty string for wikis.
"""
if is_wiki:
return ""
return '<div class="theme-toggle"><button type="button" id="theme-toggle">Toggle Light Mode</button></div>'
def _css_color(value: object, fallback: str) -> str:
"""Return a CSS color string from a theme value.
Generated by AI/LLM: 2026-10-19 - constellation JSON to CSS colors.
Args:
value: Theme field (usually a hex string).
fallback: Used when value is not a non-empty string.
Returns:
A color literal safe for CSS.
"""
if isinstance(value, str) and value.strip():
return value.strip()
return fallback
def theme_css_for_wiki(wiki_root: pathlib.Path, is_wiki: bool = True) -> str:
"""Build a ``:root`` CSS block from the wiki's opening constellation theme.
Generated by AI/LLM: 2026-10-19 - same theme resolution as wiki graph.
For non-wiki repos, uses a default light theme.
Themes ship as one JSON file per palette under the packaged
``llm_wiki/constellation/`` directory (for example ``night-sky.json``).
The wiki chooses which palette to open on via
``fiona.wiki.graph.theme`` in ``fiona-settings.json``. Local
``constellation/`` or ``constellation-settings.json`` overlays work
the same way as for ``fiona-assistant wiki graph``.
Args:
wiki_root: Directory that may hold ``fiona-settings.json``.
is_wiki: Whether this is a wiki repository. If False, uses default light theme.
Returns:
CSS rules defining report variables (includes ``:root``).
"""
if is_wiki:
graph_settings = load_graph_settings(str(wiki_root))
themes = load_constellation_themes(str(wiki_root), graph_settings)
theme_name = _opening_theme(graph_settings, themes)
theme = themes.get(theme_name, themes.get("colorful", {}))
if not isinstance(theme, dict):
theme = {}
card = theme.get("card") if isinstance(theme.get("card"), dict) else {}
buttons = theme.get("buttons") if isinstance(theme.get("buttons"), dict) else {}
highlight = theme.get("highlight") if isinstance(theme.get("highlight"), dict) else {}
orphan = theme.get("orphan") if isinstance(theme.get("orphan"), dict) else {}
bg = _css_color(theme.get("background"), "#f4f6fb")
card_bg = _css_color(card.get("background"), "#ffffff")
border = _css_color(card.get("border"), "#e2e8f0")
text = _css_color(theme.get("text_color"), "#121212")
font = _css_color(theme.get("font_family"), "Segoe UI, sans-serif")
blue = _css_color(buttons.get("background"), "#124191")
accent = _css_color(highlight.get("edge_color"), "#0057e8")
header_end = _css_color(highlight.get("node_color"), accent)
muted = _css_color(theme.get("subtitle_color"), "#64748b")
add_tint = _css_color(highlight.get("node_color"), "#15803d")
del_tint = _css_color(orphan.get("node_color"), "#b91c1c")
summary_bg = _css_color(theme.get("graph_background"), card_bg)
button_bg = _css_color(buttons.get("background"), "#ffffff")
button_text = _css_color(buttons.get("text"), text)
button_hover = _css_color(buttons.get("hover"), border)
link_hover_bg = _css_color(highlight.get("edge_color"), "#eff6ff")
else:
# Default dark theme for non-wiki repos
bg = "#1a1a1a"
card_bg = "#2d2d2d"
border = "#404040"
text = "#e0e0e0"
font = "Segoe UI, sans-serif"
blue = "#6ba1f5"
accent = "#7aa7d6"
header_end = "#c586c0"
muted = "#9e9e9e"
add_tint = "#7edd8a"
del_tint = "#ff7b7b"
summary_bg = "#252525"
button_bg = "#3d3d3d"
button_text = "#e0e0e0"
button_hover = "#4a4a4a"
link_hover_bg = "#3a3a3a"
return f""":root {{
--bg: {bg};
--card: {card_bg};
--border: {border};
--text: {text};
--font: {font};
--blue: {blue};
--accent: {accent};
--header-end: {header_end};
--muted: {muted};
--summary-bg: {summary_bg};
--button-bg: {button_bg};
--button-text: {button_text};
--button-hover: {button_hover};
--link-hover-bg: color-mix(in srgb, {link_hover_bg} 18%, var(--card));
--link-active-bg: color-mix(in srgb, {accent} 22%, var(--card));
--diff-add-bg: color-mix(in srgb, {add_tint} 22%, var(--card));
--diff-del-bg: color-mix(in srgb, {del_tint} 22%, var(--card));
--diff-hunk: {accent};
--diff-meta: {blue};
--churn-add: {add_tint};
--churn-del: {del_tint};
--sidebar-w: 300px;
}}"""
def classify_diff_line(line: str) -> str:
"""Return a CSS class name for one unified-diff line.
Generated by AI/LLM: 2026-10-19 - diff syntax highlighting classes.
Args:
line: One line from unified diff output.
Returns:
A class name used by the HTML template.
"""
if line.startswith(("+++", "---")):
return "diff-meta"
if line.startswith("@@"):
return "diff-hunk"
if line.startswith("+") and not line.startswith("+++"):
return "diff-add"
if line.startswith("-") and not line.startswith("---"):
return "diff-del"
return "diff-ctx"
def colorize_diff(text: str) -> str:
"""Turn unified diff text into HTML spans.
Generated by AI/LLM: 2026-10-19 - escape and wrap diff lines.
Removes spacing between consecutive added lines and between consecutive
deleted lines, but preserves spacing between added and deleted lines.
Args:
text: Unified diff body for one file.
Returns:
HTML safe for embedding in ``<pre>``.
"""
result_parts: list[str] = []
prev_css: str | None = None
for line in text.splitlines():
css = classify_diff_line(line)
span = f'<span class="{css}">{html.escape(line)}</span>'
# For diff-add and diff-del, concatenate consecutive spans without newlines
if css in ('diff-add', 'diff-del') and css == prev_css:
# Append to last part without newline
if result_parts:
result_parts[-1] = result_parts[-1] + span
else:
result_parts.append(span)
else:
# Add as new part with newline
result_parts.append(span)
prev_css = css
return "\n".join(result_parts)
def path_anchor_id(path: str) -> str:
"""Return a stable HTML ``id`` for a repo-relative file path.
Generated by AI/LLM: 2026-10-19 - sidebar hash navigation.
Args:
path: Repository-relative path.
Returns:
An HTML id attribute value.
"""
normalized = path.replace("\\", "/")
slug = re.sub(r"[^a-zA-Z0-9]+", "-", normalized).strip("-")
return f"file-{slug}" if slug else "file-root"
def parse_numstat(numstat_text: str) -> dict[str, tuple[int, int]]:
"""Parse ``git diff --numstat`` into path -> (added, deleted) line counts.
Generated by AI/LLM: 2026-10-19 - churn labels in file tree.
Args:
numstat_text: Raw ``git diff --numstat`` output.
Returns:
Mapping of file path to added/deleted line counts.
"""
stats: dict[str, tuple[int, int]] = {}
for line in numstat_text.strip().splitlines():
if not line.strip():
continue
parts = line.split("\t")
if len(parts) < 3:
continue
added_raw, deleted_raw, file_path = parts[0], parts[1], parts[2]
if added_raw == "-" or deleted_raw == "-":
stats[file_path] = (0, 0)
continue
stats[file_path] = (int(added_raw), int(deleted_raw))
return stats
def insert_path_in_tree(tree: dict, path: str) -> None:
"""Insert one file path into a nested folder tree.
Generated by AI/LLM: 2026-10-19 - sidebar directory structure.
Args:
tree: Nested dict (folders are dicts, leaves are full paths).
path: Repository-relative file path.
"""
parts = path.replace("\\", "/").split("/")
cursor = tree
for part in parts[:-1]:
cursor = cursor.setdefault(part, {})
cursor[parts[-1]] = path
def render_file_tree(tree: dict, stats: dict[str, tuple[int, int]], file_status: dict[str, str] | None = None) -> str:
"""Render nested ``<ul>`` HTML for the sidebar file tree.
Generated by AI/LLM: 2026-10-19 - file list with churn counts and status icons.
Args:
tree: Nested path tree from insert_path_in_tree.
stats: Per-file line churn from parse_numstat.
file_status: Optional dict mapping file paths to their status ('deleted', 'untracked', 'modified').
Returns:
HTML fragment for the sidebar.
"""
if file_status is None:
file_status = {}
def status_icon(file_path: str) -> str:
status = file_status.get(file_path, "modified")
if status == "deleted":
return '<span class="file-icon" title="Deleted">🗑️</span>'
elif status == "untracked":
return '<span class="file-icon" title="Untracked">📄</span>'
elif status == "added":
return '<span class="file-icon" title="Added">➕</span>'
else:
return '<span class="file-icon" title="Modified">📝</span>'
def churn_label(file_path: str) -> str:
added, deleted = stats.get(file_path, (0, 0))
if added == 0 and deleted == 0:
return ""
return (
f'<span class="churn">'
f'<span class="add">+{added}</span> '
f'<span class="del">−{deleted}</span>'
f"</span>"
)
def walk(node: dict) -> str:
items: list[str] = []
for name in sorted(node.keys(), key=str.lower):
value = node[name]
if isinstance(value, str):
anchor = path_anchor_id(value)
items.append(
f'<li class="leaf"><a href="#{anchor}">{status_icon(value)}{html.escape(name)}</a>'
f"{churn_label(value)}</li>"
)
elif isinstance(value, dict):
inner = walk(value)
items.append(
f'<li class="folder"><span class="folder-label">{html.escape(name)}</span>'
f"<ul>{inner}</ul></li>"
)
return "".join(items)
return f'<ul class="file-tree">{walk(tree)}</ul>'
def get_untracked_files(repo: pathlib.Path) -> list[str]:
"""Get list of untracked files in the repository.
Args:
repo: Git repository root.
Returns:
List of untracked file paths relative to repo.
"""
try:
output = run_git(repo, "ls-files", "--others", "--exclude-standard")
return [p.strip() for p in output.splitlines() if p.strip()]
except RuntimeError:
return []
def get_deleted_files(repo: pathlib.Path, base_ref: str, head_ref: str) -> list[str]:
"""Get list of deleted files between base and head.
Args:
repo: Git repository root.
base_ref: Base reference.
head_ref: Head reference.
Returns:
List of deleted file paths relative to repo.
"""
try:
diff_range = f"{base_ref}..{head_ref}"
output = run_git(repo, "diff", "--name-only", "--diff-filter=D", diff_range)
return [p.strip() for p in output.splitlines() if p.strip()]
except RuntimeError:
return []
def create_file_diff(repo: pathlib.Path, path: str) -> str:
"""Create a diff for a single file (untracked or deleted).
For untracked files, show as new file (all additions).
For deleted files, show as removed file (all deletions).
Args:
repo: Git repository root.
path: File path relative to repo.
Returns:
Unified diff text for the file.
"""
file_path = repo / path
if not file_path.exists():
# Deleted file - show as all deletions
# Use git show to get the last version of the file
try:
content = run_git(repo, "show", f"{path}")
lines = [f"--- a/{path}", "+++ /dev/null", "@@ -1 +0,0 @@"]
for line in content.splitlines():
lines.append(f"-{line}")
return "\n".join(lines)
except RuntimeError:
return f"--- a/{path}\n+++ /dev/null\n"
else:
# Untracked file - show as all additions
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
lines = ["--- /dev/null", f"+++ b/{path}", "@@ -0,0 +1 @@"]
for line in content.splitlines():
lines.append(f"+{line}")
return "\n".join(lines)
except (OSError, UnicodeDecodeError):
return "--- /dev/null\n" f"+++ b/{path}\n"
def split_diff_by_file(raw_diff: str) -> list[tuple[str, str]]:
"""Split ``git diff`` output into (path, body) pairs.
Generated by AI/LLM: 2026-10-19 - one section per changed file.
Args:
raw_diff: Full unified diff text.
Returns:
List of path and diff body (without the ``diff --git`` header line).
"""
blocks: list[tuple[str, str]] = []
for part in re.split(r"^diff --git ", raw_diff, flags=re.MULTILINE):
if not part.strip():
continue
header_line, rest = part.split("\n", 1)
match = re.match(r"a/(.+?) b/(.+)$", header_line)
path = match.group(2) if match else header_line
blocks.append((path, rest))
return blocks
def build_files_html(file_blocks: list[tuple[str, str]], open_details: bool) -> str:
"""Render per-file ``<details>`` sections.
Generated by AI/LLM: 2026-10-19 - collapsible per-file diffs.
All file diffs are collapsed by default except the first one.
Args:
file_blocks: Paths and diff bodies.
open_details: When True, sections start expanded (overridden to only first).
Returns:
HTML fragment.
"""
chunks: list[str] = []
for idx, (path, body) in enumerate(file_blocks):
anchor = path_anchor_id(path)
# Only the first file diff is open by default
open_attr = " open" if (open_details and idx == 0) else ""
chunks.append(
f'<details class="file" id="{anchor}"{open_attr}>'
f"<summary><code>{html.escape(path)}</code></summary>"
f'<pre class="diff">{colorize_diff(body)}</pre>'
f"</details>"
)
return "\n".join(chunks)
def load_template() -> str:
"""Read the packaged HTML layout template.
Generated by AI/LLM: 2026-10-19 - gittool/templates/git-diff-report.template.html.
Returns:
Template text with ``{{...}}`` placeholders.
Raises:
FileNotFoundError: When the template is missing from the package.
"""
resource = importlib.resources.files("fiona").joinpath(
"gittool",
"templates",
"git-diff-report.template.html",
)
path = pathlib.Path(str(resource))
if not path.is_file():
raise FileNotFoundError(f"Template missing: {path}")
return path.read_text(encoding="utf-8")
def render_report(
page_title: str,
header_body_html: str,
stat_block: str,
file_blocks: list[tuple[str, str]],
file_stats: dict[str, tuple[int, int]],
theme_css: str,
open_details: bool = True,
theme_toggle_html: str = "",
file_status: dict[str, str] | None = None,
) -> str:
"""Fill the template with report content.
Generated by AI/LLM: 2026-10-19 - substitute placeholders.
Args:
page_title: Document title and H1 default.
header_body_html: HTML inside ``<header>`` (trusted caller content).
stat_block: ``git diff --stat`` text.
file_blocks: Per-file diff sections.
file_stats: Line churn per path.
theme_css: ``:root`` CSS from theme_css_for_wiki.
open_details: Expand file sections by default.
theme_toggle_html: HTML for theme toggle button.
file_status: Optional dict mapping file paths to their status ('deleted', 'untracked', 'modified').
Returns:
Complete HTML page.
"""
template = load_template()
files_html = build_files_html(file_blocks, open_details)
tree: dict = {}
for path, _body in file_blocks:
insert_path_in_tree(tree, path)
tree_html = render_file_tree(tree, file_stats, file_status)
return (
template.replace("{{PAGE_TITLE}}", html.escape(page_title))
.replace("{{THEME_CSS}}", theme_css)
.replace("{{THEME_TOGGLE_HTML}}", theme_toggle_html)
.replace("{{HEADER_BODY}}", header_body_html)
.replace("{{STAT_BLOCK}}", html.escape(stat_block.strip()))
.replace("{{FILE_COUNT}}", str(len(file_blocks)))
.replace("{{TREE_HTML}}", tree_html)
.replace("{{FILES_HTML}}", files_html)
)
def commit_meta(repo: pathlib.Path, head: str) -> tuple[str, str, str]:
"""Return (full hash, subject, body) for ``head``.
Generated by AI/LLM: 2026-10-19 - report header metadata.
Args:
repo: Git repository root.
head: Commit ref to describe.
Returns:
Full SHA, subject line, and body (may be empty).
"""
text = run_git(repo, "log", "-1", "--format=%H%n%s%n%b", head).strip()
lines = text.split("\n", 2)
commit_hash = lines[0]
subject = lines[1] if len(lines) > 1 else ""
body = lines[2] if len(lines) > 2 else ""
return commit_hash, subject, body
def default_output_path(wiki_root: pathlib.Path, repo: pathlib.Path, head: str) -> pathlib.Path:
"""Pick ``wiki_root/tmp/git-diff-<short-head>.html``.
Generated by AI/LLM: 2026-10-19 - ignored tmp/ under wiki root.
Args:
wiki_root: llm-wiki root for tmp/.
repo: Git repository (for rev-parse).
head: Head ref to shorten in the filename.
Returns:
Absolute path under ``wiki_root/tmp/``.
"""
short_head = run_git(repo, "rev-parse", "--short", head).strip()
repo_name = repo.resolve().name.replace(" ", "-")
return wiki_root / "tmp" / f"{repo_name}-git-diff-{short_head}.html"
def generate_report(
repo: pathlib.Path,
wiki_root: pathlib.Path,
base: str | None,
head: str,
title: str | None,
subtitle: str | None,
open_details: bool,
staged_only: bool = False,
unstaged_only: bool = False,
) -> tuple[str, str, list[tuple[str, str]]]:
"""Produce HTML and metadata without writing a file.
Generated by AI/LLM: 2026-10-19 - core diff report builder.
Args:
repo: Git repository root.
wiki_root: Wiki root for constellation theme CSS.
base: Optional base ref.
head: Head ref.
title: Optional page title.
subtitle: Optional extra header line.
open_details: Expand file diffs by default.
staged_only: When True, only show staged changes.
unstaged_only: When True, only show unstaged changes.
Returns:
HTML string, diff range label, and file blocks.
"""
base_ref, head_ref = resolve_base_head(repo, base, head)
# Determine the diff range based on flags
base_ref, head_ref = resolve_base_head(repo, base, head)
if staged_only:
# Only staged changes (compare index to HEAD)
commit_hash, subject, body = commit_meta(repo, "HEAD")
# Use git diff --cached to show only staged changes
stat = run_git(repo, "diff", "--cached", "--stat")
numstat = run_git(repo, "diff", "--cached", "--numstat")
raw_diff = run_git(repo, "diff", "--cached")
elif unstaged_only:
# Only unstaged changes (compare working tree to index)
commit_hash, subject, body = commit_meta(repo, "HEAD")
# Use git diff without --cached and without range to show only unstaged changes
stat = run_git(repo, "diff", "--stat")
numstat = run_git(repo, "diff", "--numstat")
raw_diff = run_git(repo, "diff")
else:
# Default: compare base to head
commit_hash, subject, body = commit_meta(repo, head_ref)
# If base and head resolve to the same commit, compare HEAD to working tree to show unstaged changes
base_sha = run_git(repo, "rev-parse", base_ref).strip()
head_sha = run_git(repo, "rev-parse", head_ref).strip()
diff_range = f"{base_ref}..{head_ref}" if base_sha != head_sha else "HEAD"
stat = run_git(repo, "diff", "--stat", diff_range)
numstat = run_git(repo, "diff", "--numstat", diff_range)
raw_diff = run_git(repo, "diff", diff_range)
file_stats = parse_numstat(numstat)
file_blocks = split_diff_by_file(raw_diff)
# Track file status: 'modified', 'deleted', 'untracked', or 'added'
file_status: dict[str, str] = {}
# Helper function to detect file status from diff
def detect_file_status(diff_body: str) -> str:
lines = diff_body.strip().split("\n")
if not lines:
return "modified"
# Check for git diff deletion marker
if lines[0].startswith("deleted file mode"):
return "deleted"
# Check for git diff addition marker
if lines[0].startswith("new file mode"):
return "added"
# Check the first two lines for diff headers
if len(lines) >= 2:
if lines[0].startswith("--- a/") and lines[1] == "+++ /dev/null":
return "deleted"
if lines[0] == "--- /dev/null" and lines[1].startswith("+++ b/"):
return "added"
# Default to modified for standard diffs
return "modified"
# Mark files from the main diff based on their diff content
for path, body in file_blocks:
file_status[path] = detect_file_status(body)
# Include additional files based on mode
if staged_only:
# For staged mode, don't include untracked files (they're not staged)
# Deleted files that are staged will be included in the git diff --cached output
pass
elif unstaged_only:
# For unstaged mode, include untracked files (they are also unstaged)
untracked_files = get_untracked_files(repo)
for untracked_path in untracked_files:
if not any(path == untracked_path for path, _ in file_blocks):
diff_content = create_file_diff(repo, untracked_path)
file_blocks.append((untracked_path, diff_content))
file_stats[untracked_path] = (0, 0)
file_status[untracked_path] = "untracked"
else:
# Default mode: include untracked and deleted files
untracked_files = get_untracked_files(repo)
deleted_files = get_deleted_files(repo, base_ref, head_ref)
# Add untracked files as new files
for untracked_path in untracked_files:
if not any(path == untracked_path for path, _ in file_blocks):
diff_content = create_file_diff(repo, untracked_path)
file_blocks.append((untracked_path, diff_content))
file_stats[untracked_path] = (0, 0)
file_status[untracked_path] = "untracked"
# Add deleted files
for deleted_path in deleted_files:
if not any(path == deleted_path for path, _ in file_blocks):
diff_content = create_file_diff(repo, deleted_path)
file_blocks.append((deleted_path, diff_content))
file_stats[deleted_path] = (0, 0)
file_status[deleted_path] = "deleted"
page_title = title or f"{repo.name} diff review"
header_lines = [
f"<h1>{html.escape(page_title)}</h1>",
f"<p><strong>{html.escape(subject)}</strong></p>",
(
f"<p>Commit <code>{html.escape(commit_hash[:12])}</code> "
f"vs <code>{html.escape(base_ref[:12] if len(base_ref) > 12 else base_ref)}</code></p>"
),
]
if body.strip():
header_lines.append(f"<p>{html.escape(body.strip())}</p>")
if subtitle:
header_lines.append(f"<p>{html.escape(subtitle)}</p>")
generated = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M")
header_lines.append(f"<p>Generated {generated} UTC.</p>")
header_body = "\n ".join(header_lines)
# Check if this is a wiki repository
is_wiki = is_wiki_repo(wiki_root)
theme_css = theme_css_for_wiki(wiki_root, is_wiki=is_wiki)
toggle_html = theme_toggle_html(is_wiki)
html_page = render_report(
page_title,
header_body,
stat,
file_blocks,
file_stats,
theme_css,
open_details,
toggle_html,
file_status,
)
return html_page, f"{base_ref}..{head_ref}", file_blocks
def write_report(
repo: pathlib.Path,
output: pathlib.Path,
base: str | None,
head: str,
title: str | None,
subtitle: str | None,
open_details: bool,
staged_only: bool = False,
unstaged_only: bool = False,
) -> pathlib.Path:
"""Write the HTML report to ``output``.
Generated by AI/LLM: 2026-10-19 - create parent dirs and write UTF-8.
Args:
repo: Git repository root.
output: Destination HTML path.
base: Optional base ref.
head: Head ref.
title: Optional page title.
subtitle: Optional header line.
open_details: Expand file diffs by default.
staged_only: When True, only show staged changes.
unstaged_only: When True, only show unstaged changes.
Returns:
Resolved output path.
"""
wiki_root = wiki_root_for_repo(repo)
html_page, _range, _blocks = generate_report(
repo,
wiki_root,
base,
head,
title,
subtitle,
open_details,
staged_only=staged_only,
unstaged_only=unstaged_only,
)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(html_page, encoding="utf-8", newline="\n")
return output.resolve()
def main(argv: list[str] | None = None) -> int:
"""CLI entry point for ``fiona-assistant git diff``.
Generated by AI/LLM: 2026-10-19 - default output under wiki tmp/.
Args:
argv: Optional argument list (omit for sys.argv).
Returns:
Process exit code.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base", help="Base revision (default: origin/main or main/master)")
parser.add_argument("--head", default="HEAD", help="Head revision (default: HEAD)")
parser.add_argument("--title", help="Report H1 / page title")
parser.add_argument(
"--subtitle",
help="Extra header line (e.g. temporary review before push)",
)
parser.add_argument(
"-o",
"--output",
type=pathlib.Path,
help="Output HTML path (default: <wiki>/tmp/<repo>-git-diff-<short>.html)",
)
parser.add_argument(
"--collapsed",
action="store_true",
help="Start with per-file sections collapsed",
)
parser.add_argument(
"--unstaged",
action="store_true",
help="Diff only unstaged changes (ignores staged changes)",
)
parser.add_argument(
"--staged",
action="store_true",
help="Diff only staged changes (ignores unstaged changes)",
)
args = parser.parse_args(argv)
repo = find_git_root()
# find_git_root already verifies it's a git repo, so no need to check again
wiki_root = wiki_root_for_repo(repo)
head_ref = args.head
try:
_base_ref, head_ref = resolve_base_head(repo, args.base, args.head)
except RuntimeError as exc:
print(str(exc), file=sys.stderr)
return 1
out = args.output
if out is None:
try:
out = default_output_path(wiki_root, repo, head_ref)
except RuntimeError as exc:
print(str(exc), file=sys.stderr)
return 1
elif not out.is_absolute():
out = (wiki_root / out).resolve()
# Validate that --staged and --unstaged are not both specified
if args.staged and args.unstaged:
print("Error: Cannot specify both --staged and --unstaged", file=sys.stderr)
return 1
try:
path = write_report(
repo,
out,
args.base,
args.head,
args.title,
args.subtitle,
open_details=not args.collapsed,
staged_only=args.staged,
unstaged_only=args.unstaged,
)
except (RuntimeError, FileNotFoundError) as exc:
print(str(exc), file=sys.stderr)
return 1
print(path)
return 0