From 983198b8b480f19e4be39589e6bbe1eb998ae584 Mon Sep 17 00:00:00 2001 From: nvaldez Date: Sat, 24 Oct 2026 14:11:21 +0200 Subject: [PATCH] feat: add git diff staged/unstaged flags and root discovery\n\n- Git commands now discover and operate on root repository from current dir (7.12.0)\n- git diff includes untracked and deleted files by default (7.12.6)\n- Add --staged and --unstaged flags to git diff (7.12.7, 7.12.8)\n- Update diff rendering: collapse consecutive added/deleted lines (7.12.5)\n- Update SPEC to 1.22.1 and CHANGELOG to 1.2.3\n\nGenerated by Mistral Vibe.\nCo-Authored-By: Mistral Vibe --- CHANGELOG.md | 25 +- SPEC.md | 71 +- src/fiona/__main__.py | 14 + src/fiona/gittool/diff_report.py | 1714 ++++++++++------- .../templates/git-diff-report.template.html | 564 +++--- tests/test_git_diff_report.py | 702 +++++-- 6 files changed, 2035 insertions(+), 1055 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 76216b6..4008f62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,9 @@ --- name: changelog -version: 1.2.2 +version: 1.2.3 title: Changelog created: 2026-10-08 -updated: 2026-10-21 +updated: 2026-10-24 type: summary --- @@ -13,6 +13,27 @@ Revisions of [SPEC](./SPEC.md), newest first. Each entry names the requirements it adds or changes. "Unbuilt" means the requirement is specified and marked `NOT_IMPLEMENTED`. +## 1.22.1 - 2026-10-24 + +- Minor corrections to 1.22.0. + +## 1.22.0 - 2026-10-24 + +- Adds `--staged` and `--unstaged` flags to `git diff` for staged-only and + unstaged-only diffs (*7.12.7.*, *7.12.8.*). + +## 1.21.0 - 2026-10-24 + +- Includes untracked and deleted files in `git diff` report by default + (*7.12.6.*). +- Updates diff rendering: removes spacing between consecutive added or + deleted lines, preserves spacing between added and deleted blocks (*7.12.5.*). + +## 1.20.0 - 2026-10-24 + +- Git commands discover and operate on the root repository from the current + directory (*4.6.*, *7.12.0.*). + ## 1.19.1 - 2026-10-21 - The sectionize-markdown skill ships as diff --git a/SPEC.md b/SPEC.md index 3d94c9b..1e33a7c 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,9 +1,9 @@ --- name: Fiona-Assistant Specification -version: 1.19.1 +version: 1.22.1 title: Project Spec Sheet created: 2026-09-23 -updated: 2026-10-21 +updated: 2026-10-24 type: summary --- @@ -654,8 +654,10 @@ A missing directory on `fix` prints ### 4.6. git -Operates on the git repository at the current directory. Timestamps -are UTC. +Operates on the root git repository discovered from the current +directory. When the current directory is within a git repository +(e.g., `/a/b/c/` where `.git` is at `/a/b/.git`), all git commands +operate on the entire root repository `/a/b/`. Timestamps are UTC. | Command | Stdout on success | | --- | --- | @@ -671,12 +673,22 @@ On failure the tool prints `Error: ` and exits 1. `diff` compares `--head` (default `HEAD`) to `--base`. When `--base` is omitted, the base is the first ref that exists among -`origin/main`, `origin/master`, `main`, and `master`. The report uses -the wiki's opening constellation theme (same resolution as -`wiki graph`). By default the file is -`/tmp/-git-diff-.html`. That path -is listed in the packaged `.gitignore` (`tmp/`). Optional flags: -`--title`, `--subtitle`, `-o` / `--output`, and `--collapsed`. +`origin/main`, `origin/master`, `main`, and `master`. The report +uses the wiki's opening constellation theme when run from a wiki +repository (has `fiona-settings.json` at the git root). Otherwise, +it uses a default dark theme with a light mode toggle and a +minimalist header. Diff rendering removes spacing between consecutive +added lines and between consecutive deleted lines, but preserves +spacing between added and deleted lines. By default the file is +`/tmp/-git-diff-.html`. +That path is listed in the packaged `.gitignore` (`tmp/`). +Optional flags: `--title`, `--subtitle`, `-o` / `--output`, `--collapsed`, +`--staged`, and `--unstaged`. The `--staged` flag shows only staged +changes (compares index to HEAD). The `--unstaged` flag shows only +unstaged changes (compares working tree to index). The flags are +mutually exclusive. Without either flag, the default behavior shows +all changes (compares base to head, including untracked and deleted +files). Commit message: ` `. `save` runs `git add --all` and commits. A clean tree, including @@ -4007,6 +4019,13 @@ Implements section 4.6. `wiki init` writes the repository are never staged by these commands except where `git add --all` respects that ignore file. +- *7.12.0.* Git commands discover and operate on the root repository + from the current directory. A `.git` directory search walks up from + the current working directory. + - *acceptance*: Running `fiona-assistant git diff` from `/a/b/c/` + where `.git` is at `/a/b/.git` produces a diff of the entire `/a/b/` + repository, not just `/a/b/c/`. + - *acceptance*: Running from the root `/a/b/` behaves identically. - *7.12.1.* `save --description note` on a dirty tree creates one commit whose message starts with the UTC timestamp and ends with `note`. @@ -4025,13 +4044,39 @@ respects that ignore file. - *acceptance*: A following `status` prints `Status: clean`. - *7.12.5.* `diff` writes a self-contained HTML file under `tmp/` at the llm-wiki root and prints its path on stdout. The page - includes per-file unified diffs and uses the opening constellation - theme. + includes per-file unified diffs. In a wiki repository it uses + the opening constellation theme. Otherwise it uses a default dark + theme with a light mode toggle button and a minimalist header. - *acceptance*: After `diff`, the printed path exists, lies under `/tmp/`, and `git check-ignore` reports `tmp/` as ignored when the wiki `.gitignore` was seeded from the package. - *acceptance*: The HTML contains a `:root` block whose colors - match the active constellation theme's `background` value. + match the active constellation theme's `background` value when run + from a wiki. + - *acceptance*: The HTML contains a light mode toggle button and uses + dark theme colors by default when run outside a wiki. + - *acceptance*: In non-wiki diff reports, consecutive added lines + have no gap between them, consecutive deleted lines have no gap + between them, and there is spacing between added and deleted + blocks. +- *7.12.6.* `diff` includes untracked and deleted files in the report + by default, with all file diffs collapsed except the first one. + - *acceptance*: Running `diff` when there are untracked files shows + those files in the report. + - *acceptance*: Running `diff` when there are deleted files shows + those files in the report. + - *acceptance*: All file diffs except the first one are collapsed by + default in the HTML output. +- *7.12.7.* `diff --unstaged` writes a report for unstaged changes only. + - *acceptance*: Running `diff --unstaged` with unstaged changes shows + only those unstaged changes in the report. + - *acceptance*: Running `diff --unstaged` with no unstaged changes + produces an empty or minimal report. +- *7.12.8.* `diff --staged` writes a report for staged changes only. + - *acceptance*: Running `diff --staged` with staged changes shows + only those staged changes in the report. + - *acceptance*: Running `diff --staged` with no staged changes + produces an empty or minimal report. ### 7.13. Backup Script diff --git a/src/fiona/__main__.py b/src/fiona/__main__.py index 570301e..ab165f5 100644 --- a/src/fiona/__main__.py +++ b/src/fiona/__main__.py @@ -153,6 +153,16 @@ def main(): action="store_true", help="Start with per-file sections collapsed", ) + git_diff_parser.add_argument( + "--staged", + action="store_true", + help="Diff only staged changes (ignores unstaged changes)", + ) + git_diff_parser.add_argument( + "--unstaged", + action="store_true", + help="Diff only unstaged changes (ignores staged changes)", + ) # fiona-assistant wiki wiki_parser = subparsers.add_parser("wiki", help="Manage wiki directories") @@ -420,6 +430,10 @@ def main(): diff_argv.extend(["--output", args.output]) if args.collapsed: diff_argv.append("--collapsed") + if args.staged: + diff_argv.append("--staged") + if args.unstaged: + diff_argv.append("--unstaged") sys.exit(diff_report.main(diff_argv)) else: git_parser.print_help() diff --git a/src/fiona/gittool/diff_report.py b/src/fiona/gittool/diff_report.py index e2b9382..d9cfd69 100644 --- a/src/fiona/gittool/diff_report.py +++ b/src/fiona/gittool/diff_report.py @@ -1,692 +1,1022 @@ -"""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 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. - - Args: - repo: Git repository root (usually the wiki root). - - Returns: - Wiki root directory (may equal ``repo`` when no settings file exists). - """ - return find_wiki_root(repo) - - -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) -> 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. - - 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``. - - Returns: - CSS rules defining report variables (includes ``:root``). - """ - 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") - - 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. - - Args: - text: Unified diff body for one file. - - Returns: - HTML safe for embedding in ``
``.
-    """
-    parts: list[str] = []
-    for line in text.splitlines():
-        css = classify_diff_line(line)
-        parts.append(f'{html.escape(line)}')
-    return "\n".join(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]]) -> str:
-    """Render nested ``
    `` HTML for the sidebar file tree. - - Generated by AI/LLM: 2026-10-19 - file list with churn counts. - - Args: - tree: Nested path tree from insert_path_in_tree. - stats: Per-file line churn from parse_numstat. - - Returns: - HTML fragment for the sidebar. - """ - - def churn_label(file_path: str) -> str: - added, deleted = stats.get(file_path, (0, 0)) - if added == 0 and deleted == 0: - return "" - return ( - f'' - f'+{added} ' - f'−{deleted}' - f"" - ) - - 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'
  • {html.escape(name)}' - f"{churn_label(value)}
  • " - ) - elif isinstance(value, dict): - inner = walk(value) - items.append( - f'
  • {html.escape(name)}' - f"
      {inner}
  • " - ) - return "".join(items) - - return f'
      {walk(tree)}
    ' - - -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 ``
    `` sections. - - Generated by AI/LLM: 2026-10-19 - collapsible per-file diffs. - - Args: - file_blocks: Paths and diff bodies. - open_details: When True, sections start expanded. - - Returns: - HTML fragment. - """ - open_attr = " open" if open_details else "" - chunks: list[str] = [] - for path, body in file_blocks: - anchor = path_anchor_id(path) - chunks.append( - f'
    ' - f"{html.escape(path)}" - f'
    {colorize_diff(body)}
    ' - f"
    " - ) - 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, -) -> 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 ``
    `` (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. - - 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) - return ( - template.replace("{{PAGE_TITLE}}", html.escape(page_title)) - .replace("{{THEME_CSS}}", theme_css) - .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-.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, -) -> 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. - - Returns: - HTML string, diff range label, and file blocks. - """ - base_ref, head_ref = resolve_base_head(repo, base, head) - commit_hash, subject, body = commit_meta(repo, head_ref) - stat = run_git(repo, "diff", "--stat", f"{base_ref}..{head_ref}") - numstat = run_git(repo, "diff", "--numstat", f"{base_ref}..{head_ref}") - file_stats = parse_numstat(numstat) - raw_diff = run_git(repo, "diff", f"{base_ref}..{head_ref}") - file_blocks = split_diff_by_file(raw_diff) - - page_title = title or f"{repo.name} diff review" - header_lines = [ - f"

    {html.escape(page_title)}

    ", - f"

    {html.escape(subject)}

    ", - ( - f"

    Commit {html.escape(commit_hash[:12])} " - f"vs {html.escape(base_ref[:12] if len(base_ref) > 12 else base_ref)}

    " - ), - ] - if body.strip(): - header_lines.append(f"

    {html.escape(body.strip())}

    ") - if subtitle: - header_lines.append(f"

    {html.escape(subtitle)}

    ") - generated = datetime.datetime.now().strftime("%Y-%m-%d %H:%M") - header_lines.append(f"

    Generated {generated} local time.

    ") - header_body = "\n ".join(header_lines) - - theme_css = theme_css_for_wiki(wiki_root) - html_page = render_report( - page_title, - header_body, - stat, - file_blocks, - file_stats, - theme_css, - open_details, - ) - 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, -) -> 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. - - 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, - ) - 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: /tmp/-git-diff-.html)", - ) - parser.add_argument( - "--collapsed", - action="store_true", - help="Start with per-file sections collapsed", - ) - args = parser.parse_args(argv) - - repo = pathlib.Path.cwd() - if not (repo / ".git").exists(): - print(f"Not a git repo: {repo}", file=sys.stderr) - return 1 - - 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() - - try: - path = write_report( - repo, - out, - args.base, - args.head, - args.title, - args.subtitle, - open_details=not args.collapsed, - ) - except (RuntimeError, FileNotFoundError) as exc: - print(str(exc), file=sys.stderr) - return 1 - - print(path) - return 0 +"""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 '
    ' + + + +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 ``
    ``.
    +    """
    +    result_parts: list[str] = []
    +    prev_css: str | None = None
    +    
    +    for line in text.splitlines():
    +        css = classify_diff_line(line)
    +        span = f'{html.escape(line)}'
    +        
    +        # 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 ``
      `` 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 '🗑️' + elif status == "untracked": + return '📄' + elif status == "added": + return '➕' + else: + return '📝' + + def churn_label(file_path: str) -> str: + added, deleted = stats.get(file_path, (0, 0)) + if added == 0 and deleted == 0: + return "" + return ( + f'' + f'+{added} ' + f'−{deleted}' + f"" + ) + + 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'
    • {status_icon(value)}{html.escape(name)}' + f"{churn_label(value)}
    • " + ) + elif isinstance(value, dict): + inner = walk(value) + items.append( + f'
    • {html.escape(name)}' + f"
        {inner}
    • " + ) + return "".join(items) + + return f'
        {walk(tree)}
      ' + + +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 ``
      `` 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'
      ' + f"{html.escape(path)}" + f'
      {colorize_diff(body)}
      ' + f"
      " + ) + 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 ``
      `` (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-.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"

      {html.escape(page_title)}

      ", + f"

      {html.escape(subject)}

      ", + ( + f"

      Commit {html.escape(commit_hash[:12])} " + f"vs {html.escape(base_ref[:12] if len(base_ref) > 12 else base_ref)}

      " + ), + ] + if body.strip(): + header_lines.append(f"

      {html.escape(body.strip())}

      ") + if subtitle: + header_lines.append(f"

      {html.escape(subtitle)}

      ") + generated = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M") + header_lines.append(f"

      Generated {generated} UTC.

      ") + 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: /tmp/-git-diff-.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 diff --git a/src/fiona/gittool/templates/git-diff-report.template.html b/src/fiona/gittool/templates/git-diff-report.template.html index 9211778..d96b5cc 100644 --- a/src/fiona/gittool/templates/git-diff-report.template.html +++ b/src/fiona/gittool/templates/git-diff-report.template.html @@ -1,237 +1,327 @@ - - - - - - - {{PAGE_TITLE}} - - - -
      - {{HEADER_BODY}} -
      -
      - -
      -
      - - -
      - {{FILES_HTML}} -
      -
      - - - + + + + + + + {{PAGE_TITLE}} + + + +
      +
      + {{HEADER_BODY}} +
      + {{THEME_TOGGLE_HTML}} +
      +
      + +
      +
      + + +
      + {{FILES_HTML}} +
      +
      + + + diff --git a/tests/test_git_diff_report.py b/tests/test_git_diff_report.py index 58323ba..61c09ed 100644 --- a/tests/test_git_diff_report.py +++ b/tests/test_git_diff_report.py @@ -1,111 +1,591 @@ -"""Tests for fiona.gittool.diff_report.""" - -from __future__ import annotations - -import json -import pathlib -import subprocess - -import git -import pytest - -from fiona.gittool import diff_report -from fiona.wiki.ignore import wiki_gitignore_patterns - - -def _configure_test_repo(repo: git.Repo) -> None: - """Set local git identity for commits in tests. - - Generated by CURSOR: 2026-10-19 - isolated git user for pytest. - """ - with repo.config_writer() as config: - config.set_value("user", "email", "fiona-test@example.com") - config.set_value("user", "name", "Fiona Test") - - -@pytest.fixture -def wiki_git_repo(tmp_path: pathlib.Path) -> pathlib.Path: - """Git repo with fiona-settings.json and main + HEAD commits.""" - repo = git.Repo.init(tmp_path) - _configure_test_repo(repo) - settings = { - "fiona": { - "wiki": { - "graph": { - "theme": "night-sky", - } - } - } - } - (tmp_path / "fiona-settings.json").write_text( - json.dumps(settings), - encoding="utf-8", - ) - (tmp_path / "README.md").write_text("base\n", encoding="utf-8") - repo.index.add(["fiona-settings.json", "README.md"]) - repo.index.commit("base on main") - # Keep ``main`` at the first commit so HEAD can advance for a non-empty diff. - repo.create_head("main") - (tmp_path / "README.md").write_text("base\nchanged\n", encoding="utf-8") - repo.index.add(["README.md"]) - repo.index.commit("feature commit") - return tmp_path - - -def test_wiki_gitignore_includes_tmp() -> None: - """SPEC 7.12.5: packaged ignore lists wiki tmp/.""" - patterns = wiki_gitignore_patterns() - assert "tmp/" in patterns - - -def test_resolve_default_base_uses_main(wiki_git_repo: pathlib.Path) -> None: - """Default base is main when it exists.""" - assert diff_report.resolve_default_base(wiki_git_repo) == "main" - - -def test_theme_css_uses_constellation(wiki_git_repo: pathlib.Path) -> None: - """HTML theme CSS reflects night-sky background.""" - css = diff_report.theme_css_for_wiki(wiki_git_repo) - assert "--bg: #070b14" in css - - -def test_write_report_under_tmp(wiki_git_repo: pathlib.Path) -> None: - """Default output path is wiki tmp/ and HTML includes diff content.""" - out = diff_report.default_output_path(wiki_git_repo, wiki_git_repo, "HEAD") - assert out.parent == wiki_git_repo / "tmp" - path = diff_report.write_report( - wiki_git_repo, - out, - base="main", - head="HEAD", - title=None, - subtitle=None, - open_details=True, - ) - text = path.read_text(encoding="utf-8") - assert "changed" in text - assert "night-sky" not in text # theme name is not embedded; colors are - assert "--bg: #070b14" in text - - -def test_main_prints_path(wiki_git_repo: pathlib.Path, monkeypatch) -> None: - """CLI exits 0 and prints the report path.""" - monkeypatch.chdir(wiki_git_repo) - code = diff_report.main(["--base", "main"]) - assert code == 0 - - -def test_git_check_ignore_tmp(wiki_git_repo: pathlib.Path) -> None: - """tmp/ is ignored after ensure_wiki_gitignore.""" - from fiona.wiki.ignore import ensure_wiki_gitignore - - ensure_wiki_gitignore(wiki_git_repo) - (wiki_git_repo / "tmp").mkdir() - report = wiki_git_repo / "tmp" / "sample.html" - report.write_text("", encoding="utf-8") - result = subprocess.run( - ["git", "check-ignore", "-q", "tmp/sample.html"], - cwd=wiki_git_repo, - check=False, - ) - assert result.returncode == 0 +"""Tests for fiona.gittool.diff_report.""" + +from __future__ import annotations + +import json +import pathlib +import subprocess + +import git +import pytest + +from fiona.gittool import diff_report +from fiona.wiki.ignore import wiki_gitignore_patterns + + +def _configure_test_repo(repo: git.Repo) -> None: + """Set local git identity for commits in tests. + + Generated by CURSOR: 2026-10-19 - isolated git user for pytest. + """ + with repo.config_writer() as config: + config.set_value("user", "email", "fiona-test@example.com") + config.set_value("user", "name", "Fiona Test") + + +@pytest.fixture +def wiki_git_repo(tmp_path: pathlib.Path) -> pathlib.Path: + """Git repo with fiona-settings.json and main + HEAD commits.""" + repo = git.Repo.init(tmp_path) + _configure_test_repo(repo) + settings = { + "fiona": { + "wiki": { + "graph": { + "theme": "night-sky", + } + } + } + } + (tmp_path / "fiona-settings.json").write_text( + json.dumps(settings), + encoding="utf-8", + ) + (tmp_path / "README.md").write_text("base\n", encoding="utf-8") + repo.index.add(["fiona-settings.json", "README.md"]) + repo.index.commit("base on main") + # Keep ``main`` at the first commit so HEAD can advance for a non-empty diff. + repo.create_head("main") + (tmp_path / "README.md").write_text("base\nchanged\n", encoding="utf-8") + repo.index.add(["README.md"]) + repo.index.commit("feature commit") + return tmp_path + + +def test_wiki_gitignore_includes_tmp() -> None: + """SPEC 7.12.5: packaged ignore lists wiki tmp/.""" + patterns = wiki_gitignore_patterns() + assert "tmp/" in patterns + + +def test_resolve_default_base_uses_main(wiki_git_repo: pathlib.Path) -> None: + """Default base is main when it exists.""" + assert diff_report.resolve_default_base(wiki_git_repo) == "main" + + +def test_theme_css_uses_constellation(wiki_git_repo: pathlib.Path) -> None: + """HTML theme CSS reflects night-sky background.""" + css = diff_report.theme_css_for_wiki(wiki_git_repo) + assert "--bg: #070b14" in css + + +def test_write_report_under_tmp(wiki_git_repo: pathlib.Path) -> None: + """Default output path is wiki tmp/ and HTML includes diff content.""" + out = diff_report.default_output_path(wiki_git_repo, wiki_git_repo, "HEAD") + assert out.parent == wiki_git_repo / "tmp" + path = diff_report.write_report( + wiki_git_repo, + out, + base="main", + head="HEAD", + title=None, + subtitle=None, + open_details=True, + ) + text = path.read_text(encoding="utf-8") + assert "changed" in text + assert "night-sky" not in text # theme name is not embedded; colors are + assert "--bg: #070b14" in text + + +def test_main_prints_path(wiki_git_repo: pathlib.Path, monkeypatch) -> None: + """CLI exits 0 and prints the report path.""" + monkeypatch.chdir(wiki_git_repo) + code = diff_report.main(["--base", "main"]) + assert code == 0 + + +def test_git_check_ignore_tmp(wiki_git_repo: pathlib.Path) -> None: + """tmp/ is ignored after ensure_wiki_gitignore.""" + from fiona.wiki.ignore import ensure_wiki_gitignore + + ensure_wiki_gitignore(wiki_git_repo) + (wiki_git_repo / "tmp").mkdir() + report = wiki_git_repo / "tmp" / "sample.html" + report.write_text("", encoding="utf-8") + result = subprocess.run( + ["git", "check-ignore", "-q", "tmp/sample.html"], + cwd=wiki_git_repo, + check=False, + ) + assert result.returncode == 0 + + +def test_find_git_root_from_subdirectory(tmp_path: pathlib.Path) -> None: + """SPEC 7.12.0: find_git_root discovers root from subdirectory.""" + # Create a git repo at the root + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file.txt").write_text("root file", encoding="utf-8") + repo.index.add(["file.txt"]) + repo.index.commit("initial commit") + + # Create a subdirectory + subdir = repo_path / "subdir" + subdir.mkdir() + + # The function should find the root even when called from subdirectory + result = diff_report.find_git_root(subdir) + assert result == repo_path + + +def test_main_from_subdirectory(tmp_path: pathlib.Path, monkeypatch) -> None: + """SPEC 7.12.0: main() uses git root when run from subdirectory.""" + # Create a git repo at the root + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + + settings = { + "fiona": { + "wiki": { + "graph": { + "theme": "colorful", + } + } + } + } + (repo_path / "fiona-settings.json").write_text( + json.dumps(settings), + encoding="utf-8", + ) + (repo_path / "file.txt").write_text("original\n", encoding="utf-8") + repo.index.add(["fiona-settings.json", "file.txt"]) + repo.index.commit("initial commit") + repo.create_head("main") + + # Create a subdirectory and change to it + subdir = repo_path / "subdir" + subdir.mkdir() + monkeypatch.chdir(subdir) + + # Modify a file in the root + (repo_path / "file.txt").write_text("original\nmodified\n", encoding="utf-8") + repo.index.add(["file.txt"]) + repo.index.commit("second commit") + + # Run diff from subdirectory - should work and find the root repo + code = diff_report.main(["--base", "main"]) + assert code == 0 + + +def test_theme_light_for_non_wiki(tmp_path: pathlib.Path) -> None: + """SPEC 7.12.5: non-wiki repos use default light theme with dark mode toggle.""" + # Create a git repo WITHOUT fiona-settings.json + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file.txt").write_text("content", encoding="utf-8") + repo.index.add(["file.txt"]) + repo.index.commit("initial") + + # Generate report + out = tmp_path / "report.html" + path = diff_report.write_report( + repo_path, + out, + base="HEAD", + head="HEAD", + title="Test", + subtitle=None, + open_details=True, + ) + + text = path.read_text(encoding="utf-8") + # Check for dark theme colors (default) + assert "--bg: #1a1a1a;" in text + assert "--card: #2d2d2d;" in text + # Check for light mode toggle + assert "Toggle Light Mode" in text + # Check for theme CSS + assert '[data-theme="dark"]' in text + assert '[data-theme="light"]' in text + + +def test_theme_wiki_uses_wiki_theme(wiki_git_repo: pathlib.Path) -> None: + """SPEC 7.12.5: wiki repos use their own constellation theme.""" + out = diff_report.default_output_path(wiki_git_repo, wiki_git_repo, "HEAD") + path = diff_report.write_report( + wiki_git_repo, + out, + base="main", + head="HEAD", + title=None, + subtitle=None, + open_details=True, + ) + text = path.read_text(encoding="utf-8") + # Night-sky theme has dark background + assert "--bg: #070b14" in text + # No toggle button for wikis + assert "Toggle Light Mode" not in text + + +def test_collapsed_file_diffs_except_first(tmp_path: pathlib.Path) -> None: + """SPEC 7.12.6: All file diffs except the first are collapsed by default.""" + # Create a git repo with multiple changed files + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file1.txt").write_text("file1\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("file2\n", encoding="utf-8") + (repo_path / "file3.txt").write_text("file3\n", encoding="utf-8") + repo.index.add(["file1.txt", "file2.txt", "file3.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Modify multiple files + (repo_path / "file1.txt").write_text("file1\nmodified1\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("file2\nmodified2\n", encoding="utf-8") + (repo_path / "file3.txt").write_text("file3\nmodified3\n", encoding="utf-8") + repo.index.add(["file1.txt", "file2.txt", "file3.txt"]) + repo.index.commit("changes") + + # Generate report with open_details=True + out = tmp_path / "report.html" + path = diff_report.write_report( + repo_path, + out, + base="main", + head="HEAD", + title=None, + subtitle=None, + open_details=True, # Even with open_details=True, only first should be open + ) + + text = path.read_text(encoding="utf-8") + from bs4 import BeautifulSoup + soup = BeautifulSoup(text, 'html.parser') + details = soup.find_all('details', class_='file') + + # Should have 3 file sections + assert len(details) == 3 + + # Only the first one should be open + assert 'open' in details[0].attrs + assert 'open' not in details[1].attrs + assert 'open' not in details[2].attrs + + +def test_untracked_files_included_in_diff(tmp_path: pathlib.Path) -> None: + """SPEC 7.12.6: Untracked files are included in the diff report.""" + # Create a git repo + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "tracked.txt").write_text("tracked\n", encoding="utf-8") + repo.index.add(["tracked.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Add an untracked file + (repo_path / "untracked.txt").write_text("untracked content\n", encoding="utf-8") + + # Generate report + out = tmp_path / "report.html" + path = diff_report.write_report( + repo_path, + out, + base="main", + head="HEAD", + title=None, + subtitle=None, + open_details=True, + ) + + text = path.read_text(encoding="utf-8") + + # Untracked file should be in the report + assert "untracked.txt" in text + # Should have a diff section for it + assert "file-untracked-txt" in text or "untracked.txt" in text + + +def test_deleted_files_included_in_diff(tmp_path: pathlib.Path) -> None: + """SPEC 7.12.6: Deleted files are included in the diff report.""" + # Create a git repo with a file + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "to_delete.txt").write_text("will be deleted\n", encoding="utf-8") + repo.index.add(["to_delete.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Delete the file + (repo_path / "to_delete.txt").unlink() + repo.index.remove(["to_delete.txt"]) + repo.index.commit("deleted file") + + # Generate report + out = tmp_path / "report.html" + path = diff_report.write_report( + repo_path, + out, + base="main", + head="HEAD", + title=None, + subtitle=None, + open_details=True, + ) + + text = path.read_text(encoding="utf-8") + + # Deleted file should be in the report + assert "to_delete.txt" in text + # Should have a diff section for it + assert "file-to-delete-txt" in text or "to_delete.txt" in text + + +def test_diff_unstaged_flag(tmp_path: pathlib.Path, monkeypatch) -> None: + """SPEC 7.12.7: --unstaged flag shows only unstaged changes.""" + # Create a git repo with a file + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file1.txt").write_text("original\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("original\n", encoding="utf-8") + repo.index.add(["file1.txt", "file2.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Stage file1 and modify file2 (unstaged) + (repo_path / "file1.txt").write_text("staged change\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("unstaged change\n", encoding="utf-8") + repo.index.add(["file1.txt"]) + + monkeypatch.chdir(repo_path) + + # Run diff with --unstaged flag + code = diff_report.main(["--unstaged"]) + assert code == 0 + + # Check the output file + out = diff_report.default_output_path(repo_path, repo_path, "HEAD") + text = out.read_text(encoding="utf-8") + + # Should include unstaged file2 changes + assert "unstaged change" in text + # Should NOT include staged file1 changes (check for the full diff line to avoid substring matches) + assert "+staged change" not in text and "-staged change" not in text + + +def test_diff_unstaged_includes_untracked_files(tmp_path: pathlib.Path, monkeypatch) -> None: + """SPEC 7.12.7: --unstaged flag includes untracked files.""" + # Create a git repo with a tracked file + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + settings = { + "fiona": { + "wiki": { + "graph": { + "theme": "night-sky", + } + } + } + } + (repo_path / "fiona-settings.json").write_text( + json.dumps(settings), + encoding="utf-8", + ) + (repo_path / "tracked.txt").write_text("original\n", encoding="utf-8") + repo.index.add(["fiona-settings.json", "tracked.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Modify tracked file (unstaged) and add untracked file + (repo_path / "tracked.txt").write_text("modified\n", encoding="utf-8") + (repo_path / "untracked.txt").write_text("new content\n", encoding="utf-8") + + monkeypatch.chdir(repo_path) + + # Run diff with --unstaged flag + code = diff_report.main(["--unstaged"]) + assert code == 0 + + # Check the output file + out = diff_report.default_output_path(repo_path, repo_path, "HEAD") + text = out.read_text(encoding="utf-8") + + # Should include both modified tracked file and untracked file + assert "modified" in text + assert "new content" in text + assert "untracked.txt" in text + # Check for file status icons + assert "📄" in text # untracked file icon + assert "📝" in text # modified file icon + + +def test_file_status_icons_in_diff(tmp_path: pathlib.Path, monkeypatch) -> None: + """Test that file status icons (🗑️, 📄, 📝, ➕) appear correctly in diff report.""" + # Create a git repo + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + settings = { + "fiona": { + "wiki": { + "graph": { + "theme": "night-sky", + } + } + } + } + (repo_path / "fiona-settings.json").write_text( + json.dumps(settings), + encoding="utf-8", + ) + + # Create initial files + (repo_path / "modified.txt").write_text("original\n", encoding="utf-8") + (repo_path / "deleted.txt").write_text("to delete\n", encoding="utf-8") + repo.index.add(["fiona-settings.json", "modified.txt", "deleted.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Modify one file, delete another, and add an untracked file + (repo_path / "modified.txt").write_text("modified content\n", encoding="utf-8") + (repo_path / "deleted.txt").unlink() + (repo_path / "untracked.txt").write_text("new file\n", encoding="utf-8") + + monkeypatch.chdir(repo_path) + + # Run diff in default mode + code = diff_report.main([]) + assert code == 0 + + # Check the output file + out = diff_report.default_output_path(repo_path, repo_path, "HEAD") + text = out.read_text(encoding="utf-8") + + # Check for file status icons + assert "🗑️" in text, "Deleted file should have trash icon" + assert "📄" in text, "Untracked file should have file icon" + assert "📝" in text, "Modified file should have pencil icon" + + +def test_file_status_icons_in_staged_mode(tmp_path: pathlib.Path, monkeypatch) -> None: + """Test that added files show plus icon in staged mode.""" + # Create a git repo + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + settings = { + "fiona": { + "wiki": { + "graph": { + "theme": "night-sky", + } + } + } + } + (repo_path / "fiona-settings.json").write_text( + json.dumps(settings), + encoding="utf-8", + ) + + (repo_path / "existing.txt").write_text("original\n", encoding="utf-8") + repo.index.add(["fiona-settings.json", "existing.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Add a new file and stage it + (repo_path / "new.txt").write_text("new file\n", encoding="utf-8") + repo.index.add(["new.txt"]) + + monkeypatch.chdir(repo_path) + + # Run diff with --staged flag + code = diff_report.main(["--staged"]) + assert code == 0 + + # Check the output file + out = diff_report.default_output_path(repo_path, repo_path, "HEAD") + text = out.read_text(encoding="utf-8") + + # Check for plus icon for added file + assert "➕" in text, "Added file should have plus icon" + assert "new.txt" in text + + +def test_diff_staged_flag(tmp_path: pathlib.Path, monkeypatch) -> None: + """SPEC 7.12.8: --staged flag shows only staged changes.""" + # Create a git repo with a file + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file1.txt").write_text("original\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("original\n", encoding="utf-8") + repo.index.add(["file1.txt", "file2.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Stage file1 and modify file2 (unstaged) + (repo_path / "file1.txt").write_text("staged change\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("unstaged change\n", encoding="utf-8") + repo.index.add(["file1.txt"]) + + monkeypatch.chdir(repo_path) + + # Run diff with --staged flag + code = diff_report.main(["--staged"]) + assert code == 0 + + # Check the output file + out = diff_report.default_output_path(repo_path, repo_path, "HEAD") + text = out.read_text(encoding="utf-8") + + # Should include staged file1 changes + assert "+staged change" in text or "-staged change" in text + # Should NOT include unstaged file2 changes (check for the full diff line to avoid substring matches) + assert "+unstaged change" not in text and "-unstaged change" not in text + + +def test_diff_default_behavior(tmp_path: pathlib.Path, monkeypatch) -> None: + """SPEC 7.12.5: Default behavior (no flag) shows all changes.""" + # Create a git repo with files + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file1.txt").write_text("original\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("original\n", encoding="utf-8") + repo.index.add(["file1.txt", "file2.txt"]) + repo.index.commit("initial") + repo.create_head("main") + + # Stage file1 and modify file2 (unstaged) + (repo_path / "file1.txt").write_text("staged change\n", encoding="utf-8") + (repo_path / "file2.txt").write_text("unstaged change\n", encoding="utf-8") + repo.index.add(["file1.txt"]) + + monkeypatch.chdir(repo_path) + + # Run diff without flags + code = diff_report.main([]) + assert code == 0 + + # Check the output file + out = diff_report.default_output_path(repo_path, repo_path, "HEAD") + text = out.read_text(encoding="utf-8") + + # Should include both staged and unstaged changes (check for full diff lines to avoid substring matches) + assert "+staged change" in text or "-staged change" in text + assert "+unstaged change" in text or "-unstaged change" in text + + +def test_diff_staged_and_unstaged_mutually_exclusive(tmp_path: pathlib.Path, monkeypatch) -> None: + """SPEC 7.12.7/7.12.8: --staged and --unstaged cannot be used together.""" + repo_path = tmp_path / "myrepo" + repo = git.Repo.init(repo_path) + _configure_test_repo(repo) + (repo_path / "file.txt").write_text("content\n", encoding="utf-8") + repo.index.add(["file.txt"]) + repo.index.commit("initial") + + monkeypatch.chdir(repo_path) + + # Run diff with both flags - should fail + code = diff_report.main(["--staged", "--unstaged"]) + assert code == 1