diff --git a/README.md b/README.md index 9424b67..828848e 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,68 @@ reports that the branch is up to date. Use a disposable token for this local dem Pull remains a handshake placeholder; fetching and restoring a branch through `minigit pull` is not implemented yet. +## Status and diff + +`minigit status` prints the current branch, then up to three sections. Empty +sections are left out, paths are sorted, and a repository with nothing to report +prints `clean`. Before the first commit it also prints `no commits yet`. + +- **staged**: the HEAD commit's tree compared with the index. +- **not staged**: the index compared with the files in the working directory. +- **untracked**: files on disk that are not in the index. + +A file that was staged and then edited again appears in both `staged` and +`not staged`. `minigit diff` compares the HEAD tree with the working files (an +empty snapshot when there are no commits yet). Both commands only read: they +never change files, the index, or any ref, and their output is plain text, so it +is safe to redirect to a file. + +``` +$ minigit status +On branch main +staged: + notes.txt +not staged: + notes.txt +untracked: + todo.md + +$ minigit diff +diff --minigit a/notes.txt b/notes.txt +--- a/notes.txt ++++ b/notes.txt +@@ -1,7 +1,9 @@ + one +-two ++TWO + three + four + five + six + seven ++eight ++nine +diff --minigit a/todo.md b/todo.md +new file mode 100644 +--- /dev/null ++++ b/todo.md +@@ -0,0 +1,1 @@ ++x +``` + +A hunk header reads `@@ -, +, @@`. The +old numbers refer to the HEAD version and the new numbers to the working file. +Lines are numbered from 1, and an empty range is written as the line before it, +so a new file starts at `-0,0`. Each hunk shows 3 unchanged lines around the +changes, and edits that are close together share one hunk. A line starting with +a space is unchanged, `-` was removed, and `+` was added. Added and deleted +files, mode changes, and a missing final newline are all shown, and binary files +get a one-line summary. + +Paths with spaces or Unicode print as they are. A path containing a control +character or a backslash prints as a quoted, escaped string. `add` refuses file +names that contain a tab or a newline. + ## Layout ``` @@ -133,4 +195,4 @@ changes instead of whitespace. Tests are the ones you write in `tests/`. - [Project description](https://docs.google.com/document/d/16OqU5R1x6is5E-2ZWk4KoWDouUU8gCKNzJvW7LTXJtI/edit?tab=t.0#heading=h.m3v17fze97bb) - the full explanation of what we are building and why. - [docs/branch-protection.md](docs/branch-protection.md) - the rules on `main` - and the merge settings, and how to change them. + and the merge settings, and how to change them. \ No newline at end of file diff --git a/minigit/index.py b/minigit/index.py index f842c8f..eab4653 100644 --- a/minigit/index.py +++ b/minigit/index.py @@ -1,7 +1,7 @@ """Module 2 - Index and working tree. Owns the bridge between live files on disk and the immutable object store: -the index file, staging, diffing, and checkout. +the index file, staging, diffing, checkout, and the text `status` and `diff` print. Depends on: module 1. Serves: module 3. @@ -9,8 +9,10 @@ Build the `WorkingTree` class here, per the interface contract. """ +import json import os -from dataclasses import dataclass +import re +from dataclasses import dataclass, field from typing import NamedTuple from minigit.errors import MiniGitError, ObjectCorruptError @@ -22,11 +24,147 @@ class IndexEntry(NamedTuple): path: str +class LineEdit(NamedTuple): + """One change, in the coordinates of the OLD (base) list of lines. + + Replace `old_count` lines starting at index `start` with `new_lines`. + A pure insert has old_count == 0; a pure delete has new_lines == []. + """ + + start: int + old_count: int + new_lines: list + + @dataclass class DiffResult: added: list deleted: list modified: list + # path -> list[LineEdit] for text files, or None for binary / undecodable files. + # A mode-only change has an empty list. Ignored by == so filename-list checks still work. + line_diffs: dict = field(default_factory=dict, compare=False) + + +class _FileChange(NamedTuple): + path: str + status: str # "added" | "deleted" | "modified" + old_mode: str | None + new_mode: str | None + old_lines: list # [] when binary + edits: list # [] when binary + binary: bool + content_changed: bool + + +# --------------------------------------------------------------------------- +# Myers line diff (pure functions - no files, no store) +# --------------------------------------------------------------------------- + + +def split_lines(text: str) -> list[str]: + """Split on "\n" only, keeping the newline on each line. + + "a\nb" -> ["a\n", "b"]; a missing final newline stays visible as a last + line without "\n". (str.splitlines would also split on \r, \x0c, etc.) + """ + return re.findall(r"[^\n]*\n|[^\n]+", text) + + +def myers_diff(a: list, b: list) -> list[LineEdit]: + """Return the shortest list of LineEdit that turns `a` into `b`.""" + return _group_ops(_shortest_path(a, b)) + + +def _shortest_path(a: list, b: list) -> list: + n, m = len(a), len(b) + if n == 0 and m == 0: + return [] + + # v[k] = furthest x reached on diagonal k, where k = x - y. + v = {1: 0} + trace = [] # trace[d] = copy of v at the start of round d + + for d in range(n + m + 1): + trace.append(dict(v)) + for k in range(-d, d + 1, 2): + if k == -d or (k != d and v[k - 1] < v[k + 1]): + x = v[k + 1] # step down: insert a line from b + else: + x = v[k - 1] + 1 # step right: delete a line from a + y = x - k + while x < n and y < m and a[x] == b[y]: # matching lines are free + x += 1 + y += 1 + v[k] = x + if x >= n and y >= m: + return _backtrack(b, trace, d, n, m) + raise AssertionError("unreachable") # pragma: no cover + + +def _backtrack(b: list, trace: list, last_d: int, n: int, m: int) -> list: + x, y = n, m + ops = [] # ("del", old_index) or ("ins", old_index, line) + + for d in range(last_d, 0, -1): + v = trace[d] + k = x - y + if k == -d or (k != d and v[k - 1] < v[k + 1]): + prev_k = k + 1 # came from above: an insertion + else: + prev_k = k - 1 # came from the left: a deletion + prev_x = v[prev_k] + prev_y = prev_x - prev_k + + while x > prev_x and y > prev_y: # walk back over matching lines + x -= 1 + y -= 1 + + if prev_k == k + 1: + ops.append(("ins", prev_x, b[prev_y])) + else: + ops.append(("del", prev_x)) + x, y = prev_x, prev_y + + ops.reverse() + return ops + + +def _group_ops(ops: list) -> list[LineEdit]: + """Merge neighbouring del/ins ops into LineEdit(start, old_count, new_lines).""" + edits = [] + current = None # [start, old_count, new_lines] + for op in ops: + pos = op[1] + if current is None or pos != current[0] + current[1]: + if current is not None: + edits.append(LineEdit(*current)) + current = [pos, 0, []] + if op[0] == "del": + current[1] += 1 + else: + current[2].append(op[2]) + if current is not None: + edits.append(LineEdit(*current)) + return edits + + +def apply_edits(base: list, edits: list[LineEdit]) -> list: + """Apply LineEdits (base coordinates) to `base`; the inverse of myers_diff.""" + result = list(base) + for edit in sorted(edits, key=lambda e: e.start, reverse=True): + result[edit.start : edit.start + edit.old_count] = edit.new_lines + return result + + +def _bytes_to_lines(data: bytes) -> list[str] | None: + """Decode file bytes into lines, or None if the file looks binary.""" + if b"\0" in data: + return None + try: + return split_lines(data.decode("utf-8")) + except UnicodeDecodeError: + return None class WorkingTree: @@ -47,11 +185,17 @@ def read_index(self) -> list[IndexEntry]: entries = [] with open(self.index_path, encoding="utf-8") as f: - for line in f: + for number, line in enumerate(f, start=1): line = line.rstrip("\n") if not line: continue - mode, hash_, path = line.split(" ", 2) + try: + mode, hash_, path = line.split(" ", 2) + except ValueError: + raise MiniGitError( + f"corrupt index: line {number} is not ' '; " + "delete .minigit/index and run 'minigit add' again" + ) from None entries.append(IndexEntry(mode, hash_, path)) return sorted(entries, key=lambda e: e.path) @@ -69,13 +213,32 @@ def write_index(self, entries) -> None: def stage_file(self, path) -> None: full_path = os.path.join(self.root, path) - - if not os.path.isfile(full_path): - raise MiniGitError(f"No such file: {path}") - rel_path = os.path.relpath(full_path, self.root) rel_path = rel_path.replace(os.sep, "/") + if rel_path == ".." or rel_path.startswith("../") or rel_path.split("/")[0] == ".minigit": + raise MiniGitError( + f"cannot stage {path}: it is outside the repository or inside .minigit; " + "give a path to a file in the working tree" + ) + + if any(char in rel_path for char in "\0\t\r\n"): + raise MiniGitError( + f"cannot stage {display_path(path)}: names with a tab or newline are not " + "supported; rename the file" + ) + + if not os.path.isfile(full_path): + # A tracked file that is gone from disk: staging it stages the deletion. + entries = self.read_index() + remaining = [e for e in entries if e.path != rel_path] + if len(remaining) == len(entries): + raise MiniGitError( + f"No such file: {path}; check the path, or run 'minigit status' to list files" + ) + self.write_index(remaining) + return + with open(full_path, "rb") as f: data = f.read() @@ -134,34 +297,73 @@ def walk(hash_, prefix): walk(tree_hash, "") return sorted(entries, key=lambda e: e.path) - def diff_working_tree_vs(self, tree_hash) -> DiffResult: - result = DiffResult([], [], []) - tree_entries = self.read_tree_entries(tree_hash) + def _disk_mode(self, full_path: str) -> str: + return "100755" if os.access(full_path, os.X_OK) else "100644" + + def _make_change(self, path, status, old_mode, new_mode, old_data, new_data) -> _FileChange: + old_lines = _bytes_to_lines(old_data) + new_lines = _bytes_to_lines(new_data) + binary = old_lines is None or new_lines is None + edits = [] if binary else myers_diff(old_lines, new_lines) + return _FileChange( + path=path, + status=status, + old_mode=old_mode, + new_mode=new_mode, + old_lines=[] if binary else old_lines, + edits=edits, + binary=binary, + content_changed=old_data != new_data, + ) + + def _compare_with_tree(self, tree_hash) -> list[_FileChange]: + """Compare a tree (None = empty tree) with the files on disk. Read-only.""" + tree_entries = self.read_tree_entries(tree_hash) if tree_hash else [] known_paths = {e.path for e in tree_entries} + changes = [] for entry in tree_entries: full_path = os.path.join(self.root, entry.path) if not os.path.isfile(full_path): - result.deleted.append(entry.path) - else: - with open(full_path, "rb") as f: - data = f.read() - current_hash = self.store.hash_object(data, "blob") - current_mode = "100755" if os.access(full_path, os.X_OK) else "100644" - if current_hash != entry.hash or current_mode != entry.mode: - result.modified.append(entry.path) + _, old_data = self.store.read_object(entry.hash) + changes.append( + self._make_change(entry.path, "deleted", entry.mode, None, old_data, b"") + ) + continue + with open(full_path, "rb") as f: + new_data = f.read() + new_mode = self._disk_mode(full_path) + if self.store.hash_object(new_data, "blob") == entry.hash and new_mode == entry.mode: + continue + _, old_data = self.store.read_object(entry.hash) + changes.append( + self._make_change(entry.path, "modified", entry.mode, new_mode, old_data, new_data) + ) for dirpath, dirnames, filenames in os.walk(self.root): dirnames[:] = [d for d in dirnames if d != ".minigit"] for filename in filenames: full_path = os.path.join(dirpath, filename) rel_path = os.path.relpath(full_path, self.root).replace(os.sep, "/") - if rel_path not in known_paths: - result.added.append(rel_path) + if rel_path in known_paths: + continue + with open(full_path, "rb") as f: + new_data = f.read() + new_mode = self._disk_mode(full_path) + changes.append(self._make_change(rel_path, "added", None, new_mode, b"", new_data)) - result.added.sort() - result.deleted.sort() - result.modified.sort() + return sorted(changes, key=lambda c: c.path) + + def diff_working_tree_vs(self, tree_hash) -> DiffResult: + """Compare the working files with a tree (None = empty tree). + + added / deleted / modified stay plain sorted path lists. line_diffs adds + path -> list[LineEdit] (base = the tree's version), or None for binary files. + """ + result = DiffResult([], [], []) + for change in self._compare_with_tree(tree_hash): + getattr(result, change.status).append(change.path) + result.line_diffs[change.path] = None if change.binary else change.edits return result def _working_status(self) -> DiffResult: @@ -191,10 +393,21 @@ def _working_status(self) -> DiffResult: return result - def checkout(self, tree_hash) -> None: + def checkout(self, tree_hash, conflicted_paths=()) -> None: + """Make the working files and the index match `tree_hash`. + + `conflicted_paths` (used by a merge) are written to disk like every other + path - their blob in the tree holds the conflict markers - but their index + entry stays at its pre-merge version (or is left out if there was none), so + status reports them as "not staged" until `add` resolves them. + """ target_entries = self.read_tree_entries(tree_hash) target_by_path = {e.path: e for e in target_entries} + conflicted = set(conflicted_paths) + for path in sorted(conflicted - set(target_by_path)): + raise MiniGitError(f"conflicted path is not in the target tree: {path}") + # Reject unsafe paths blob_cache = {} for entry in target_entries: @@ -212,13 +425,18 @@ def checkout(self, tree_hash) -> None: self._validate_checkout_path(entry.path) full_path = os.path.join(self.root, entry.path) if not os.path.isfile(full_path): - raise MiniGitError(f"local changes would be lost: {entry.path} is missing") + raise MiniGitError( + f"local changes would be lost: {entry.path} is missing; " + "restore the file or commit its deletion first" + ) with open(full_path, "rb") as f: data = f.read() disk_hash = self.store.hash_object(data, "blob") disk_mode = "100755" if os.access(full_path, os.X_OK) else "100644" if disk_hash != entry.hash or disk_mode != entry.mode: - raise MiniGitError(f"local changes would be lost: {entry.path}") + raise MiniGitError( + f"local changes would be lost: {entry.path}; commit or undo your edits first" + ) # Preflight every parent and destination before deleting any tracked file. # Directories may become files only when all their contents are tracked. @@ -237,20 +455,31 @@ def checkout(self, tree_hash) -> None: full_parent = os.path.join(self.root, parent) if os.path.lexists(full_parent) and not os.path.isdir(full_parent): if parent not in removable: - raise MiniGitError(f"untracked path would be overwritten: {parent}") + raise MiniGitError( + f"untracked path would be overwritten: {parent}; " + "move or delete it first" + ) full_path = os.path.join(self.root, entry.path) if os.path.isdir(full_path): if entry.path not in tracked_dirs: - raise MiniGitError(f"untracked path would be overwritten: {entry.path}") + raise MiniGitError( + f"untracked path would be overwritten: {entry.path}; " + "move or delete it first" + ) for directory, dirnames, filenames in os.walk(full_path): for name in dirnames + filenames: child = os.path.join(directory, name) relative = os.path.relpath(child, self.root).replace(os.sep, "/") if os.path.islink(child) or relative not in removable | tracked_dirs: - raise MiniGitError(f"untracked path would be overwritten: {relative}") + raise MiniGitError( + f"untracked path would be overwritten: {relative}; " + "move or delete it first" + ) elif os.path.lexists(full_path) and entry.path not in current_by_path: - raise MiniGitError(f"untracked path would be overwritten: {entry.path}") + raise MiniGitError( + f"untracked path would be overwritten: {entry.path}; move or delete it first" + ) # Remove tracked files the target doesn't have, then prune for entry in current_entries: @@ -268,8 +497,14 @@ def checkout(self, tree_hash) -> None: f.write(blob_cache[entry.path]) os.chmod(full_path, 0o755 if entry.mode == "100755" else 0o644) - # Now matched - self.write_index(target_entries) + # Now matched - except conflicted paths, which keep their pre-merge entry. + index_entries = [] + for entry in target_entries: + if entry.path not in conflicted: + index_entries.append(entry) + elif entry.path in current_by_path: + index_entries.append(current_by_path[entry.path]) + self.write_index(index_entries) def _validate_checkout_path(self, path: str) -> None: if ( @@ -304,14 +539,77 @@ def cmd_add(args) -> int: return 0 +# --------------------------------------------------------------------------- +# Output formatting for `status` and `diff` (plain text; no Myers code in here) +# --------------------------------------------------------------------------- + +CONTEXT_LINES = 3 # unchanged lines shown around each change in a diff hunk + + +def display_path(path: str, prefix: str = "") -> str: + """Return `prefix + path` the way status and diff print it. + + Ordinary paths (spaces and Unicode included) are printed as they are. A path with + a control character or a backslash is printed as a quoted, escaped string, so one + path always stays on one line and the output reads the same everywhere. + """ + text = prefix + path + if any(not char.isprintable() or char == "\\" for char in text): + return json.dumps(text) + return text + + +def format_status(header, unborn, unresolved, staged, not_staged, untracked) -> list[str]: + """Return the lines `minigit status` prints. Empty sections are left out.""" + lines = [header] + if unborn: + lines.append("no commits yet") + sections = ( + ("unresolved (merge conflict):", unresolved), + ("staged:", staged), + ("not staged:", not_staged), + ("untracked:", untracked), + ) + shown = False + for title, paths in sections: + if paths: + lines.append(title) + lines.extend(f" {display_path(path)}" for path in sorted(paths)) + shown = True + if not shown: + lines.append("clean") + return lines + + +def _head_header(head) -> str: + """First status line. `head` is what CommitManager.read_head() returned.""" + if head is None: + return "On branch main" # no HEAD file yet: same default as CommitManager + if len(head) == 40 and all(char in "0123456789abcdef" for char in head): + return f"HEAD detached at {head[:7]}" + return f"On branch {head}" + + +def _unresolved_merge_paths(manager) -> list[str]: + """Paths a pending merge has not resolved yet. + + Module 3 owns merge state. Until it offers `unresolved_merge_paths()`, there are none. + """ + helper = getattr(manager, "unresolved_merge_paths", None) + return sorted(helper()) if callable(helper) else [] + + def cmd_status(args) -> int: + """minigit status: branch, then staged (HEAD tree vs index), not staged (index vs + working files) and untracked files. Read-only.""" wt = WorkingTree() index_entries = wt.read_index() index_by_path = {e.path: e for e in index_entries} from minigit.commits import CommitManager - head_tree_hash = CommitManager(wt.root, store=wt.store, tree=wt).get_head_tree() + manager = CommitManager(wt.root, store=wt.store, tree=wt) + head_tree_hash = manager.get_head_tree() head_entries = wt.read_tree_entries(head_tree_hash) if head_tree_hash else [] head_by_path = {e.path: e for e in head_entries} @@ -350,33 +648,124 @@ def cmd_status(args) -> int: if rel_path not in known_paths: untracked_paths.add(rel_path) - staged = sorted(staged_paths) - not_staged = sorted(not_staged_paths) - untracked = sorted(untracked_paths) - - printed_anything = False - - if staged: - print("staged:") - for path in staged: - print(f" {path}") - printed_anything = True + lines = format_status( + _head_header(manager.read_head()), + head_tree_hash is None, + _unresolved_merge_paths(manager), + staged_paths, + not_staged_paths, + untracked_paths, + ) + for line in lines: + print(line) + return 0 - if not_staged: - print("not staged:") - for path in not_staged: - print(f" {path}") - printed_anything = True - if untracked: - print("untracked:") - for path in untracked: - print(f" {path}") - printed_anything = True +def _hunk_range(start: int, count: int) -> str: + """`start` is a 0-based line index. A non-empty range is written 1-based + ("3,2" = lines 3 and 4); an empty range is written as the line before it ("2,0").""" + return f"{start if count == 0 else start + 1},{count}" + + +def _diff_lines(prefix: str, line: str) -> list[str]: + out = [prefix + line.removesuffix("\n")] + if not line.endswith("\n"): + out.append("\\ No newline at end of file") + return out + + +def _group_edits(edits: list, context: int) -> list[list]: + """Group edits that are close enough for their context lines to touch or overlap.""" + groups: list[list] = [] + for edit in edits: + if groups: + last = groups[-1][-1] + if edit.start - (last.start + last.old_count) <= 2 * context: + groups[-1].append(edit) + continue + groups.append([edit]) + return groups + + +def _render_hunk(old_lines: list, group: list, shift: int, context: int): + """Return (hunk lines, change in line count). `shift` = lines added minus removed so far.""" + first, last = group[0], group[-1] + old_from = max(0, first.start - context) + old_to = min(len(old_lines), last.start + last.old_count + context) + body: list[str] = [] + removed = added = 0 + position = old_from + for edit in group: + for line in old_lines[position : edit.start]: + body.extend(_diff_lines(" ", line)) + for line in old_lines[edit.start : edit.start + edit.old_count]: + body.extend(_diff_lines("-", line)) + for line in edit.new_lines: + body.extend(_diff_lines("+", line)) + removed += edit.old_count + added += len(edit.new_lines) + position = edit.start + edit.old_count + for line in old_lines[position:old_to]: + body.extend(_diff_lines(" ", line)) + old_count = old_to - old_from + new_count = old_count - removed + added + header = ( + f"@@ -{_hunk_range(old_from, old_count)} +{_hunk_range(old_from + shift, new_count)} @@" + ) + return [header, *body], added - removed + + +def _format_change(change: _FileChange, context: int = CONTEXT_LINES) -> list[str]: + """Render one file's changes as printable lines. + + Hunk header: `@@ -, +, @@`, with the + old numbers from the HEAD version and the new ones from the working file. + Each hunk shows `context` unchanged lines around the changes; lines start with + " " (unchanged), "-" (removed) or "+" (added). + """ + path = change.path + out = [f"diff --minigit {display_path(path, 'a/')} {display_path(path, 'b/')}"] + + if change.status == "added": + out.append(f"new file mode {change.new_mode}") + elif change.status == "deleted": + out.append(f"deleted file mode {change.old_mode}") + elif change.old_mode != change.new_mode: + out.append(f"old mode {change.old_mode}") + out.append(f"new mode {change.new_mode}") + + if change.binary: + if change.status == "added": + out.append(f"binary file added: {display_path(path)}") + elif change.status == "deleted": + out.append(f"binary file deleted: {display_path(path)}") + elif change.content_changed: + out.append(f"binary file changed: {display_path(path)}") + return out + if not change.edits: + return out # mode-only change, or an empty file added / deleted + + out.append("--- /dev/null" if change.status == "added" else f"--- {display_path(path, 'a/')}") + out.append("+++ /dev/null" if change.status == "deleted" else f"+++ {display_path(path, 'b/')}") + + shift = 0 + for group in _group_edits(change.edits, context): + hunk, delta = _render_hunk(change.old_lines, group, shift, context) + out.extend(hunk) + shift += delta + return out + + +def cmd_diff(args) -> int: + """minigit diff: HEAD tree vs the working files (unborn HEAD = empty tree). Read-only.""" + wt = WorkingTree() - if not printed_anything: - print("clean") + from minigit.commits import CommitManager + head_tree_hash = CommitManager(wt.root, store=wt.store, tree=wt).get_head_tree() + for change in wt._compare_with_tree(head_tree_hash): + for line in _format_change(change): + print(line) return 0 @@ -385,5 +774,12 @@ def register_index_commands(subparsers) -> None: add_parser.add_argument("path") add_parser.set_defaults(handler=cmd_add) - status_parser = subparsers.add_parser("status", help="show staged files") + status_parser = subparsers.add_parser( + "status", help="show the branch and staged, not staged and untracked files" + ) status_parser.set_defaults(handler=cmd_status) + + diff_parser = subparsers.add_parser( + "diff", help="show line changes: the HEAD tree compared with the working files" + ) + diff_parser.set_defaults(handler=cmd_diff) diff --git a/tests/test_index.py b/tests/test_index.py index d3d73e6..ca278ec 100644 --- a/tests/test_index.py +++ b/tests/test_index.py @@ -1,13 +1,33 @@ -"""Tests for minigit/index.py - WorkingTree, trees, diffing, and status.""" +"""Tests for minigit/index.py - WorkingTree, trees, diffing, status, checkout, Myers diff, +and pull / merge-result handling.""" +import argparse +import hashlib import os +import random +import re +import shutil +import sys +import types import pytest from minigit.commits import CommitManager -from minigit.errors import MiniGitError -from minigit.index import WorkingTree, cmd_status -from minigit.objects import ObjectStore +from minigit.errors import MiniGitError, ObjectNotFoundError +from minigit.index import ( + LineEdit, + WorkingTree, + apply_edits, + cmd_add, + cmd_diff, + cmd_status, + display_path, + myers_diff, + split_lines, +) +from minigit.objects import ObjectStore, TreeEntry + +BRANCH = "On branch main\n" # first line of `minigit status` on the default branch def test_build_tree_empty_index(tmp_path): @@ -193,7 +213,7 @@ def test_status_clean_after_commit(tmp_path, monkeypatch, capsys): cmd_status(_Args()) output = capsys.readouterr().out - assert output.strip() == "clean" + assert output == BRANCH + "clean\n" def test_status_staged_and_unstaged_on_one_file(tmp_path, monkeypatch, capsys): @@ -250,7 +270,7 @@ def test_status_and_diff_do_not_store_unstaged_content(tmp_path, monkeypatch, ca file.write_text("unstaged") monkeypatch.chdir(tmp_path) cmd_status(_Args()) - assert capsys.readouterr().out == "not staged:\n file\n" + assert capsys.readouterr().out == BRANCH + "not staged:\n file\n" assert wt.diff_working_tree_vs(tree).modified == ["file"] assert set(wt.store.objects_dir.rglob("*")) == before @@ -263,7 +283,7 @@ def test_status_reports_file_removed_from_index_as_untracked(tmp_path, monkeypat wt.write_index([]) monkeypatch.chdir(tmp_path) cmd_status(_Args()) - assert capsys.readouterr().out == "staged:\n file\nuntracked:\n file\n" + assert capsys.readouterr().out == BRANCH + "staged:\n file\nuntracked:\n file\n" def test_checkout_restores_changed_file(tmp_path): @@ -408,3 +428,1082 @@ def test_checkout_is_idempotent(tmp_path): assert first_index == second_index assert (tmp_path / "hello.txt").read_text() == "hi" + + +# --------------------------------------------------------------------------- +# Myers: pure function tests +# --------------------------------------------------------------------------- + + +def lcs_length(a, b): + table = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] + for i in range(len(a) - 1, -1, -1): + for j in range(len(b) - 1, -1, -1): + if a[i] == b[j]: + table[i][j] = table[i + 1][j + 1] + 1 + else: + table[i][j] = max(table[i + 1][j], table[i][j + 1]) + return table[0][0] + + +def edit_cost(edits): + return sum(e.old_count + len(e.new_lines) for e in edits) + + +def test_identical_lists_have_no_edits(): + assert myers_diff(["a", "b", "c"], ["a", "b", "c"]) == [] + + +def test_both_empty_have_no_edits(): + assert myers_diff([], []) == [] + + +def test_pure_insert_uses_base_position(): + assert myers_diff(["a", "c"], ["a", "b", "c"]) == [LineEdit(1, 0, ["b"])] + + +def test_insert_at_start_and_end(): + assert myers_diff(["b"], ["a", "b"]) == [LineEdit(0, 0, ["a"])] + assert myers_diff(["a"], ["a", "b"]) == [LineEdit(1, 0, ["b"])] + + +def test_pure_delete(): + assert myers_diff(["a", "b", "c"], ["a", "c"]) == [LineEdit(1, 1, [])] + + +def test_replace(): + assert myers_diff(["a", "b", "c"], ["a", "x", "c"]) == [LineEdit(1, 1, ["x"])] + + +def test_from_empty_and_to_empty(): + assert myers_diff([], ["a", "b"]) == [LineEdit(0, 0, ["a", "b"])] + assert myers_diff(["a", "b"], []) == [LineEdit(0, 2, [])] + + +def test_repeated_lines(): + edits = myers_diff(["x", "x", "x"], ["x", "x"]) + assert edit_cost(edits) == 1 + assert apply_edits(["x", "x", "x"], edits) == ["x", "x"] + + +def test_two_separate_changes_stay_separate(): + old = ["a", "b", "c", "d", "e"] + new = ["a", "B", "c", "d", "E"] + assert myers_diff(old, new) == [LineEdit(1, 1, ["B"]), LineEdit(4, 1, ["E"])] + + +def test_missing_final_newline_is_a_change(): + old = split_lines("a\nb") + new = split_lines("a\nb\n") + assert myers_diff(old, new) == [LineEdit(1, 1, ["b\n"])] + + +def test_edits_are_sorted_and_do_not_overlap(): + random.seed(7) + for _ in range(200): + a = [random.choice("abc") for _ in range(random.randint(0, 8))] + b = [random.choice("abc") for _ in range(random.randint(0, 8))] + edits = myers_diff(a, b) + for first, second in zip(edits, edits[1:], strict=False): + assert first.start + first.old_count < second.start + + +def test_random_round_trip_and_minimal(): + random.seed(1) + for _ in range(500): + a = [random.choice("abc") for _ in range(random.randint(0, 9))] + b = [random.choice("abc") for _ in range(random.randint(0, 9))] + edits = myers_diff(a, b) + assert apply_edits(a, edits) == b + assert edit_cost(edits) == len(a) + len(b) - 2 * lcs_length(a, b) + + +def test_split_lines_keeps_newlines_and_only_splits_on_newline(): + assert split_lines("") == [] + assert split_lines("a\n") == ["a\n"] + assert split_lines("a\nb") == ["a\n", "b"] + assert split_lines("a\r\nb\n") == ["a\r\n", "b\n"] + assert split_lines("a\x0cb\u2028c\n") == ["a\x0cb\u2028c\n"] + assert split_lines("\n\n") == ["\n", "\n"] + + +# --------------------------------------------------------------------------- +# diff_working_tree_vs with line details +# --------------------------------------------------------------------------- + + +@pytest.fixture +def repo(tmp_path): + store = ObjectStore(str(tmp_path)) + return WorkingTree(str(tmp_path), store=store) + + +def write(repo, name, content, mode=None): + path = os.path.join(repo.root, name) + os.makedirs(os.path.dirname(path), exist_ok=True) + data = content if isinstance(content, bytes) else content.encode() + with open(path, "wb") as f: + f.write(data) + if mode is not None: + os.chmod(path, mode) + return path + + +def snapshot_tree(repo, files): + """Stage `files`, build the tree (this is our stand-in for HEAD), return its hash.""" + for name in files: + repo.stage_file(name) + return repo.build_tree_from_index() + + +def minigit_files(repo): + found = [] + for dirpath, _, filenames in os.walk(os.path.join(repo.root, ".minigit")): + for filename in filenames: + full = os.path.join(dirpath, filename) + found.append((os.path.relpath(full, repo.root), os.path.getmtime(full))) + return sorted(found) + + +def test_modified_file_has_line_edits_and_name_lists(repo): + write(repo, "a.txt", "one\ntwo\nthree\n") + tree = snapshot_tree(repo, ["a.txt"]) + write(repo, "a.txt", "one\nTWO\nthree\n") + + result = repo.diff_working_tree_vs(tree) + + assert result.modified == ["a.txt"] + assert result.added == [] + assert result.deleted == [] + assert result.line_diffs["a.txt"] == [LineEdit(1, 1, ["TWO\n"])] + + +def test_added_and_deleted_files_have_line_edits(repo): + write(repo, "gone.txt", "x\ny\n") + tree = snapshot_tree(repo, ["gone.txt"]) + os.remove(os.path.join(repo.root, "gone.txt")) + write(repo, "new.txt", "p\nq\n") + + result = repo.diff_working_tree_vs(tree) + + assert result.deleted == ["gone.txt"] + assert result.added == ["new.txt"] + assert result.line_diffs["gone.txt"] == [LineEdit(0, 2, [])] + assert result.line_diffs["new.txt"] == [LineEdit(0, 0, ["p\n", "q\n"])] + + +def test_unchanged_file_is_not_reported(repo): + write(repo, "same.txt", "hello\n") + tree = snapshot_tree(repo, ["same.txt"]) + + result = repo.diff_working_tree_vs(tree) + + assert result.added == result.deleted == result.modified == [] + assert result.line_diffs == {} + + +def test_unborn_head_none_is_an_empty_tree(repo): + write(repo, "a.txt", "hi\n") + + result = repo.diff_working_tree_vs(None) + + assert result.added == ["a.txt"] + assert result.line_diffs["a.txt"] == [LineEdit(0, 0, ["hi\n"])] + + +def test_binary_and_undecodable_files_have_no_line_diff(repo): + write(repo, "img.bin", b"\x00\x01\x02") + write(repo, "latin.txt", b"caf\xe9\n") + tree = snapshot_tree(repo, ["img.bin", "latin.txt"]) + write(repo, "img.bin", b"\x00\x01\x03") + write(repo, "latin.txt", b"caf\xe8\n") + + result = repo.diff_working_tree_vs(tree) + + assert result.modified == ["img.bin", "latin.txt"] + assert result.line_diffs["img.bin"] is None + assert result.line_diffs["latin.txt"] is None + + +def test_unicode_text_is_diffed_as_text(repo): + write(repo, "u.txt", "café\nnaïve\n") + tree = snapshot_tree(repo, ["u.txt"]) + write(repo, "u.txt", "café\nnaïve!\n") + + result = repo.diff_working_tree_vs(tree) + + assert result.line_diffs["u.txt"] == [LineEdit(1, 1, ["naïve!\n"])] + + +def test_mode_only_change_is_modified_with_no_line_edits(repo): + write(repo, "run.sh", "echo hi\n", mode=0o644) + tree = snapshot_tree(repo, ["run.sh"]) + os.chmod(os.path.join(repo.root, "run.sh"), 0o755) + + result = repo.diff_working_tree_vs(tree) + + assert result.modified == ["run.sh"] + assert result.line_diffs["run.sh"] == [] + + +def test_diff_ignores_minigit_directory(repo): + write(repo, "a.txt", "x\n") + tree = snapshot_tree(repo, ["a.txt"]) + + result = repo.diff_working_tree_vs(tree) + + assert not any(p.startswith(".minigit") for p in result.added) + + +def test_diff_writes_nothing_to_minigit(repo): + write(repo, "a.txt", "one\n") + tree = snapshot_tree(repo, ["a.txt"]) + write(repo, "a.txt", "two\n") + write(repo, "b.txt", "new\n") + before = minigit_files(repo) + + repo.diff_working_tree_vs(tree) + + assert minigit_files(repo) == before + + +# --------------------------------------------------------------------------- +# `minigit diff` and status (fake minigit.commits so these tests stand alone) +# --------------------------------------------------------------------------- + + +@pytest.fixture +def cli_repo(tmp_path, monkeypatch): + monkeypatch.chdir(tmp_path) + repo = WorkingTree(".", store=ObjectStore(".")) + state = {"head_tree": None} + + class FakeCommitManager: + def __init__(self, repo_path=".", store=None, tree=None): + pass + + def get_head_tree(self): + return state["head_tree"] + + def read_head(self): + return None + + fake = types.ModuleType("minigit.commits") + fake.CommitManager = FakeCommitManager + monkeypatch.setitem(sys.modules, "minigit.commits", fake) + + def commit(*files): + state["head_tree"] = snapshot_tree(repo, files) + + return repo, commit + + +def run_diff(capsys): + assert cmd_diff(None) == 0 + return capsys.readouterr().out + + +def test_cli_clean_tree_prints_nothing(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "hi\n") + commit("a.txt") + + assert run_diff(capsys) == "" + + +def test_cli_shows_headers_and_added_removed_lines(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "one\ntwo\nthree\n") + commit("a.txt") + write(repo, "a.txt", "one\nTWO\nthree\n") + + out = run_diff(capsys).splitlines() + + assert "diff --minigit a/a.txt b/a.txt" in out + assert "--- a/a.txt" in out + assert "+++ b/a.txt" in out + assert "@@ -1,3 +1,3 @@" in out + assert out[out.index("@@ -1,3 +1,3 @@") + 1 :] == [" one", "-two", "+TWO", " three"] + + +def test_cli_removed_lines_come_from_the_old_text(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "keep\nold1\nold2\nkeep2\n") + commit("a.txt") + write(repo, "a.txt", "keep\nnew\nkeep2\n") + + out = run_diff(capsys).splitlines() + + assert out.index("-old1") < out.index("-old2") < out.index("+new") + + +def test_cli_nearby_edits_share_one_hunk(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "a\nb\nc\nd\ne\nf\n") + commit("a.txt") + write(repo, "a.txt", "a\nX\nY\nb\nc\nd\ne\nF\n") + + out = run_diff(capsys).splitlines() + + assert [line for line in out if line.startswith("@@")] == ["@@ -1,6 +1,8 @@"] + + +def test_cli_distant_edits_are_separate_hunks_with_shifted_numbers(cli_repo, capsys): + repo, commit = cli_repo + old = "".join(f"{i}\n" for i in range(1, 21)) + new = "1\nTWO\n" + "".join(f"{i}\n" for i in range(3, 19)) + "TWENTY\n" + write(repo, "a.txt", old) + commit("a.txt") + write(repo, "a.txt", new) + + out = run_diff(capsys).splitlines() + + assert [line for line in out if line.startswith("@@")] == [ + "@@ -1,5 +1,5 @@", + "@@ -16,5 +16,4 @@", + ] + + +def test_cli_new_and_deleted_files(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "gone.txt", "bye\n") + commit("gone.txt") + os.remove("gone.txt") + write(repo, "new.txt", "hello\n") + + out = run_diff(capsys).splitlines() + + assert "deleted file mode 100644" in out + assert "-bye" in out + assert "+++ /dev/null" in out + assert "new file mode 100644" in out + assert "--- /dev/null" in out + assert "+hello" in out + + +def test_cli_unborn_head_shows_everything_as_new(cli_repo, capsys): + repo, _ = cli_repo + write(repo, "a.txt", "hi\n") + + out = run_diff(capsys).splitlines() + + assert "new file mode 100644" in out + assert "+hi" in out + + +def test_cli_binary_file_reports_binary_changed(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "img.bin", b"\x00\x01") + commit("img.bin") + write(repo, "img.bin", b"\x00\x02") + + out = run_diff(capsys) + + assert "binary file changed" in out + assert "@@" not in out + + +def test_cli_mode_only_change(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "run.sh", "echo hi\n", mode=0o644) + commit("run.sh") + os.chmod("run.sh", 0o755) + + out = run_diff(capsys).splitlines() + + assert "old mode 100644" in out + assert "new mode 100755" in out + assert not any(line.startswith("@@") for line in out) + + +def test_cli_missing_final_newline_is_marked(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "a\nb") + commit("a.txt") + write(repo, "a.txt", "a\nb\n") + + out = run_diff(capsys).splitlines() + + assert "-b" in out + assert "\\ No newline at end of file" in out + assert "+b" in out + + +def test_cli_diff_and_status_are_read_only(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "one\n") + commit("a.txt") + write(repo, "a.txt", "two\n") + write(repo, "b.txt", "new\n") + before_files = minigit_files(repo) + before_index = repo.read_index() + + cmd_diff(None) + cmd_status(None) + capsys.readouterr() + + assert minigit_files(repo) == before_files + assert repo.read_index() == before_index + with open("a.txt") as f: + assert f.read() == "two\n" + + +def test_status_sections_still_staged_not_staged_untracked(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "one\n") + commit("a.txt") + write(repo, "a.txt", "two\n") + write(repo, "b.txt", "new\n") + repo.stage_file("b.txt") + write(repo, "c.txt", "loose\n") + + cmd_status(None) + out = capsys.readouterr().out.splitlines() + + assert out == [ + "On branch main", + "staged:", + " b.txt", + "not staged:", + " a.txt", + "untracked:", + " c.txt", + ] + + +# --------------------------------------------------------------------------- +# Merge integration: M3 hands us a merged tree (conflict markers are just blob text) +# --------------------------------------------------------------------------- + + +def test_checkout_applies_a_merge_tree_with_conflict_markers(repo): + write(repo, "a.txt", "base\n") + repo.stage_file("a.txt") + base_tree = repo.build_tree_from_index() + repo.checkout(base_tree) + + conflicted = b"<<<<<<< ours\nmine\n=======\ntheirs\n>>>>>>> theirs\n" + blob = repo.store.write_object(conflicted, "blob") + clean = repo.store.write_object(b"added by merge\n", "blob") + merge_tree = repo.store.write_tree( + [ + TreeEntry("100644", "blob", blob, "a.txt"), + TreeEntry("100644", "blob", clean, "b.txt"), + ] + ) + + repo.checkout(merge_tree) + + with open(os.path.join(repo.root, "a.txt"), "rb") as f: + assert f.read() == conflicted + with open(os.path.join(repo.root, "b.txt"), "rb") as f: + assert f.read() == b"added by merge\n" + assert [e.path for e in repo.read_index()] == ["a.txt", "b.txt"] + assert repo.diff_working_tree_vs(merge_tree).line_diffs == {} + + +# --------------------------------------------------------------------------- +# Week 6: pull (fast-forward), safe checkout, merge results +# --------------------------------------------------------------------------- + + +class Repo: + """One repository: real object store, working tree and commit manager.""" + + def __init__(self, root): + self.root = str(root) + os.makedirs(self.root, exist_ok=True) + self.store = ObjectStore(self.root) + self.wt = WorkingTree(self.root, store=self.store) + self.cm = CommitManager(self.root, store=self.store, tree=self.wt) + + def path(self, name): + return os.path.join(self.root, name) + + def write(self, name, content, mode=None): + full = self.path(name) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "wb") as f: + f.write(content if isinstance(content, bytes) else content.encode()) + if mode is not None: + os.chmod(full, mode) + + def read(self, name): + with open(self.path(name), "rb") as f: + return f.read() + + def exists(self, name): + return os.path.lexists(self.path(name)) + + def remove(self, name): + os.remove(self.path(name)) + + def stage(self, *names): + for name in names: + self.wt.stage_file(name) + + def commit(self, message, extra_parents=()): + """Commit whatever is in the index on the current branch.""" + branch = self.cm._current_branch() + tip = self.cm.read_ref(branch) + parents = ([tip] if tip else []) + list(extra_parents) + tree = self.wt.build_tree_from_index() + return self.cm.create_commit(tree, parents, "Test ", message) + + def snapshot(self): + """Everything that defines repo state: files on disk, index, refs, HEAD.""" + files = {} + for dirpath, dirnames, filenames in os.walk(self.root): + dirnames[:] = [d for d in dirnames if d not in {".minigit"}] + for name in filenames: + full = os.path.join(dirpath, name) + rel = os.path.relpath(full, self.root) + with open(full, "rb") as f: + files[rel] = (f.read(), os.access(full, os.X_OK)) + meta = {} + for sub in ("index", "HEAD"): + full = os.path.join(self.root, ".minigit", sub) + if os.path.exists(full): + with open(full, "rb") as f: + meta[sub] = f.read() + refs = os.path.join(self.root, ".minigit", "refs", "heads") + if os.path.isdir(refs): + for name in sorted(os.listdir(refs)): + with open(os.path.join(refs, name), "rb") as f: + meta[f"ref:{name}"] = f.read() + return files, meta + + def object_files(self): + found = {} + for dirpath, _, filenames in os.walk(os.path.join(self.root, ".minigit", "objects")): + for name in filenames: + full = os.path.join(dirpath, name) + found[full] = os.path.getmtime(full) + return found + + +def download(source: Repo, target: Repo, branch="main", as_ref="theirs"): + """Stand-in for fetch: copy every object over and point `as_ref` at the source tip.""" + src_objects = os.path.join(source.root, ".minigit", "objects") + dst_objects = os.path.join(target.root, ".minigit", "objects") + shutil.copytree(src_objects, dst_objects, dirs_exist_ok=True) + target.cm.write_ref(as_ref, source.cm.read_ref(branch)) + + +def status_text(repo, monkeypatch, capsys): + monkeypatch.chdir(repo.root) + assert cmd_status(None) == 0 + return capsys.readouterr().out + + +def diff_text(repo, monkeypatch, capsys): + monkeypatch.chdir(repo.root) + assert cmd_diff(None) == 0 + return capsys.readouterr().out + + +@pytest.fixture +def source(tmp_path): + """A 'remote' repo with one commit: nested dirs, an executable, binary, unicode.""" + repo = Repo(tmp_path / "source") + repo.write("README.md", "hello\n") + repo.write("src/app.py", "print('v1')\n") + repo.write("src/deep/util.py", "x = 1\n") + repo.write("run.sh", "#!/bin/sh\necho hi\n", mode=0o755) + repo.write("data.bin", b"\x00\x01\xff\xfe") + repo.write("café.txt", "crème\n") + repo.write("noeol.txt", "no newline at end") + repo.stage( + "README.md", "src/app.py", "src/deep/util.py", "run.sh", "data.bin", "café.txt", + "noeol.txt", + ) # fmt: skip + repo.commit("first") + return repo + + +@pytest.fixture +def local(tmp_path): + return Repo(tmp_path / "local") + + +# --------------------------------------------------------------------------- +# Fast-forward: files, deletions, nested directories, modes, index, status +# --------------------------------------------------------------------------- + + +def test_fast_forward_into_fresh_repo_restores_everything(source, local, monkeypatch, capsys): + download(source, local) + + local.cm.merge("theirs") + + assert local.read("README.md") == b"hello\n" + assert local.read("src/deep/util.py") == b"x = 1\n" + assert local.read("data.bin") == b"\x00\x01\xff\xfe" + assert local.read("café.txt") == "crème\n".encode() + assert local.read("noeol.txt") == b"no newline at end" + assert os.access(local.path("run.sh"), os.X_OK) + assert not os.access(local.path("README.md"), os.X_OK) + assert [e.path for e in local.wt.read_index()] == sorted(e.path for e in source.wt.read_index()) + assert local.cm._current_branch() == "main" + assert local.cm.read_ref("main") == source.cm.read_ref("main") + assert status_text(local, monkeypatch, capsys) == BRANCH + "clean\n" + assert diff_text(local, monkeypatch, capsys) == "" + + +def test_second_fast_forward_applies_edit_delete_new_dir_and_mode( + source, local, monkeypatch, capsys +): + download(source, local) + local.cm.merge("theirs") + + source.write("README.md", "hello again\n") + source.remove("src/deep/util.py") # last file in src/deep -> directory must go too + source.write("docs/guide/intro.md", "intro\n") + os.chmod(source.path("run.sh"), 0o644) + source.stage("README.md", "src/deep/util.py", "docs/guide/intro.md", "run.sh") + source.commit("second") + download(source, local) + + local.cm.merge("theirs") + + assert local.read("README.md") == b"hello again\n" + assert not local.exists("src/deep/util.py") + assert not local.exists("src/deep") + assert local.read("docs/guide/intro.md") == b"intro\n" + assert not os.access(local.path("run.sh"), os.X_OK) + assert local.cm._current_branch() == "main" + assert status_text(local, monkeypatch, capsys) == BRANCH + "clean\n" + assert diff_text(local, monkeypatch, capsys) == "" + + +# --------------------------------------------------------------------------- +# Local work is preserved; validation failures change nothing +# --------------------------------------------------------------------------- + + +@pytest.fixture +def synced(source, local): + """`local` already has the first commit; `source` then moves ahead.""" + download(source, local) + local.cm.merge("theirs") + source.write("README.md", "hello from upstream\n") + source.write("added.txt", "new upstream file\n") + source.stage("README.md", "added.txt") + source.commit("second") + download(source, local) + return source, local + + +def test_dirty_tracked_file_blocks_pull_and_is_kept(synced): + _, local = synced + local.write("README.md", "my local edit\n") + before = local.snapshot() + + with pytest.raises( + MiniGitError, match="local changes would be lost: README.md; commit or undo your edits" + ): + local.cm.merge("theirs") + + assert local.snapshot() == before + assert local.read("README.md") == b"my local edit\n" + assert not local.exists("added.txt") + + +def test_untracked_collision_blocks_pull_and_is_kept(synced): + _, local = synced + local.write("added.txt", "my untracked file\n") + before = local.snapshot() + + with pytest.raises(MiniGitError): + local.cm.merge("theirs") + + assert local.snapshot() == before + assert local.read("added.txt") == b"my untracked file\n" + + +def test_missing_blob_leaves_files_and_index_untouched(synced): + source, local = synced + new_blob = next(e.hash for e in source.wt.read_index() if e.path == "added.txt") + os.remove(os.path.join(local.root, ".minigit", "objects", new_blob[:2], new_blob[2:])) + before = local.snapshot() + + with pytest.raises(ObjectNotFoundError): + local.cm.merge("theirs") + + assert local.snapshot() == before + + +def test_unsafe_path_in_incoming_tree_changes_nothing(local): + local.write("keep.txt", "mine\n") + local.stage("keep.txt") + local.commit("base") + blob = local.store.write_object(b"evil", "blob") + sub = local.store.write_tree([TreeEntry("100644", "blob", blob, "x")]) + # a tree whose directory is named ".minigit" would write inside the repo's own data + tree = local.store.write_tree( + [ + TreeEntry("40000", "tree", sub, ".minigit"), + TreeEntry("100644", "blob", blob, "keep.txt"), + ] + ) + before = local.snapshot() + + with pytest.raises(MiniGitError): + local.wt.checkout(tree) + + assert local.snapshot() == before + + +# --------------------------------------------------------------------------- +# Status and diff are read-only +# --------------------------------------------------------------------------- + + +def test_status_and_diff_do_not_change_the_repo(synced, monkeypatch, capsys): + _, local = synced + local.cm.merge("theirs") + local.write("README.md", "edited after pull\n") + local.write("untracked.txt", "u\n") + local.write("staged.txt", "s\n") + local.stage("staged.txt") + before_state = local.snapshot() + before_objects = local.object_files() + + status_text(local, monkeypatch, capsys) + diff_text(local, monkeypatch, capsys) + + assert local.snapshot() == before_state + assert local.object_files() == before_objects + + +# --------------------------------------------------------------------------- +# Merge results: markers on disk, pre-merge index entries, resolution via `add` +# --------------------------------------------------------------------------- + +MARKERS = b"<<<<<<< ours\nmine\n=======\ntheirs\n>>>>>>> theirs\n" + + +@pytest.fixture +def merging(local): + """A repo with a commit, plus the tree M3 would build for a conflicting merge.""" + local.write("a.txt", "base\n") + local.write("b.txt", "unchanged\n") + local.stage("a.txt", "b.txt") + local.commit("ours") + marker_blob = local.store.write_object(MARKERS, "blob") + clean_blob = local.store.write_object(b"added by theirs\n", "blob") + b_blob = next(e.hash for e in local.wt.read_index() if e.path == "b.txt") + merged_tree = local.store.write_tree( + [ + TreeEntry("100644", "blob", marker_blob, "a.txt"), + TreeEntry("100644", "blob", b_blob, "b.txt"), + TreeEntry("100644", "blob", clean_blob, "c.txt"), + ] + ) + return local, merged_tree + + +def test_conflicted_path_gets_markers_but_keeps_pre_merge_index_entry(merging, monkeypatch, capsys): + local, merged_tree = merging + old_a = next(e for e in local.wt.read_index() if e.path == "a.txt") + + local.wt.checkout(merged_tree, conflicted_paths={"a.txt"}) + + assert local.read("a.txt") == MARKERS + assert local.read("c.txt") == b"added by theirs\n" + index = {e.path: e for e in local.wt.read_index()} + assert index["a.txt"] == old_a + assert index["c.txt"].hash == hashlib.sha1(b"blob 16\0added by theirs\n").hexdigest() + assert ( + status_text(local, monkeypatch, capsys) + == BRANCH + "staged:\n c.txt\nnot staged:\n a.txt\n" + ) + + +def test_conflicted_checkout_of_unknown_path_is_refused_before_any_write(merging): + local, merged_tree = merging + before = local.snapshot() + + with pytest.raises(MiniGitError): + local.wt.checkout(merged_tree, conflicted_paths={"nope.txt"}) + + assert local.snapshot() == before + + +def test_resolve_with_add_then_commit_is_clean_across_fresh_objects(merging, monkeypatch, capsys): + local, merged_tree = merging + local.wt.checkout(merged_tree, conflicted_paths={"a.txt"}) + theirs_tip = local.cm.read_ref("main") # stand-in for the second parent + + # each step below uses brand-new objects, like separate CLI processes would + fresh = Repo(local.root) + fresh.write("a.txt", "resolved by hand\n") + monkeypatch.chdir(fresh.root) + assert cmd_add(argparse.Namespace(path="a.txt")) == 0 + + fresh = Repo(local.root) + assert status_text(fresh, monkeypatch, capsys) == BRANCH + "staged:\n a.txt\n c.txt\n" + + fresh = Repo(local.root) + fresh.commit("merge", extra_parents=[theirs_tip]) + + fresh = Repo(local.root) + assert status_text(fresh, monkeypatch, capsys) == BRANCH + "clean\n" + assert fresh.read("a.txt") == b"resolved by hand\n" + assert len(fresh.cm.read_commit(fresh.cm.read_ref("main")).parents) == 2 + + +def test_resolved_deletion_with_add_then_commit(merging, monkeypatch, capsys): + local, merged_tree = merging + local.wt.checkout(merged_tree, conflicted_paths={"a.txt"}) + + local.remove("a.txt") + monkeypatch.chdir(local.root) + assert cmd_add(argparse.Namespace(path="a.txt")) == 0 + + fresh = Repo(local.root) + assert [e.path for e in fresh.wt.read_index()] == ["b.txt", "c.txt"] + assert status_text(fresh, monkeypatch, capsys) == BRANCH + "staged:\n a.txt\n c.txt\n" + fresh.commit("merge: delete a.txt") + fresh = Repo(local.root) + assert status_text(fresh, monkeypatch, capsys) == BRANCH + "clean\n" + assert not fresh.exists("a.txt") + + +def test_add_of_a_missing_untracked_path_still_fails(local): + with pytest.raises(MiniGitError, match="No such file"): + local.wt.stage_file("never-existed.txt") + + +# --------------------------------------------------------------------------- +# Week 7: status / diff output, path display, error messages +# --------------------------------------------------------------------------- + + +def run_status(capsys): + assert cmd_status(None) == 0 + return capsys.readouterr().out + + +def test_status_empty_unborn_repo(cli_repo, capsys): + assert run_status(capsys) == BRANCH + "no commits yet\nclean\n" + + +def test_status_unborn_repo_lists_staged_files(cli_repo, capsys): + repo, _ = cli_repo + write(repo, "a.txt", "hi\n") + repo.stage_file("a.txt") + + assert run_status(capsys) == BRANCH + "no commits yet\nstaged:\n a.txt\n" + + +def test_status_staged_then_edited_file_is_in_both_sections(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "v1\n") + commit("a.txt") + write(repo, "a.txt", "v2\n") + repo.stage_file("a.txt") + write(repo, "a.txt", "v3\n") + + assert run_status(capsys) == BRANCH + "staged:\n a.txt\nnot staged:\n a.txt\n" + + +def test_status_paths_are_sorted_and_handle_nesting_spaces_and_unicode(cli_repo, capsys): + repo, _ = cli_repo + for name in ["z.txt", "dir/sub/b file.txt", "café/é.txt", "a.txt"]: + write(repo, name, "x\n") + + expected = ["a.txt", "café/é.txt", "dir/sub/b file.txt", "z.txt"] + assert run_status(capsys) == ( + BRANCH + "no commits yet\nuntracked:\n" + "".join(f" {p}\n" for p in expected) + ) + + +def test_display_path_escapes_only_unprintable_paths(): + assert display_path("my dir/café é.txt") == "my dir/café é.txt" + assert display_path("a\nb.txt") == '"a\\nb.txt"' + assert display_path("a\\b.txt") == '"a\\\\b.txt"' + assert display_path("x.txt", "a/") == "a/x.txt" + assert display_path("x\ty.txt", "a/") == '"a/x\\ty.txt"' + + +def test_status_first_line_names_the_branch_or_detached_head(tmp_path, monkeypatch, capsys): + (tmp_path / "f.txt").write_text("x") + wt = WorkingTree(tmp_path) + wt.stage_file("f.txt") + manager = CommitManager(tmp_path) + commit = manager.create_commit(wt.build_tree_from_index(), [], "Test", "initial") + monkeypatch.chdir(tmp_path) + + manager.write_head("feature") + assert run_status(capsys).splitlines()[0] == "On branch feature" + + (tmp_path / ".minigit" / "HEAD").write_text(commit + "\n") + assert run_status(capsys).splitlines()[0] == f"HEAD detached at {commit[:7]}" + + +def test_status_lists_unresolved_merge_paths_from_the_manager(cli_repo, capsys, monkeypatch): + repo, _ = cli_repo + write(repo, "a.txt", "x\n") + monkeypatch.setattr( + sys.modules["minigit.commits"].CommitManager, + "unresolved_merge_paths", + lambda self: ["a.txt"], + raising=False, + ) + + assert run_status(capsys) == ( + BRANCH + "no commits yet\nunresolved (merge conflict):\n a.txt\nuntracked:\n a.txt\n" + ) + + +def apply_printed_hunks(old_lines, diff_lines): + """Apply the printed hunks to old_lines (all lines end in "\\n") - checks the numbers.""" + result, pos, hunks = [], 0, [] + for line in diff_lines: + if line.startswith("@@"): + hunks.append((re.fullmatch(r"@@ -(\d+),(\d+) \+(\d+),(\d+) @@", line).groups(), [])) + elif hunks: + hunks[-1][1].append(line) + for (old_start, old_count, new_start, new_count), body in hunks: + old_start, old_count, new_start, new_count = map( + int, (old_start, old_count, new_start, new_count) + ) + first_old = old_start if old_count == 0 else old_start - 1 + result += old_lines[pos:first_old] + pos = first_old + assert len(result) == (new_start if new_count == 0 else new_start - 1) + seen_old = seen_new = 0 + for line in body: + text = line[1:] + "\n" + if line[0] in " -": + assert old_lines[pos] == text + pos += 1 + seen_old += 1 + if line[0] in " +": + result.append(text) + seen_new += 1 + assert (seen_old, seen_new) == (old_count, new_count) + return result + old_lines[pos:] + + +def test_printed_hunks_rebuild_the_new_file_for_any_context_size(repo): + from minigit.index import _format_change + + random.seed(3) + for _ in range(300): + old = [random.choice("abc") + "\n" for _ in range(random.randint(0, 14))] + new = [random.choice("abc") + "\n" for _ in range(random.randint(0, 14))] + change = repo._make_change( + "f.txt", "modified", "100644", "100644", "".join(old).encode(), "".join(new).encode() + ) + for context in (0, 1, 3): + printed = _format_change(change, context) + assert apply_printed_hunks(old, printed) == new + + +def test_cli_empty_and_repeated_line_files(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "rep.txt", "x\nx\nx\n") + commit("rep.txt") + write(repo, "rep.txt", "x\nx\n") + write(repo, "empty.txt", "") + + out = run_diff(capsys).splitlines() + + assert "diff --minigit a/empty.txt b/empty.txt" in out + assert "new file mode 100644" in out + assert [line for line in out if line.startswith("@@")] == ["@@ -1,3 +1,2 @@"] + assert out.count("-x") == 1 + + +def test_cli_binary_files_added_and_deleted_get_a_summary(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "gone.bin", b"\x00\x01") + commit("gone.bin") + os.remove("gone.bin") + write(repo, "new.bin", b"\x00\x02") + + out = run_diff(capsys).splitlines() + + assert "binary file deleted: gone.bin" in out + assert "binary file added: new.bin" in out + assert not any(line.startswith("@@") for line in out) + + +def test_cli_diff_shows_space_unicode_and_odd_paths_clearly(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "my dir/café notes.txt", "one\n") + commit("my dir/café notes.txt") + write(repo, "my dir/café notes.txt", "two\n") + write(repo, "odd\nname.txt", "new\n") # cannot be staged, but it can sit in the folder + + out = run_diff(capsys).splitlines() + status = run_status(capsys) + + assert "diff --minigit a/my dir/café notes.txt b/my dir/café notes.txt" in out + assert "--- a/my dir/café notes.txt" in out + assert '+++ "b/odd\\nname.txt"' in out + assert not any(line == "name.txt" for line in out) + assert ' "odd\\nname.txt"\n' in status + + +def test_cli_diff_output_is_plain_and_repeatable(cli_repo, capsys): + repo, commit = cli_repo + write(repo, "a.txt", "one\n") + commit("a.txt") + write(repo, "a.txt", "two\n") + + first = run_diff(capsys) + + assert first == run_diff(capsys) + assert "\x1b" not in first + + +def test_diff_help_says_head_tree_versus_working_files(monkeypatch): + from minigit.index import register_index_commands + + monkeypatch.setenv("COLUMNS", "200") + parser = argparse.ArgumentParser() + register_index_commands(parser.add_subparsers()) + + assert "the HEAD tree compared with the working files" in parser.format_help() + + +def test_status_and_diff_leave_an_unborn_repo_unchanged(local, monkeypatch, capsys): + local.write("a.txt", "x\n") + before, objects = local.snapshot(), local.object_files() + + status_text(local, monkeypatch, capsys) + diff_text(local, monkeypatch, capsys) + + assert local.snapshot() == before + assert local.object_files() == objects + + +def test_status_and_diff_leave_a_conflicted_repo_unchanged(merging, monkeypatch, capsys): + local, merged_tree = merging + local.wt.checkout(merged_tree, conflicted_paths={"a.txt"}) + before, objects = local.snapshot(), local.object_files() + + status_text(local, monkeypatch, capsys) + out = diff_text(local, monkeypatch, capsys) + + assert "<<<<<<< ours" in out + assert local.snapshot() == before + assert local.object_files() == objects + + +def test_expected_failures_name_the_path_and_the_next_step(repo): + with pytest.raises(MiniGitError, match=r"No such file: nope\.txt; check the path"): + repo.stage_file("nope.txt") + with pytest.raises(MiniGitError, match=r"cannot stage \.\./x\.txt: .*outside the repository"): + repo.stage_file("../x.txt") + write(repo, "odd\nname.txt", "x\n") + with pytest.raises(MiniGitError, match=r'cannot stage "odd\\nname.txt": names with a tab'): + repo.stage_file("odd\nname.txt") + os.makedirs(os.path.dirname(repo.index_path)) + with open(repo.index_path, "w") as f: + f.write("garbage\n") + with pytest.raises(MiniGitError, match=r"corrupt index: line 1 .*minigit add"): + repo.read_index() diff --git a/tests/test_week3_integration.py b/tests/test_week3_integration.py index bbc9b69..e18b0b4 100644 --- a/tests/test_week3_integration.py +++ b/tests/test_week3_integration.py @@ -16,7 +16,7 @@ def test_cli_commit_status_and_history(tmp_path, monkeypatch, capsys): assert main(["add", "src/hello.txt"]) == 0 capsys.readouterr() assert main(["status"]) == 0 - assert capsys.readouterr().out == "staged:\n src/hello.txt\n" + assert capsys.readouterr().out == "On branch main\nno commits yet\nstaged:\n src/hello.txt\n" assert main(["commit", "-m", "first"]) == 0 manager = CommitManager(tmp_path) first = manager.read_ref("main") @@ -26,12 +26,15 @@ def test_cli_commit_status_and_history(tmp_path, monkeypatch, capsys): assert manager.store.read_object(entries[0].hash) == ("blob", b"first") capsys.readouterr() assert main(["status"]) == 0 - assert capsys.readouterr().out == "clean\n" + assert capsys.readouterr().out == "On branch main\nclean\n" file.write_text("second") assert main(["add", "src/hello.txt"]) == 0 file.write_text("third") assert main(["status"]) == 0 - assert capsys.readouterr().out == "staged:\n src/hello.txt\nnot staged:\n src/hello.txt\n" + assert ( + capsys.readouterr().out + == "On branch main\nstaged:\n src/hello.txt\nnot staged:\n src/hello.txt\n" + ) assert main(["commit", "-m", "second"]) == 0 second = manager.read_ref("main") assert manager.read_commit(second).parents == [first] diff --git a/tests/test_week4_integration.py b/tests/test_week4_integration.py index faf7810..d484914 100644 --- a/tests/test_week4_integration.py +++ b/tests/test_week4_integration.py @@ -31,7 +31,7 @@ def test_week4_cli_checkpoint_and_push(tmp_path, monkeypatch, capsys): assert manager.read_ref("main") == manager.read_ref("feature") == b capsys.readouterr() assert main(["status"]) == 0 - assert capsys.readouterr().out.strip() == "clean" + assert capsys.readouterr().out.strip() == "On branch main\nclean" remote = tmp_path / "remote" remote.mkdir()