Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
docs: Use Rust test for README snapshot sync
Maximilian Roos71aa0ab6cd7f
diff --git a/README.md b/README.mdindex 29c8a9ae5..bff3f35b5 100644--- a/README.md+++ b/README.md@@ -799,13 +799,16 @@ git config worktrunk.status.feature-x "π¬"**Status appears in the Status column:**<!-- README:snapshot:tests/snapshots/integration__integration_tests__list__with_user_status.snap -->-```+```bash+$ wt listBranch Status HEADΒ± mainβ Path Remoteβ Commit Age Message@ main ^ ./test-repo b834638e 10mo Initial commit+ clean-no-status β ./clean-no-status b834638e 10mo Initial commit+ clean-with-status β π¬ ./clean-with-status b834638e 10mo Initial commit+ dirty-no-status ! +1 -1 ./dirty-no-status b834638e 10mo Initial commit+ dirty-with-status ?β π€ ./dirty-with-status b834638e 10mo Initial commit++βͺ Showing 5 worktrees, 1 with changes```<!-- README:end -->@@ -898,18 +901,18 @@ Commands from project hooks and LLM configuration require approval on first run.**Example approval prompt:**-<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_named_commands.snap -->+<!-- README:snapshot:tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_approval_prompt.snap -->```π‘ test-repo needs approval to execute 3 commands:π post-create install:- echo 'Installing dependencies...'+ echo 'Installing dependencies...'π post-create build:- echo 'Building project...'+ echo 'Building project...'π post-create test:- echo 'Running tests...'+ echo 'Running tests...'π‘ Allow and remember? [y/N]```diff --git a/dev/update-readme.py b/dev/update-readme.pydeleted file mode 100755index f5e1a8b19..000000000--- a/dev/update-readme.py+++ /dev/null@@ -1,338 +0,0 @@-#!/usr/bin/env python3-"""Update README.md with content from snapshot files.--This script manages README sections that reference snapshot test output.--USAGE:--1. Update README from snapshots:- python dev/update-readme.py-- Replaces marked sections with normalized snapshot content:- - Strips ANSI color codes- - Converts [SHA] to a1b2c3d- - Normalizes temp paths to relative paths--2. Check for staleness (useful in CI):- python dev/update-readme.py --check--MARKER FORMAT (add manually to README):--<!-- README:snapshot:path/to/snapshot.snap -->-```bash-$ command-... content from snapshot ...-```-<!-- README:end -->-"""--import re-import subprocess-import sys-from pathlib import Path---def strip_ansi(text: str) -> str:- """Remove ANSI escape codes from text.-- Handles both actual escape sequences (\x1b[...) and literal bracket- notation ([0m, [1m, etc.) as stored in snapshot files.- """- # Actual ANSI escape sequences- text = re.sub(r'\x1b\[[0-9;]*m', '', text)- # Literal bracket notation (as stored in snapshots)- text = re.sub(r'\[[0-9;]*m', '', text)- return text---def parse_snapshot(path: Path) -> str:- """Extract content from an insta snapshot file."""- content = path.read_text()-- # Remove YAML front matter- if content.startswith('---'):- # Find the end of YAML front matter- parts = content.split('---', 2)- if len(parts) >= 3:- content = parts[2].strip()-- # Handle insta_cmd format with stdout/stderr sections- if '----- stdout -----' in content:- stdout_match = re.search(r'----- stdout -----\n(.*?)----- stderr -----', content, re.DOTALL)- stderr_match = re.search(r'----- stderr -----\n(.*?)(?:\Z|----- )', content, re.DOTALL)-- # Use stdout if it has content (worktrunk output), otherwise use stderr- # Don't combine them - they're not temporally ordered- stdout_content = stdout_match.group(1).rstrip() if stdout_match else ""- stderr_content = stderr_match.group(1).rstrip() if stderr_match else ""-- if stdout_content:- content = stdout_content- else:- content = stderr_content-- # Strip ANSI codes- content = strip_ansi(content)-- return content---def get_help_output(command: str) -> str:- """Run a command and capture its help output.-- For long help (--help), extracts only the Usage section (before- documentation sections like "Operation", "Hooks", etc).- """- args = command.split()- result = subprocess.run(- args,- capture_output=True,- text=True,- cwd=Path(__file__).parent.parent- )- # Help goes to stdout- output = result.stdout if result.stdout else result.stderr- output = strip_ansi(output).strip()-- # For --help, extract only the Usage section- # Stop at first documentation section (indicated by title without indentation)- if '--help' in command:- lines = output.split('\n')- result_lines = []- in_header = True-- for line in lines:- # Check if we've reached a documentation section- # These are lines that start without indentation and aren't options- if not in_header and line and not line.startswith(' ') and not line.startswith('-'):- # Check for section headers (e.g., "Operation", "Hooks", "Examples")- if line[0].isupper() and not line.startswith('Usage:') and ':' not in line:- break-- result_lines.append(line)-- # We're past the title line after first line- if 'Usage:' in line:- in_header = False-- return '\n'.join(result_lines).strip()-- return output---def normalize_for_readme(content: str) -> str:- """Normalize snapshot output for README display.-- Converts test placeholders to realistic-looking values:- - [SHA] -> a1b2c3d (realistic commit hash)- - [TMPDIR]/test-repo.branch -> ../repo.branch/- - ./test-repo -> ./repo- """- # Replace SHA/HASH placeholders with a consistent realistic hash- content = re.sub(r'\[SHA\]', 'a1b2c3d', content)- content = re.sub(r'\[HASH\]', 'a1b2c3d', content)-- # Replace temp dir paths with readable relative paths- # Match [TMPDIR]/test-repo.branch (no trailing slash in replacement)- content = re.sub(- r'\[TMPDIR\]/test-repo\.(\S+?)(?=/|\s|$)',- r'../repo.\1',- content- )- # Also handle other temp path patterns- content = re.sub(- r'/(?:var/folders|tmp|private/tmp)[^/\s]*/[^/\s]*/test-repo\.(\S+?)(?=/|\s|$)',- r'../repo.\1',- content- )-- # Replace [REPO] placeholder with repo- content = re.sub(r'\[REPO\]', '../repo', content)-- return content---def update_readme(readme_path: Path, dry_run: bool = False) -> list[tuple[str, str, str]]:- """Update README with content from markers.-- Returns list of (marker_type, identifier, status) tuples.- """- content = readme_path.read_text()- updates = []-- # Pattern for snapshot markers- # <!-- README:snapshot:path/to/file.snap -->- # ```bash- # $ command- # content- # ```- # <!-- README:end -->- snapshot_pattern = re.compile(- r'(<!-- README:snapshot:([^\s]+) -->)\n'- r'```(\w+)\n'- r'(\$ [^\n]+\n)?' # Optional command line- r'(.*?)'- r'```\n'- r'(<!-- README:end -->)',- re.DOTALL- )-- # Pattern for help markers - finds first code block in section- help_pattern = re.compile(- r'(<!-- README:help:([^\n]+) -->)\n'- r'(.*?)' # Content before first code block- r'(```\n)'- r'(.*?)' # Code block content- r'(```)\n'- r'(.*?)' # Content after code block until end marker- r'(<!-- README:end -->)',- re.DOTALL- )-- project_root = readme_path.parent-- def replace_snapshot(match):- start_marker = match.group(1)- snap_path = match.group(2)- lang = match.group(3)- command = match.group(4) or ""- end_marker = match.group(6)-- full_path = project_root / snap_path- if not full_path.exists():- updates.append(('snapshot', snap_path, f'NOT FOUND: {full_path}'))- return match.group(0)-- try:- new_content = parse_snapshot(full_path)- new_content = normalize_for_readme(new_content)- updates.append(('snapshot', snap_path, 'updated'))- return f'{start_marker}\n```{lang}\n{command}{new_content}\n```\n{end_marker}'- except Exception as e:- updates.append(('snapshot', snap_path, f'ERROR: {e}'))- return match.group(0)-- def replace_help(match):- start_marker = match.group(1)- command = match.group(2)- before_code = match.group(3)- code_start = match.group(4)- after_code = match.group(7)- end_marker = match.group(8)-- try:- new_content = get_help_output(command)- updates.append(('help', command, 'updated'))- return f'{start_marker}\n{before_code}{code_start}{new_content}\n```\n{after_code}{end_marker}'- except Exception as e:- updates.append(('help', command, f'ERROR: {e}'))- return match.group(0)-- # Apply replacements- new_content = snapshot_pattern.sub(replace_snapshot, content)- new_content = help_pattern.sub(replace_help, new_content)-- if not dry_run and new_content != content:- readme_path.write_text(new_content)-- return updates---def check_staleness(readme_path: Path) -> list[tuple[str, str, bool]]:- """Check if README sections are stale compared to their source snapshots.-- Returns list of (snap_path, status, is_different) tuples.- """- content = readme_path.read_text()- results = []-- # Pattern for snapshot markers- snapshot_pattern = re.compile(- r'<!-- README:snapshot:([^\s]+) -->\n'- r'```\w*\n'- r'(?:\$ [^\n]+\n)?'- r'(.*?)'- r'```\n'- r'<!-- README:end -->',- re.DOTALL- )-- project_root = readme_path.parent-- for match in snapshot_pattern.finditer(content):- snap_path = match.group(1)- current_content = match.group(2).strip()-- full_path = project_root / snap_path- if not full_path.exists():- results.append((snap_path, 'NOT FOUND', True))- continue-- try:- snap_content = parse_snapshot(full_path)- snap_content = normalize_for_readme(snap_content)- is_different = snap_content.strip() != current_content- status = 'needs review' if is_different else 'ok'- results.append((snap_path, status, is_different))- except Exception as e:- results.append((snap_path, f'ERROR: {e}', True))-- return results---def main():- import argparse-- parser = argparse.ArgumentParser(description='Update README.md from snapshot files')- parser.add_argument('--check', action='store_true',- help='Check if sections are stale without updating')- parser.add_argument('--dry-run', action='store_true',- help='Show what would be updated without making changes')- parser.add_argument('--readme', type=Path, default=Path('README.md'),- help='Path to README.md')-- args = parser.parse_args()-- readme_path = args.readme- if not readme_path.is_absolute():- readme_path = Path(__file__).parent.parent / readme_path-- if not readme_path.exists():- print(f"Error: {readme_path} not found", file=sys.stderr)- sys.exit(1)-- if args.check:- results = check_staleness(readme_path)-- if not results:- print("No markers found in README.md")- sys.exit(0)-- has_stale = False- for snap_path, status, is_different in results:- indicator = "β οΈ " if is_different else "β "- print(f"{indicator} {snap_path}: {status}")- if is_different:- has_stale = True-- if has_stale:- print("\nSome sections may need manual review")- sys.exit(1)- else:- print("\nAll sections are up to date")- else:- updates = update_readme(readme_path, dry_run=args.dry_run)-- if not updates:- print("No markers found in README.md")- sys.exit(0)-- for marker_type, identifier, status in updates:- print(f"[{marker_type}] {identifier}: {status}")-- if args.dry_run:- print("\nDry run - no changes made")---if __name__ == '__main__':- main()diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex 4c25dd6b5..935006efa 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -30,6 +30,7 @@ pub mod list_pty;pub mod merge;pub mod post_start_commands;pub mod push;+pub mod readme_sync;pub mod remove;pub mod security;pub mod shell_wrapper;diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rsnew file mode 100644index 000000000..87ca32b68--- /dev/null+++ b/tests/integration_tests/readme_sync.rs@@ -0,0 +1,185 @@+//! README synchronization test+//!+//! Verifies that README.md examples stay in sync with their source snapshots.+//! This replaces the Python `dev/update-readme.py` script with a native Rust test.+//!+//! Run with: `cargo test --test integration readme_sync`+//!+//! To update README when snapshots change:+//! 1. Run this test to see which sections are out of sync+//! 2. Copy the expected content from the test output into README.md++use regex::Regex;+use std::fs;+use std::path::Path;+use std::sync::LazyLock;++/// Regex to find README snapshot markers+static MARKER_PATTERN: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(+ r"(?s)<!-- README:snapshot:([^\s]+) -->\n```\w*\n(?:\$ [^\n]+\n)?(.*?)```\n<!-- README:end -->",+ )+ .expect("Invalid marker regex")+});++/// Regex to strip ANSI escape codes (actual escape sequences)+static ANSI_ESCAPE_REGEX: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\x1b\[[0-9;]*m").expect("Invalid ANSI regex"));++/// Regex to strip literal bracket notation (as stored in snapshots)+static ANSI_LITERAL_REGEX: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\[[0-9;]*m").expect("Invalid literal ANSI regex"));++/// Regex for SHA placeholder+static SHA_REGEX: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\[SHA\]").expect("Invalid SHA regex"));++/// Regex for HASH placeholder (used by shell_wrapper tests)+static HASH_REGEX: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\[HASH\]").expect("Invalid HASH regex"));++/// Regex for TMPDIR paths+static TMPDIR_REGEX: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\[TMPDIR\]/test-repo\.([^\s/]+)").expect("Invalid TMPDIR regex"));++/// Regex for REPO placeholder+static REPO_REGEX: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\[REPO\]").expect("Invalid REPO regex"));++/// Strip ANSI escape codes from text+fn strip_ansi(text: &str) -> String {+ let text = ANSI_ESCAPE_REGEX.replace_all(text, "");+ ANSI_LITERAL_REGEX.replace_all(&text, "").to_string()+}++/// Parse content from an insta snapshot file+fn parse_snapshot(path: &Path) -> Result<String, String> {+ let content = fs::read_to_string(path)+ .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;++ // Remove YAML front matter+ let content = if content.starts_with("---") {+ let parts: Vec<&str> = content.splitn(3, "---").collect();+ if parts.len() >= 3 {+ parts[2].trim().to_string()+ } else {+ content+ }+ } else {+ content+ };++ // Handle insta_cmd format with stdout/stderr sections+ let content = if content.contains("----- stdout -----") {+ // Extract stdout section+ let stdout = if let Some(start) = content.find("----- stdout -----\n") {+ let after_header = &content[start + "----- stdout -----\n".len()..];+ if let Some(end) = after_header.find("----- stderr -----") {+ after_header[..end].trim_end().to_string()+ } else {+ after_header.trim_end().to_string()+ }+ } else {+ String::new()+ };++ // Extract stderr section+ let stderr = if let Some(start) = content.find("----- stderr -----\n") {+ let after_header = &content[start + "----- stderr -----\n".len()..];+ if let Some(end) = after_header.find("----- ") {+ after_header[..end].trim_end().to_string()+ } else {+ after_header.trim_end().to_string()+ }+ } else {+ String::new()+ };++ // Use stdout if it has content, otherwise stderr+ if !stdout.is_empty() { stdout } else { stderr }+ } else {+ content+ };++ // Strip ANSI codes+ Ok(strip_ansi(&content))+}++/// Normalize snapshot output for README display+fn normalize_for_readme(content: &str) -> String {+ let content = SHA_REGEX.replace_all(content, "a1b2c3d");+ let content = HASH_REGEX.replace_all(&content, "a1b2c3d");+ let content = TMPDIR_REGEX.replace_all(&content, "../repo.$1");+ let content = REPO_REGEX.replace_all(&content, "../repo");++ // Trim trailing whitespace from each line (matches pre-commit behavior)+ content+ .lines()+ .map(|line| line.trim_end())+ .collect::<Vec<_>>()+ .join("\n")+}++#[test]+fn test_readme_examples_are_in_sync() {+ let project_root = Path::new(env!("CARGO_MANIFEST_DIR"));+ let readme_path = project_root.join("README.md");++ let readme_content = fs::read_to_string(&readme_path).expect("Failed to read README.md");++ let mut errors = Vec::new();+ let mut checked = 0;++ for cap in MARKER_PATTERN.captures_iter(&readme_content) {+ let snap_path = cap.get(1).unwrap().as_str();+ // Normalize README content: trim trailing whitespace from each line+ let current_content = cap+ .get(2)+ .unwrap()+ .as_str()+ .lines()+ .map(|line| line.trim_end())+ .collect::<Vec<_>>()+ .join("\n");+ let current_content = current_content.trim();+ checked += 1;++ let full_path = project_root.join(snap_path);++ // Parse and normalize the snapshot+ let expected = match parse_snapshot(&full_path) {+ Ok(content) => normalize_for_readme(&content),+ Err(e) => {+ errors.push(format!("β {}: {}", snap_path, e));+ continue;+ }+ };++ let expected = expected.trim();++ // Compare+ if current_content != expected {+ errors.push(format!(+ "β {} is out of sync\n\n--- Current (in README) ---\n{}\n\n--- Expected (from snapshot) ---\n{}\n",+ snap_path, current_content, expected+ ));+ }+ }++ if checked == 0 {+ panic!("No README:snapshot markers found in README.md");+ }++ if !errors.is_empty() {+ panic!(+ "README examples are out of sync with snapshots:\n\n{}\n\n\+ To fix: Update the README sections with the expected content above.\n\+ Checked {} markers, {} out of sync.",+ errors.join("\n"),+ checked,+ errors.len()+ );+ }++ // Test passes implicitly - no errors found+}diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex e63e950b2..e800daea8 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -2277,4 +2277,125 @@ fiassert_eq!(output.exit_code, 0, "Switch should succeed");assert_snapshot!(output.normalized());}++ /// README example: approval prompt for post-create commands+ /// This test captures just the prompt (before responding) to show what users see.+ ///+ /// Note: This uses direct PTY execution (not shell wrapper) because interactive prompts+ /// require direct stdin access. The shell wrapper approach detects non-interactive mode.+ /// The shell integration hint is truncated from the output.+ #[test]+ fn test_readme_example_approval_prompt() {+ use portable_pty::{CommandBuilder, PtySize, native_pty_system};+ use std::io::{Read, Write};++ let repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create project config with named post-create commands+ repo.write_project_config(+ r#"[post-create-command]+install = "echo 'Installing dependencies...'"+build = "echo 'Building project...'"+test = "echo 'Running tests...'"+"#,+ );+ repo.commit("Add config");++ // Direct PTY execution (not through shell wrapper) for interactive prompt+ let pty_system = native_pty_system();+ let pair = pty_system+ .openpty(PtySize {+ rows: 48,+ cols: 200,+ pixel_width: 0,+ pixel_height: 0,+ })+ .expect("Failed to open PTY");++ let cargo_bin = get_cargo_bin("wt");+ let mut cmd = CommandBuilder::new(cargo_bin);+ cmd.arg("switch");+ cmd.arg("--create");+ cmd.arg("test-approval");+ cmd.cwd(repo.root_path());++ // Set environment+ cmd.env_clear();+ cmd.env(+ "HOME",+ std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string()),+ );+ cmd.env(+ "PATH",+ std::env::var("PATH").unwrap_or_else(|_| "/usr/bin:/bin".to_string()),+ );+ for (key, value) in repo.test_env_vars() {+ cmd.env(key, value);+ }++ let mut child = pair+ .slave+ .spawn_command(cmd)+ .expect("Failed to spawn command in PTY");+ drop(pair.slave);++ let mut reader = pair+ .master+ .try_clone_reader()+ .expect("Failed to clone PTY reader");+ let mut writer = pair.master.take_writer().expect("Failed to get PTY writer");++ // Send "n" to decline and complete the command+ writer+ .write_all(b"n\n")+ .expect("Failed to write input to PTY");+ writer.flush().expect("Failed to flush PTY writer");+ drop(writer);++ // Read all output+ let mut buf = String::new();+ reader+ .read_to_string(&mut buf)+ .expect("Failed to read PTY output");+ child.wait().expect("Failed to wait for child");++ // Normalize: strip ANSI codes and control characters+ let ansi_regex = regex::Regex::new(r"\x1b\[[0-9;]*m").unwrap();+ let output = ansi_regex+ .replace_all(&buf, "")+ .replace("\r\n", "\n")+ .to_string();++ // Remove ^D and backspaces (macOS PTY artifacts)+ let ctrl_d_regex = regex::Regex::new(r"\^D\x08+").unwrap();+ let output = ctrl_d_regex.replace_all(&output, "").to_string();++ // Normalize paths+ let output = TMPDIR_REGEX.replace_all(&output, "[TMPDIR]").to_string();+ let output = TMPDIR_PLACEHOLDER_COLLAPSE_REGEX+ .replace_all(&output, "[TMPDIR]")+ .to_string();++ assert!(+ output.contains("needs approval"),+ "Should show approval prompt"+ );+ assert!(+ output.contains("[y/N]"),+ "Should show the interactive prompt"+ );++ // Extract just the prompt portion (from "π‘" to "[y/N]")+ // This removes the echoed input at the start and anything after the prompt+ let prompt_start = output.find("π‘").unwrap_or(0);+ let prompt_end = output.find("[y/N]").map(|i| i + "[y/N]".len());+ let prompt_only = if let Some(end) = prompt_end {+ output[prompt_start..end].trim().to_string()+ } else {+ output[prompt_start..].trim().to_string()+ };++ assert_snapshot!(prompt_only);+ }}diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_approval_prompt.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_approval_prompt.snapnew file mode 100644index 000000000..5933bb828--- /dev/null+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_approval_prompt.snap@@ -0,0 +1,17 @@+---+source: tests/integration_tests/shell_wrapper.rs+assertion_line: 2396+expression: prompt_only+---+π‘ test-repo needs approval to execute 3 commands:++π post-create install:+ echo 'Installing dependencies...'++π post-create build:+ echo 'Building project...'++π post-create test:+ echo 'Running tests...'++π‘ Allow and remember? [y/N]