diff --git a/.gitignore b/.gitignore index 9c4f262..c44148f 100644 --- a/.gitignore +++ b/.gitignore @@ -57,4 +57,7 @@ Thumbs.db *.pyd *fiona.log -*wiki_graph.html \ No newline at end of file +*wiki_graph.html + +# Generated review artifacts (git diff HTML, scratch exports) +tmp/ \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 271e4c2..40666ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,9 @@ --- name: changelog -version: 1.2.0 +version: 1.2.1 title: Changelog created: 2026-10-08 -updated: 2026-10-15 +updated: 2026-10-19 type: summary --- @@ -13,6 +13,12 @@ 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.18.1 - 2026-10-19 + +- `fiona-assistant git diff` writes a constellation-themed HTML + report under the wiki `tmp/` directory (*4.6*, *7.12.5*). The + packaged wiki `.gitignore` now lists `tmp/`. + ## 1.18.0 - 2026-10-15 - Adds skill memory to the template (*3.5.*): the `memory` skill diff --git a/SPEC.md b/SPEC.md index e9d4927..5dea3a5 100644 --- a/SPEC.md +++ b/SPEC.md @@ -1,9 +1,9 @@ --- name: Fiona-Assistant Specification -version: 1.18.0 +version: 1.18.1 title: Project Spec Sheet created: 2026-09-23 -updated: 2026-10-15 +updated: 2026-10-19 type: summary --- @@ -665,9 +665,19 @@ are UTC. | `clean` | `Working tree cleaned. All changes discarded.` | | `undo` | `Undo to: ` | | `status` | `Status: clean` or `Status: dirty`, then `git status` | +| `diff` | Absolute path of the HTML file written under the wiki `tmp/` directory | 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`. + Commit message: ` `. `save` runs `git add --all` and commits. A clean tree, including no untracked files, raises `Working tree is clean. Nothing to commit.` @@ -4013,6 +4023,15 @@ respects that ignore file. - *acceptance*: The HEAD sha is unchanged. - *7.12.4.* `clean` leaves `git status` empty of changes. - *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. + - *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. ### 7.13. Backup Script diff --git a/pyproject.toml b/pyproject.toml index 692566b..cd02070 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "fiona-assistant" -version = "1.16.0" +version = "1.17.0" description = "Tools for managing the LLM wiki." authors = [{name = "nvaldeziii"}] readme = "README.md" @@ -52,6 +52,7 @@ fiona = [ "data/llm_wiki/**/*", "data/default.gitignore", "wiki/templates/*", + "gittool/templates/*", ] [tool.pytest.ini_options] diff --git a/src/fiona/data/default.gitignore b/src/fiona/data/default.gitignore index 9c4f262..c44148f 100644 --- a/src/fiona/data/default.gitignore +++ b/src/fiona/data/default.gitignore @@ -57,4 +57,7 @@ Thumbs.db *.pyd *fiona.log -*wiki_graph.html \ No newline at end of file +*wiki_graph.html + +# Generated review artifacts (git diff HTML, scratch exports) +tmp/ \ No newline at end of file diff --git a/src/fiona/gittool/diff_report.py b/src/fiona/gittool/diff_report.py new file mode 100644 index 0000000..58ba9ac --- /dev/null +++ b/src/fiona/gittool/diff_report.py @@ -0,0 +1,690 @@ +"""Generate a constellation-themed HTML report from ``git diff``. + +Generated by CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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("+++") or 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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", f"--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 CURSOR: 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 CURSOR: 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 CURSOR: 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 CURSOR: 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(".").resolve() + 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 diff --git a/src/fiona/gittool/git_tool.py b/src/fiona/gittool/git_tool.py index e554308..b25ff85 100644 --- a/src/fiona/gittool/git_tool.py +++ b/src/fiona/gittool/git_tool.py @@ -349,6 +349,30 @@ def main(): # pragma: no cover # status subcommand subparsers.add_parser("status", help="Show git status") + # diff subcommand + diff_parser = subparsers.add_parser( + "diff", + help="Write constellation-themed HTML diff under wiki tmp/", + ) + diff_parser.add_argument("--base", help="Base revision (default: origin/main or main/master)") + diff_parser.add_argument("--head", default="HEAD", help="Head revision (default: HEAD)") + diff_parser.add_argument("--title", help="Report H1 / page title") + diff_parser.add_argument( + "--subtitle", + help="Extra header line (e.g. temporary review before push)", + ) + diff_parser.add_argument( + "-o", + "--output", + type=pathlib.Path, + help="Output HTML path (default: /tmp/-git-diff-.html)", + ) + diff_parser.add_argument( + "--collapsed", + action="store_true", + help="Start with per-file sections collapsed", + ) + args = parser.parse_args() setup_logging() @@ -378,6 +402,23 @@ def main(): # pragma: no cover elif args.subcommand == "status": status = git_tool.status() print(status) + elif args.subcommand == "diff": + from fiona.gittool import diff_report + + diff_argv: list[str] = [] + if args.base: + diff_argv.extend(["--base", args.base]) + if args.head != "HEAD": + diff_argv.extend(["--head", args.head]) + if args.title: + diff_argv.extend(["--title", args.title]) + if args.subtitle: + diff_argv.extend(["--subtitle", args.subtitle]) + if args.output is not None: + diff_argv.extend(["--output", str(args.output)]) + if args.collapsed: + diff_argv.append("--collapsed") + raise SystemExit(diff_report.main(diff_argv)) except Exception as e: print(f"Error: {e}") raise SystemExit(1) from e diff --git a/src/fiona/gittool/templates/git-diff-report.template.html b/src/fiona/gittool/templates/git-diff-report.template.html new file mode 100644 index 0000000..3cb7aa3 --- /dev/null +++ b/src/fiona/gittool/templates/git-diff-report.template.html @@ -0,0 +1,237 @@ + + + + + + + {{PAGE_TITLE}} + + + +
    + {{HEADER_BODY}} +
    +
    + +
    +
    + + +
    + {{FILES_HTML}} +
    +
    + + + diff --git a/tests/test_bootstrap_install.py b/tests/test_bootstrap_install.py index d10a8ec..d633473 100644 --- a/tests/test_bootstrap_install.py +++ b/tests/test_bootstrap_install.py @@ -10,7 +10,7 @@ import subprocess import pytest -# AI/LLM: Linux CI images (GitLab python:) have no PowerShell. +# CURSOR: Linux CI images (GitLab python:) have no PowerShell. POWERSHELL = shutil.which("powershell") or shutil.which("pwsh") requires_powershell = pytest.mark.skipif( not POWERSHELL, diff --git a/tests/test_git_diff_report.py b/tests/test_git_diff_report.py new file mode 100644 index 0000000..58323ba --- /dev/null +++ b/tests/test_git_diff_report.py @@ -0,0 +1,111 @@ +"""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 diff --git a/tests/test_gittool.py b/tests/test_gittool.py index e4968d1..c3d8b40 100644 --- a/tests/test_gittool.py +++ b/tests/test_gittool.py @@ -11,7 +11,7 @@ from fiona.gittool.git_tool import GitTool def _configure_test_repo(repo: git.Repo) -> None: """Set local git identity so commits and tags work without global config. - Generated by AI/LLM: 2026-10-14 - GitLab CI runs as root without user.name. + Generated by CURSOR: 2026-10-14 - GitLab CI runs as root without user.name. """ with repo.config_writer() as config: config.set_value("user", "email", "fiona-test@example.com")