Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Update README and add test for pre/post-merge hooks
Maximilian Roos0aaa5f1c939c
diff --git a/README.md b/README.mdindex c7ed878ab..cda0713e3 100644--- a/README.md+++ b/README.md@@ -70,8 +70,6 @@ wt config shell # Sets up shell integrationDuring merge operations, worktrunk can invoke a binary, such as [llm](https://llm.datasette.io/), to generate commit messages based on the diff and a configurable prompt.-<!-- Config and output from: tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap (uses mock llm) -->-Add to `~/.config/worktrunk/config.toml`:```toml@@ -82,6 +80,8 @@ args = ["-m", "claude-haiku-4-5-20251001"]Then `wt merge` will generate commit messages automatically:+<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_complex.snap -->+```bash$ wt mergeπ Generating squash commit message...@@ -129,6 +129,8 @@ Automate common tasks by creating `.config/wt.toml` in your repository root. Run**Example: Creating a worktree with hooks:**+<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snap -->+```bash$ wt switch --create feature-xπ Creating worktree for feature-x...@@ -147,6 +149,8 @@ $ wt switch --create feature-x**Example: Merging with pre-merge hooks:**+<!-- Output from: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snap -->+```bash$ wt mergeπ Squashing 3 commits into 1 (2 files, +45)...@@ -391,7 +395,7 @@ Now when you use Claude:**Status from other terminal:**-<!-- from tests/snapshots/integration__integration_tests__list__with_user_status.snap -->+<!-- Output from: tests/snapshots/integration__integration_tests__list__with_user_status.snap -->```bash$ wt listdiff --git a/tests/CLAUDE.md b/tests/CLAUDE.mdnew file mode 100644index 000000000..b5d5cbabc--- /dev/null+++ b/tests/CLAUDE.md@@ -0,0 +1,109 @@+# Testing Guidelines++## README Examples and Snapshot Testing++### Problem: Separated stdout/stderr in Standard Snapshots++README examples need to show output as users see it in their terminal - with stdout and stderr interleaved in the order they appear. However, the standard `insta_cmd` snapshot testing (used in most integration tests) separates stdout and stderr into different sections:++```yaml+----- stdout -----+π Running pre-merge test:+ uv run pytest++----- stderr -----+============================= test session starts ==============================+collected 18 items+...+```++This makes snapshots **not directly copyable** into README.md because:+1. The output is split into two sections+2. We lose the temporal ordering (which output appeared first)+3. Users never see this separation - their terminal shows combined output++### Solution: Use PTY-based Testing for README Examples++For tests that generate README examples, use the PTY-based execution pattern from `tests/integration_tests/shell_wrapper.rs`:++**Key function:** `exec_in_pty()` (line 235)+- Uses `portable_pty` to execute commands in a pseudo-terminal+- Returns combined stdout+stderr as a single `String`+- Captures output exactly as users see it in their terminal+- Includes ANSI color codes and proper temporal ordering++**Pattern to use:**++```rust+use portable_pty::{CommandBuilder, PtySize, native_pty_system};++fn exec_in_pty(+ shell: &str,+ script: &str,+ working_dir: &Path,+ env_vars: &[(String, String)],+) -> (String, i32) {+ // Execute command in PTY+ // Returns (combined_output, exit_code)+}++// In your test:+let (combined_output, exit_code) = exec_in_pty("bash", "wt merge", &repo_path, &env_vars);+assert_snapshot!("readme_example_name", combined_output);+```++**Benefits:**+- Output is directly copyable to README.md+- Shows actual user experience (interleaved stdout/stderr)+- Preserves temporal ordering of output+- No manual merging of stdout/stderr needed++**Example:** See `tests/integration_tests/shell_wrapper.rs`:+- Line 65-66: `ShellOutput` struct with `combined: String`+- Line 235-323: `exec_in_pty()` implementation using `portable_pty`+- Line 397+: Usage pattern in tests++### When to Use Each Approach++**Use `insta_cmd` (standard snapshots):**+- Unit and integration tests focused on correctness+- Tests that need to verify stdout/stderr separately+- Tests checking exit codes and specific error messages+- Most tests in the codebase++**Use `exec_in_pty` (PTY-based snapshots):**+- Tests generating output for README.md examples+- Tests verifying shell integration (`wt` function, directives)+- Tests needing to verify complete user experience+- Any test where temporal ordering of stdout/stderr matters++### Current Status++**README examples using PTY-based approach:**+- Shell wrapper tests (all of `tests/integration_tests/shell_wrapper.rs`)++**README examples using standard snapshots (working, but require manual editing):**+- `test_readme_example_simple()` - Quick start merge example+- `test_readme_example_complex()` - LLM-powered commit example+- `test_readme_example_hooks_post_create()` - Post-create hooks+- `test_readme_example_hooks_pre_merge()` - Pre-merge hooks++**Current workflow:** These tests work correctly and generate accurate snapshots. However, the snapshots separate stdout and stderr into different sections, which means they cannot be directly copied into README.md. Instead, the README examples are manually edited versions that merge stdout/stderr in the correct temporal order and remove ANSI codes.++**Future improvement:** Migrate README example tests to use PTY execution so snapshots are directly copyable into README.md without manual editing. This is an enhancement for developer convenience, not a bug fix.++### Migration Checklist++When converting a README example test from `insta_cmd` to PTY-based:++1. β Import `portable_pty` dependencies+2. β Extract or create `exec_in_pty()` helper (can reuse from shell_wrapper.rs)+3. β Replace `make_snapshot_cmd()` + `assert_cmd_snapshot!()` with `exec_in_pty()` + `assert_snapshot!()`+4. β Ensure environment variables include `CLICOLOR_FORCE=1` for ANSI codes+5. β Update snapshot file format (file snapshot, not inline)+6. β Verify output matches expected README format+7. β Update README.md to reference new snapshot location++### Implementation Note++The PTY approach is specifically for **user-facing output documentation**. It's not a replacement for standard integration tests - both approaches serve different purposes and should coexist in the test suite.diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex d0c9b3386..398dc3497 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1919,6 +1919,354 @@ command = "{}");}+/// Generate README example: Creating worktree with post-create and post-start hooks+/// This demonstrates the hooks feature with realistic tool output (uv sync, dev server).+///+/// Output is used in README.md "Project Hooks" section.+/// Source: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snap+#[test]+fn test_readme_example_hooks_post_create() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create project config with post-create and post-start hooks+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");++ // Create mock commands for realistic output+ let bin_dir = repo.root_path().join(".bin");+ fs::create_dir_all(&bin_dir).expect("Failed to create bin dir");++ // Mock uv command that simulates dependency installation+ let uv_script = r#"#!/bin/sh+if [ "$1" = "sync" ]; then+ echo ""+ echo " Resolved 24 packages in 145ms"+ echo " Installed 24 packages in 1.2s"+ exit 0+elif [ "$1" = "run" ] && [ "$2" = "dev" ]; then+ echo ""+ echo " Starting dev server on http://localhost:3000..."+ exit 0+else+ echo "uv: unknown command '$1 $2'"+ exit 1+fi+"#;+ fs::write(bin_dir.join("uv"), uv_script).expect("Failed to write uv script");++ // Make scripts executable (Unix only)+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut perms = fs::metadata(bin_dir.join("uv")).unwrap().permissions();+ perms.set_mode(0o755);+ fs::set_permissions(bin_dir.join("uv"), perms).unwrap();+ }++ let config_content = r#"+[post-create-command]+"install" = "uv sync"++[post-start-command]+"dev" = "uv run dev"+"#;++ fs::write(config_dir.join("wt.toml"), config_content).expect("Failed to write project config");++ // Commit the config+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", ".config/wt.toml", ".bin"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add config");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add project hooks"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to commit config");++ // Set PATH to include mock commands and run switch --create with --force+ let path_with_bin = format!(+ "{}:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",+ bin_dir.display()+ );++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd =+ make_snapshot_cmd(&repo, "switch", &["--create", "feature-x", "--force"], None);+ cmd.env("PATH", &path_with_bin);+ assert_cmd_snapshot!("readme_example_hooks_post_create", cmd);+ });+}++/// Generate README example: Merging with pre-merge hooks (test and lint)+/// This demonstrates the pre-merge hooks feature with realistic pytest and ruff output.+///+/// Output is used in README.md "Project Hooks" section.+/// Source: tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snap+#[test]+fn test_readme_example_hooks_pre_merge() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create project config with pre-merge hooks+ let config_dir = repo.root_path().join(".config");+ fs::create_dir_all(&config_dir).expect("Failed to create .config dir");++ // Create mock commands for realistic output+ let bin_dir = repo.root_path().join(".bin");+ fs::create_dir_all(&bin_dir).expect("Failed to create bin dir");++ // Mock pytest command+ let pytest_script = r#"#!/bin/sh+cat << 'EOF'++============================= test session starts ==============================+collected 3 items++tests/test_auth.py::test_login_success PASSED [ 33%]+tests/test_auth.py::test_login_invalid_password PASSED [ 66%]+tests/test_auth.py::test_token_validation PASSED [100%]++============================== 3 passed in 0.8s ===============================++EOF+exit 0+"#;+ fs::write(bin_dir.join("pytest"), pytest_script).expect("Failed to write pytest script");++ // Mock ruff command+ let ruff_script = r#"#!/bin/sh+if [ "$1" = "check" ]; then+ echo ""+ echo "All checks passed!"+ echo ""+ exit 0+else+ echo "ruff: unknown command '$1'"+ exit 1+fi+"#;+ fs::write(bin_dir.join("ruff"), ruff_script).expect("Failed to write ruff script");++ // Mock llm command for commit message+ let llm_script = r#"#!/bin/sh+cat > /dev/null+cat << 'EOF'+feat(api): Add user authentication endpoints++Implement login and token refresh endpoints with JWT validation.+Includes comprehensive test coverage and input validation.+EOF+"#;+ fs::write(bin_dir.join("llm"), llm_script).expect("Failed to write llm script");++ // Mock uv command for running pytest and ruff+ let uv_script = r#"#!/bin/sh+if [ "$1" = "run" ] && [ "$2" = "pytest" ]; then+ exec pytest+elif [ "$1" = "run" ] && [ "$2" = "ruff" ]; then+ shift 2+ exec ruff "$@"+else+ echo "uv: unknown command '$1 $2'"+ exit 1+fi+"#;+ fs::write(bin_dir.join("uv"), uv_script).expect("Failed to write uv script");++ // Make scripts executable (Unix only)+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ for script in &["pytest", "ruff", "llm", "uv"] {+ let mut perms = fs::metadata(bin_dir.join(script)).unwrap().permissions();+ perms.set_mode(0o755);+ fs::set_permissions(bin_dir.join(script), perms).unwrap();+ }+ }++ let config_content = r#"+[pre-merge-command]+"test" = "uv run pytest"+"lint" = "uv run ruff check"+"#;++ fs::write(config_dir.join("wt.toml"), config_content).expect("Failed to write project config");++ // Commit the config+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", ".config/wt.toml", ".bin"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add config");++ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add pre-merge hooks"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to commit config");++ // Create a worktree for main+ let main_wt = repo.root_path().parent().unwrap().join("test-repo.main-wt");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["worktree", "add", main_wt.to_str().unwrap(), "main"])+ .current_dir(repo.root_path())+ .output()+ .expect("Failed to add worktree");++ // Create a feature worktree and make multiple commits+ let feature_wt = repo.add_worktree("feature-auth", "feature-auth");++ // First commit - create initial auth.py with login endpoint+ fs::create_dir_all(feature_wt.join("api")).expect("Failed to create api dir");+ let auth_py_v1 = r#"# Authentication API endpoints+from typing import Dict, Optional+import jwt+from datetime import datetime, timedelta, timezone++def login(username: str, password: str) -> Optional[Dict]:+ """Authenticate user and return JWT token."""+ # Validate credentials (stub)+ if not username or not password:+ return None++ # Generate JWT token+ payload = {+ 'sub': username,+ 'exp': datetime.now(timezone.utc) + timedelta(hours=1)+ }+ token = jwt.encode(payload, 'secret', algorithm='HS256')+ return {'token': token, 'expires_in': 3600}+"#;+ std::fs::write(feature_wt.join("api/auth.py"), auth_py_v1).expect("Failed to write file");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "api/auth.py"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add login endpoint"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Second commit - add tests+ fs::create_dir_all(feature_wt.join("tests")).expect("Failed to create tests dir");+ let test_auth_py = r#"# Authentication endpoint tests+import pytest+from api.auth import login++def test_login_success():+ result = login('user', 'pass')+ assert result and 'token' in result++def test_login_invalid_password():+ result = login('user', '')+ assert result is None++def test_token_validation():+ assert login('valid_user', 'valid_pass')['expires_in'] == 3600+"#;+ std::fs::write(feature_wt.join("tests/test_auth.py"), test_auth_py)+ .expect("Failed to write file");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "tests/test_auth.py"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add authentication tests"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Third commit - add refresh endpoint+ let auth_py_v2 = r#"# Authentication API endpoints+from typing import Dict, Optional+import jwt+from datetime import datetime, timedelta, timezone++def login(username: str, password: str) -> Optional[Dict]:+ """Authenticate user and return JWT token."""+ # Validate credentials (stub)+ if not username or not password:+ return None++ # Generate JWT token+ payload = {+ 'sub': username,+ 'exp': datetime.now(timezone.utc) + timedelta(hours=1)+ }+ token = jwt.encode(payload, 'secret', algorithm='HS256')+ return {'token': token, 'expires_in': 3600}++def refresh_token(token: str) -> Optional[Dict]:+ """Refresh an existing JWT token."""+ try:+ payload = jwt.decode(token, 'secret', algorithms=['HS256'])+ new_payload = {+ 'sub': payload['sub'],+ 'exp': datetime.now(timezone.utc) + timedelta(hours=1)+ }+ new_token = jwt.encode(new_payload, 'secret', algorithm='HS256')+ return {'token': new_token, 'expires_in': 3600}+ except jwt.InvalidTokenError:+ return None+"#;+ std::fs::write(feature_wt.join("api/auth.py"), auth_py_v2).expect("Failed to write file");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "api/auth.py"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to add file");+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Add validation"])+ .current_dir(&feature_wt)+ .output()+ .expect("Failed to commit");++ // Configure LLM in worktrunk config+ let llm_path = bin_dir.join("llm");+ let worktrunk_config = format!(+ r#"+[commit-generation]+command = "{}"+"#,+ llm_path.display()+ );+ fs::write(repo.test_config_path(), worktrunk_config).expect("Failed to write worktrunk config");++ // Set PATH and merge with --force+ let path_with_bin = format!(+ "{}:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",+ bin_dir.display()+ );+ snapshot_merge_with_env(+ "readme_example_hooks_pre_merge",+ &repo,+ &["main", "--force"],+ Some(&feature_wt),+ &[("PATH", &path_with_bin)],+ );+}+#[test]fn test_merge_no_commit_with_clean_tree() {let mut repo = TestRepo::new();diff --git a/tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snap b/tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snapnew file mode 100644index 000000000..ac5318480--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__readme_example_hooks_post_create.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - feature-x+ - "--force"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ PATH: "/private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnTVEDc/test-repo/.bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnTVEDc/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mRunning post-create [1minstall[0m:[0m+[40m [0m [1m[34muv[0m sync[0m+β [32mCreated new worktree for [1m[32mfeature-x[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].feature-x[0m[0m+π‘ [2mTo enable automatic cd, run: wt config shell[0m+π [36mRunning post-start [1mdev[0m:[0m+[40m [0m [1m[34muv[0m run dev[0m++----- stderr -----+[0m+ Resolved 24 packages in 145ms+ Installed 24 packages in 1.2sdiff --git a/tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snap b/tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snapnew file mode 100644index 000000000..071236f88--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__readme_example_hooks_pre_merge.snap@@ -0,0 +1,59 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - merge+ - main+ - "--force"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ PATH: "/private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpp9hkDo/test-repo/.bin:/opt/homebrew/bin:/opt/homebrew/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpp9hkDo/test-config.toml+---+success: true+exit_code: 0+----- stdout -----+π [36mSquashing 3 commits into 1[0m (2 files, [32m+45[0m)...+π [36mGenerating squash commit message...[0m+[40m [0m [1mfeat(api): Add user authentication endpoints[0m+[40m [0m+[40m [0m Implement login and token refresh endpoints with JWT validation.+[40m [0m Includes comprehensive test coverage and input validation.+β [32mSquashed @ [2m[SHA][0m+π [36mRunning pre-merge [1mtest[0m:[0m+[40m [0m [1m[34muv[0m run pytest[0m+π [36mRunning pre-merge [1mlint[0m:[0m+[40m [0m [1m[34muv[0m run ruff check[0m+π [36mMerging 1 commit to [1m[36mmain[0m[36m @ [2m[SHA][0m (no rebase needed)++[40m [0m * [SHA][33m ([m[1;36mHEAD[m[33m -> [m[1;32mfeature-auth[m[33m)[m feat(api): Add user authentication endpoints+[40m [0m api/auth.py | 31 [32m+++++++++++++++++++++++++++++++[m+[40m [0m tests/test_auth.py | 14 [32m++++++++++++++[m+[40m [0m 2 files changed, 45 insertions(+)+β [32mMerged to [1m[32mmain[0m[0m (1 commit, 2 files, [32m+45[0m)+π [36mRemoving worktree & branch...[0m+β [32mRemoved worktree & branch for [1m[32mfeature-auth[0m[32m, returned to primary at [1m[32m[REPO][0m[0m++----- stderr -----+[0m+============================= test session starts ==============================+collected 3 items++tests/test_auth.py::test_login_success PASSED [ 33%]+tests/test_auth.py::test_login_invalid_password PASSED [ 66%]+tests/test_auth.py::test_token_validation PASSED [100%]++============================== 3 passed in 0.8s ===============================++[0m+All checks passed!