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 <vibe@mistral.ai>

This commit is contained in:
nvaldez
2026-10-24 14:11:21 +02:00
parent a907e7da79
commit 983198b8b4
6 changed files with 2035 additions and 1055 deletions
+23 -2
View File
@@ -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
+58 -13
View File
@@ -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: <message>` 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
`<wiki-root>/tmp/<repo-name>-git-diff-<short-head>.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
`<wiki-root>/tmp/<repo-name>-git-diff-<short-head>.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: `<YYYY-MM-DD HH:MM:SS> <description>`.
`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
`<wiki-root>/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
+14
View File
@@ -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()
+379 -49
View File
@@ -24,6 +24,47 @@ from fiona.wiki.graph_generator import (
_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.
@@ -124,6 +165,7 @@ 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).
@@ -131,7 +173,39 @@ def wiki_root_for_repo(repo: pathlib.Path) -> pathlib.Path:
Returns:
Wiki root directory (may equal ``repo`` when no settings file exists).
"""
return find_wiki_root(repo)
# Check if the repo itself is a wiki (has fiona-settings.json)
settings_file = repo / "fiona-settings.json"
if settings_file.is_file():
return find_wiki_root(repo)
# If the git repo is not a wiki, use the git root for tmp/ output
return repo
def is_wiki_repo(repo: pathlib.Path) -> bool:
"""Check if a directory is a wiki repository (has fiona-settings.json).
Args:
repo: Path to check.
Returns:
True if the directory contains fiona-settings.json.
"""
return (repo / "fiona-settings.json").is_file()
def theme_toggle_html(is_wiki: bool) -> str:
"""Generate HTML for the theme toggle button.
Args:
is_wiki: Whether this is a wiki repository.
Returns:
HTML string for the theme toggle button, or empty string for wikis.
"""
if is_wiki:
return ""
return '<div class="theme-toggle"><button type="button" id="theme-toggle">Toggle Light Mode</button></div>'
def _css_color(value: object, fallback: str) -> str:
@@ -151,10 +225,11 @@ def _css_color(value: object, fallback: str) -> str:
return fallback
def theme_css_for_wiki(wiki_root: pathlib.Path) -> str:
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``).
@@ -165,38 +240,58 @@ def theme_css_for_wiki(wiki_root: pathlib.Path) -> str:
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``).
"""
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 = {}
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 {}
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")
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};
@@ -251,17 +346,36 @@ def colorize_diff(text: str) -> str:
Generated by AI/LLM: 2026-10-19 - escape and wrap diff lines.
Removes spacing between consecutive added lines and between consecutive
deleted lines, but preserves spacing between added and deleted lines.
Args:
text: Unified diff body for one file.
Returns:
HTML safe for embedding in ``<pre>``.
"""
parts: list[str] = []
result_parts: list[str] = []
prev_css: str | None = None
for line in text.splitlines():
css = classify_diff_line(line)
parts.append(f'<span class="{css}">{html.escape(line)}</span>')
return "\n".join(parts)
span = f'<span class="{css}">{html.escape(line)}</span>'
# For diff-add and diff-del, concatenate consecutive spans without newlines
if css in ('diff-add', 'diff-del') and css == prev_css:
# Append to last part without newline
if result_parts:
result_parts[-1] = result_parts[-1] + span
else:
result_parts.append(span)
else:
# Add as new part with newline
result_parts.append(span)
prev_css = css
return "\n".join(result_parts)
def path_anchor_id(path: str) -> str:
@@ -322,18 +436,32 @@ def insert_path_in_tree(tree: dict, path: str) -> None:
cursor[parts[-1]] = path
def render_file_tree(tree: dict, stats: dict[str, tuple[int, int]]) -> str:
def render_file_tree(tree: dict, stats: dict[str, tuple[int, int]], file_status: dict[str, str] | None = None) -> str:
"""Render nested ``<ul>`` HTML for the sidebar file tree.
Generated by AI/LLM: 2026-10-19 - file list with churn counts.
Generated by AI/LLM: 2026-10-19 - file list with churn counts and status icons.
Args:
tree: Nested path tree from insert_path_in_tree.
stats: Per-file line churn from parse_numstat.
file_status: Optional dict mapping file paths to their status ('deleted', 'untracked', 'modified').
Returns:
HTML fragment for the sidebar.
"""
if file_status is None:
file_status = {}
def status_icon(file_path: str) -> str:
status = file_status.get(file_path, "modified")
if status == "deleted":
return '<span class="file-icon" title="Deleted">🗑️</span>'
elif status == "untracked":
return '<span class="file-icon" title="Untracked">📄</span>'
elif status == "added":
return '<span class="file-icon" title="Added">➕</span>'
else:
return '<span class="file-icon" title="Modified">📝</span>'
def churn_label(file_path: str) -> str:
added, deleted = stats.get(file_path, (0, 0))
@@ -353,7 +481,7 @@ def render_file_tree(tree: dict, stats: dict[str, tuple[int, int]]) -> str:
if isinstance(value, str):
anchor = path_anchor_id(value)
items.append(
f'<li class="leaf"><a href="#{anchor}">{html.escape(name)}</a>'
f'<li class="leaf"><a href="#{anchor}">{status_icon(value)}{html.escape(name)}</a>'
f"{churn_label(value)}</li>"
)
elif isinstance(value, dict):
@@ -367,6 +495,79 @@ def render_file_tree(tree: dict, stats: dict[str, tuple[int, int]]) -> str:
return f'<ul class="file-tree">{walk(tree)}</ul>'
def get_untracked_files(repo: pathlib.Path) -> list[str]:
"""Get list of untracked files in the repository.
Args:
repo: Git repository root.
Returns:
List of untracked file paths relative to repo.
"""
try:
output = run_git(repo, "ls-files", "--others", "--exclude-standard")
return [p.strip() for p in output.splitlines() if p.strip()]
except RuntimeError:
return []
def get_deleted_files(repo: pathlib.Path, base_ref: str, head_ref: str) -> list[str]:
"""Get list of deleted files between base and head.
Args:
repo: Git repository root.
base_ref: Base reference.
head_ref: Head reference.
Returns:
List of deleted file paths relative to repo.
"""
try:
diff_range = f"{base_ref}..{head_ref}"
output = run_git(repo, "diff", "--name-only", "--diff-filter=D", diff_range)
return [p.strip() for p in output.splitlines() if p.strip()]
except RuntimeError:
return []
def create_file_diff(repo: pathlib.Path, path: str) -> str:
"""Create a diff for a single file (untracked or deleted).
For untracked files, show as new file (all additions).
For deleted files, show as removed file (all deletions).
Args:
repo: Git repository root.
path: File path relative to repo.
Returns:
Unified diff text for the file.
"""
file_path = repo / path
if not file_path.exists():
# Deleted file - show as all deletions
# Use git show to get the last version of the file
try:
content = run_git(repo, "show", f"{path}")
lines = [f"--- a/{path}", "+++ /dev/null", "@@ -1 +0,0 @@"]
for line in content.splitlines():
lines.append(f"-{line}")
return "\n".join(lines)
except RuntimeError:
return f"--- a/{path}\n+++ /dev/null\n"
else:
# Untracked file - show as all additions
try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()
lines = ["--- /dev/null", f"+++ b/{path}", "@@ -0,0 +1 @@"]
for line in content.splitlines():
lines.append(f"+{line}")
return "\n".join(lines)
except (OSError, UnicodeDecodeError):
return "--- /dev/null\n" f"+++ b/{path}\n"
def split_diff_by_file(raw_diff: str) -> list[tuple[str, str]]:
"""Split ``git diff`` output into (path, body) pairs.
@@ -394,17 +595,20 @@ def build_files_html(file_blocks: list[tuple[str, str]], open_details: bool) ->
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.
open_details: When True, sections start expanded (overridden to only first).
Returns:
HTML fragment.
"""
open_attr = " open" if open_details else ""
chunks: list[str] = []
for path, body in file_blocks:
for idx, (path, body) in enumerate(file_blocks):
anchor = path_anchor_id(path)
# Only the first file diff is open by default
open_attr = " open" if (open_details and idx == 0) else ""
chunks.append(
f'<details class="file" id="{anchor}"{open_attr}>'
f"<summary><code>{html.escape(path)}</code></summary>"
@@ -444,6 +648,8 @@ def render_report(
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.
@@ -457,6 +663,8 @@ def render_report(
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.
@@ -466,10 +674,11 @@ def render_report(
tree: dict = {}
for path, _body in file_blocks:
insert_path_in_tree(tree, path)
tree_html = render_file_tree(tree, file_stats)
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)))
@@ -524,6 +733,8 @@ def generate_report(
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.
@@ -537,18 +748,111 @@ def generate_report(
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)
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}")
# 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)
raw_diff = run_git(repo, "diff", f"{base_ref}..{head_ref}")
file_blocks = split_diff_by_file(raw_diff)
# Track file status: 'modified', 'deleted', 'untracked', or 'added'
file_status: dict[str, str] = {}
# Helper function to detect file status from diff
def detect_file_status(diff_body: str) -> str:
lines = diff_body.strip().split("\n")
if not lines:
return "modified"
# Check for git diff deletion marker
if lines[0].startswith("deleted file mode"):
return "deleted"
# Check for git diff addition marker
if lines[0].startswith("new file mode"):
return "added"
# Check the first two lines for diff headers
if len(lines) >= 2:
if lines[0].startswith("--- a/") and lines[1] == "+++ /dev/null":
return "deleted"
if lines[0] == "--- /dev/null" and lines[1].startswith("+++ b/"):
return "added"
# Default to modified for standard diffs
return "modified"
# Mark files from the main diff based on their diff content
for path, body in file_blocks:
file_status[path] = detect_file_status(body)
# Include additional files based on mode
if staged_only:
# For staged mode, don't include untracked files (they're not staged)
# Deleted files that are staged will be included in the git diff --cached output
pass
elif unstaged_only:
# For unstaged mode, include untracked files (they are also unstaged)
untracked_files = get_untracked_files(repo)
for untracked_path in untracked_files:
if not any(path == untracked_path for path, _ in file_blocks):
diff_content = create_file_diff(repo, untracked_path)
file_blocks.append((untracked_path, diff_content))
file_stats[untracked_path] = (0, 0)
file_status[untracked_path] = "untracked"
else:
# Default mode: include untracked and deleted files
untracked_files = get_untracked_files(repo)
deleted_files = get_deleted_files(repo, base_ref, head_ref)
# Add untracked files as new files
for untracked_path in untracked_files:
if not any(path == untracked_path for path, _ in file_blocks):
diff_content = create_file_diff(repo, untracked_path)
file_blocks.append((untracked_path, diff_content))
file_stats[untracked_path] = (0, 0)
file_status[untracked_path] = "untracked"
# Add deleted files
for deleted_path in deleted_files:
if not any(path == deleted_path for path, _ in file_blocks):
diff_content = create_file_diff(repo, deleted_path)
file_blocks.append((deleted_path, diff_content))
file_stats[deleted_path] = (0, 0)
file_status[deleted_path] = "deleted"
page_title = title or f"{repo.name} diff review"
header_lines = [
f"<h1>{html.escape(page_title)}</h1>",
@@ -562,11 +866,14 @@ def generate_report(
header_lines.append(f"<p>{html.escape(body.strip())}</p>")
if subtitle:
header_lines.append(f"<p>{html.escape(subtitle)}</p>")
generated = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
header_lines.append(f"<p>Generated {generated} local time.</p>")
generated = datetime.datetime.now(datetime.UTC).strftime("%Y-%m-%d %H:%M")
header_lines.append(f"<p>Generated {generated} UTC.</p>")
header_body = "\n ".join(header_lines)
theme_css = theme_css_for_wiki(wiki_root)
# 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,
@@ -575,6 +882,8 @@ def generate_report(
file_stats,
theme_css,
open_details,
toggle_html,
file_status,
)
return html_page, f"{base_ref}..{head_ref}", file_blocks
@@ -587,6 +896,8 @@ def write_report(
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``.
@@ -600,6 +911,8 @@ def write_report(
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.
@@ -613,6 +926,8 @@ def write_report(
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")
@@ -649,12 +964,20 @@ def main(argv: list[str] | None = None) -> int:
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 = pathlib.Path.cwd()
if not (repo / ".git").exists():
print(f"Not a git repo: {repo}", file=sys.stderr)
return 1
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
@@ -674,6 +997,11 @@ def main(argv: list[str] | None = None) -> int:
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,
@@ -683,6 +1011,8 @@ def main(argv: list[str] | None = None) -> int:
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)
@@ -14,12 +14,22 @@
background: var(--bg);
color: var(--text);
line-height: 1.45;
transition: background-color 0.3s ease, color 0.3s ease;
}
header {
background: linear-gradient(135deg, var(--blue), var(--header-end));
color: var(--button-text);
padding: 1.5rem 1.25rem;
border-bottom: 4px solid color-mix(in srgb, var(--text) 12%, transparent);
background: var(--card);
color: var(--text);
padding: 1rem 1.25rem;
border-bottom: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
header .header-title {
flex: 1;
min-width: 200px;
}
header h1 { margin: 0 0 0.35rem; font-size: 1.4rem; font-weight: 600; }
header p { margin: 0.25rem 0; opacity: 0.92; font-size: 0.9rem; }
@@ -28,6 +38,21 @@
padding: 0.1rem 0.35rem;
border-radius: 4px;
}
.theme-toggle {
display: flex;
align-items: center;
gap: 0.5rem;
}
.theme-toggle button {
padding: 0.35rem 0.65rem;
cursor: pointer;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--button-bg);
color: var(--button-text);
font-size: 0.85rem;
}
.theme-toggle button:hover { background: var(--button-hover); }
.layout {
display: flex;
align-items: stretch;
@@ -93,11 +118,16 @@
}
.churn .add { color: var(--churn-add); }
.churn .del { color: var(--churn-del); }
.file-icon {
font-size: 0.8rem;
margin-right: 0.35rem;
opacity: 0.7;
}
.stat-fold {
margin: 0.75rem 0.5rem 0;
font-size: 0.75rem;
}
.stat-fold summary { AI/LLM: pointer; color: var(--muted); }
.stat-fold summary { cursor: pointer; color: var(--muted); }
.stat-fold pre {
margin: 0.35rem 0 0;
font-size: 0.68rem;
@@ -128,7 +158,7 @@
}
button {
padding: 0.35rem 0.65rem;
AI/LLM: pointer;
cursor: pointer;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--button-bg);
@@ -147,7 +177,7 @@
outline-offset: 2px;
}
details.file summary {
AI/LLM: pointer;
cursor: pointer;
padding: 0.6rem 0.75rem;
font-weight: 600;
background: var(--summary-bg);
@@ -156,15 +186,15 @@
margin: 0;
padding: 0.75rem;
font-size: 0.72rem;
line-height: 1.35;
line-height: 1.0;
overflow: auto;
max-height: 70vh;
}
.diff-add { background: var(--diff-add-bg); display: block; }
.diff-del { background: var(--diff-del-bg); display: block; }
.diff-hunk { color: var(--diff-hunk); display: block; }
.diff-meta { color: var(--diff-meta); display: block; }
.diff-ctx { display: block; }
.diff-add { background: var(--diff-add-bg); display: block; margin: 0; padding: 0; }
.diff-del { background: var(--diff-del-bg); display: block; margin: 0; padding: 0; }
.diff-hunk { color: var(--diff-hunk); display: block; margin: 0; padding: 0; }
.diff-meta { color: var(--diff-meta); display: block; margin: 0; padding: 0; }
.diff-ctx { display: block; margin: 0; padding: 0; }
@media (max-width: 900px) {
.layout { flex-direction: column; }
aside.sidebar {
@@ -175,11 +205,56 @@
border-bottom: 1px solid var(--border);
}
}
/* Dark mode theme - applied when data-theme="dark" (default) */
[data-theme="dark"] {
--bg: #1a1a1a;
--card: #2d2d2d;
--border: #404040;
--text: #e0e0e0;
--blue: #6ba1f5;
--accent: #7aa7d6;
--header-end: #c586c0;
--muted: #9e9e9e;
--summary-bg: #252525;
--button-bg: #3d3d3d;
--button-text: #e0e0e0;
--button-hover: #4a4a4a;
--churn-add: #7edd8a;
--churn-del: #ff7b7b;
--diff-add-bg: color-mix(in srgb, #7edd8a 22%, var(--card));
--diff-del-bg: color-mix(in srgb, #ff7b7b 22%, var(--card));
--link-hover-bg: color-mix(in srgb, #7aa7d6 18%, var(--card));
--link-active-bg: color-mix(in srgb, #7aa7d6 22%, var(--card));
}
/* Light mode theme - applied when data-theme="light" */
[data-theme="light"] {
--bg: #ffffff;
--card: #f8f9fa;
--border: #e2e8f0;
--text: #1a1a1a;
--blue: #0d6efd;
--accent: #0d6efd;
--header-end: #6610f2;
--muted: #6c757d;
--summary-bg: #f8f9fa;
--button-bg: #ffffff;
--button-text: #1a1a1a;
--button-hover: #e2e8f0;
--churn-add: #15803d;
--churn-del: #b91c1c;
--diff-add-bg: color-mix(in srgb, #15803d 22%, var(--card));
--diff-del-bg: color-mix(in srgb, #b91c1c 22%, var(--card));
--link-hover-bg: color-mix(in srgb, #0d6efd 18%, var(--card));
--link-active-bg: color-mix(in srgb, #0d6efd 22%, var(--card));
}
</style>
</head>
<body>
<header>
{{HEADER_BODY}}
<div class="header-title">
{{HEADER_BODY}}
</div>
{{THEME_TOGGLE_HTML}}
</header>
<div class="layout">
<aside class="sidebar" aria-label="Changed files">
@@ -200,6 +275,21 @@
</div>
<script>
(function () {
// Theme toggle functionality - default is dark mode
var themeToggle = document.getElementById('theme-toggle');
if (themeToggle) {
var htmlEl = document.documentElement;
// Default to dark mode
var savedTheme = localStorage.getItem('fiona-diff-theme') || 'dark';
htmlEl.setAttribute('data-theme', savedTheme);
themeToggle.addEventListener('click', function () {
var currentTheme = htmlEl.getAttribute('data-theme');
var newTheme = currentTheme === 'dark' ? 'light' : 'dark';
htmlEl.setAttribute('data-theme', newTheme);
localStorage.setItem('fiona-diff-theme', newTheme);
});
}
function openFromHash() {
var id = location.hash ? location.hash.slice(1) : "";
document.querySelectorAll(".file-tree a").forEach(function (a) {
+480
View File
@@ -109,3 +109,483 @@ def test_git_check_ignore_tmp(wiki_git_repo: pathlib.Path) -> None:
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