Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: simplify mock infrastructure with config-driven binary (#547)
Maximilian Roos56f8ee81d662
diff --git a/tests/common/mock_commands.rs b/tests/common/mock_commands.rsindex b838a8d3a..d10f44af3 100644--- a/tests/common/mock_commands.rs+++ b/tests/common/mock_commands.rs@@ -1,141 +1,229 @@// Cross-platform mock command helpers//// These helpers create mock executables that work on both Unix and Windows.-// All mock logic is written as shell scripts (#!/bin/sh).+// Mock behavior is defined via JSON config files, read by the mock-stub binary.//-// On Unix: shell scripts are directly executable via shebang-// On Windows: mock-stub.exe delegates to bash + shell script+// On Unix: mock-stub is copied as the command name (e.g., `gh`)+// On Windows: mock-stub.exe is copied as `gh.exe`//-// Requirements:-// - On Windows, Git Bash must be installed and `bash` must be in PATH-// - This matches production: hooks require Git Bash on Windows anyway+// Both platforms read `<command>.json` for configuration.//// This approach:-// - Single source of truth for mock behavior-// - Simpler than maintaining parallel shell/batch implementations+// - Single Rust binary for all platforms+// - No bash dependency+// - Config is just JSON - easy to generate and debug+use serde_json::json;+use std::collections::HashMap;use std::fs;use std::path::Path;-/// Path to the mock-stub.exe binary, built by `cargo test`.-#[cfg(windows)]-fn mock_stub_exe() -> std::path::PathBuf {- // The mock-stub binary is built by cargo test (via its dummy integration test)- // and lives in the same target directory as the test binary.+/// Path to the mock-stub binary, built by `cargo test`.+fn mock_stub_binary() -> std::path::PathBuf {let mut path = std::env::current_exe().expect("failed to get test executable path");path.pop(); // Remove test binary namepath.pop(); // Remove deps/++ #[cfg(windows)]path.push("mock-stub.exe");++ #[cfg(not(windows))]+ path.push("mock-stub");+path}-/// Write a mock shell script, with platform-appropriate setup.+/// Builder for mock command configuration.///-/// On Unix: writes directly as executable script-/// On Windows: writes script + copies mock-stub.exe as name.exe-pub fn write_mock_script(bin_dir: &Path, name: &str, script: &str) {+/// Example:+/// ```ignore+/// MockConfig::new("gh")+/// .version("gh version 2.0.0 (mock)")+/// .command("auth", MockResponse::exit(0))+/// .command("pr", MockResponse::file("pr_data.json"))+/// .write(bin_dir);+/// ```+pub struct MockConfig {+ name: String,+ version: Option<String>,+ commands: HashMap<String, MockResponse>,+}++/// How to respond to a command.+pub struct MockResponse {+ file: Option<String>,+ output: Option<String>,+ exit_code: i32,+}++impl MockResponse {+ /// Respond by reading contents from a file.+ pub fn file(path: &str) -> Self {+ Self {+ file: Some(path.to_string()),+ output: None,+ exit_code: 0,+ }+ }++ /// Respond with literal output.+ pub fn output(text: &str) -> Self {+ Self {+ file: None,+ output: Some(text.to_string()),+ exit_code: 0,+ }+ }++ /// Just exit with a code (no output).+ pub fn exit(code: i32) -> Self {+ Self {+ file: None,+ output: None,+ exit_code: code,+ }+ }++ /// Set exit code (chainable).+ pub fn with_exit_code(mut self, code: i32) -> Self {+ self.exit_code = code;+ self+ }++ fn to_json(&self) -> serde_json::Value {+ let mut obj = serde_json::Map::new();+ if let Some(f) = &self.file {+ obj.insert("file".to_string(), json!(f));+ }+ if let Some(o) = &self.output {+ obj.insert("output".to_string(), json!(o));+ }+ if self.exit_code != 0 || (self.file.is_none() && self.output.is_none()) {+ obj.insert("exit_code".to_string(), json!(self.exit_code));+ }+ serde_json::Value::Object(obj)+ }+}++impl MockConfig {+ /// Create a new mock config for the given command name.+ pub fn new(name: &str) -> Self {+ Self {+ name: name.to_string(),+ version: None,+ commands: HashMap::new(),+ }+ }++ /// Set the version string returned by `--version`.+ pub fn version(mut self, v: &str) -> Self {+ self.version = Some(v.to_string());+ self+ }++ /// Add a command handler.+ pub fn command(mut self, cmd: &str, response: MockResponse) -> Self {+ self.commands.insert(cmd.to_string(), response);+ self+ }++ /// Write the config and copy the mock binary to bin_dir.+ pub fn write(self, bin_dir: &Path) {+ let mut config = serde_json::Map::new();++ if let Some(v) = &self.version {+ config.insert("version".to_string(), json!(v));+ }++ let commands: serde_json::Map<String, serde_json::Value> = self+ .commands+ .iter()+ .map(|(k, v)| (k.clone(), v.to_json()))+ .collect();+ config.insert("commands".to_string(), serde_json::Value::Object(commands));++ let json = serde_json::to_string_pretty(&serde_json::Value::Object(config)).unwrap();++ // Write config file+ let config_path = bin_dir.join(format!("{}.json", self.name));+ fs::write(&config_path, json).unwrap();++ // Copy mock binary+ copy_mock_binary(bin_dir, &self.name);+ }+}++/// Copy the mock-stub binary to bin_dir with the given name.+pub fn copy_mock_binary(bin_dir: &Path, name: &str) {+ let stub = mock_stub_binary();+#[cfg(unix)]{use std::os::unix::fs::PermissionsExt;- let script_path = bin_dir.join(name);- fs::write(&script_path, script).unwrap();- fs::set_permissions(&script_path, fs::Permissions::from_mode(0o755)).unwrap();+ let dest = bin_dir.join(name);+ fs::copy(&stub, &dest).expect("failed to copy mock-stub binary");+ fs::set_permissions(&dest, fs::Permissions::from_mode(0o755)).unwrap();}#[cfg(windows)]{- // Write the shell script (no extension) - mock-stub.exe will invoke this via bash- let script_path = bin_dir.join(name);- fs::write(&script_path, script).unwrap();-- // Copy mock-stub.exe as name.exe (for Rust's Command::new which uses CreateProcessW)- let exe_path = bin_dir.join(format!("{}.exe", name));- fs::copy(mock_stub_exe(), &exe_path)- .expect("failed to copy mock-stub.exe - did `cargo test` build it?");-- // Create .bat/.cmd shims for CMD/PowerShell invocations.- // Not strictly required for our tests (Command::new finds .exe, Git Bash finds scripts),- // but provides a fallback if anyone debugs tests from cmd.exe.- let shim = format!("@bash \"%~dp0{}\" %*\n", name);- fs::write(bin_dir.join(format!("{}.cmd", name)), &shim).unwrap();- fs::write(bin_dir.join(format!("{}.bat", name)), &shim).unwrap();+ let dest = bin_dir.join(format!("{}.exe", name));+ fs::copy(&stub, &dest).expect("failed to copy mock-stub.exe");}}-/// Create a mock command that outputs fixed lines and exits.-///-/// Each line is echoed. Stdin is discarded (for mocks that receive piped input).-pub fn create_simple_mock(bin_dir: &Path, name: &str, output: &str, exit_code: i32) {- let echoes: String = output- .lines()- .map(|line| format!("echo '{}'\n", escape_shell_string(line)))- .collect();-- let script = format!(- r#"#!/bin/sh-cat > /dev/null-{echoes}exit {exit_code}-"#- );-- write_mock_script(bin_dir, name, &script);-}--/// Escape single quotes in shell strings.-fn escape_shell_string(s: &str) -> String {- s.replace('\'', "'\"'\"'")-}--// === High-level mock helpers for common test scenarios ===+// =============================================================================+// High-level mock helpers for common test scenarios+// =============================================================================/// Create a mock cargo command for tests.-///-/// Handles: test, clippy, install subcommands with realistic output.pub fn create_mock_cargo(bin_dir: &Path) {- write_mock_script(- bin_dir,- "cargo",- r#"#!/bin/sh-case "$1" in- test)- echo ' Finished test [unoptimized + debuginfo] target(s) in 0.12s'- echo ' Running unittests src/lib.rs (target/debug/deps/worktrunk-abc123)'- echo ''- echo 'running 18 tests'- echo 'test auth::tests::test_jwt_decode ... ok'- echo 'test auth::tests::test_jwt_encode ... ok'- echo 'test auth::tests::test_token_refresh ... ok'- echo 'test auth::tests::test_token_validation ... ok'- echo ''- echo 'test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s'- ;;- clippy)- echo ' Checking worktrunk v0.1.0'- echo ' Finished dev [unoptimized + debuginfo] target(s) in 1.23s'- ;;- install)- echo ' Installing worktrunk v0.1.0'- echo ' Compiling worktrunk v0.1.0'- echo ' Finished release [optimized] target(s) in 2.34s'- echo ' Installing ~/.cargo/bin/wt'- echo ' Installed package `worktrunk v0.1.0` (executable `wt`)'- ;;- *)- exit 1- ;;-esac-"#,- );+ MockConfig::new("cargo")+ .command(+ "test",+ MockResponse::output(+ " Finished test [unoptimized + debuginfo] target(s) in 0.12s+ Running unittests src/lib.rs (target/debug/deps/worktrunk-abc123)++running 18 tests+test auth::tests::test_jwt_decode ... ok+test auth::tests::test_jwt_encode ... ok+test auth::tests::test_token_refresh ... ok+test auth::tests::test_token_validation ... ok++test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s+",+ ),+ )+ .command(+ "clippy",+ MockResponse::output(+ " Checking worktrunk v0.1.0+ Finished dev [unoptimized + debuginfo] target(s) in 1.23s+",+ ),+ )+ .command(+ "install",+ MockResponse::output(+ " Installing worktrunk v0.1.0+ Compiling worktrunk v0.1.0+ Finished release [optimized] target(s) in 2.34s+ Installing ~/.cargo/bin/wt+ Installed package `worktrunk v0.1.0` (executable `wt`)+",+ ),+ )+ .write(bin_dir);}/// Create a mock llm command that outputs a commit message.-///-/// The commit message is suitable for JWT authentication feature commits.pub fn create_mock_llm_auth(bin_dir: &Path) {- create_simple_mock(- bin_dir,- "llm",- r#"feat(auth): Implement JWT authentication system+ MockConfig::new("llm")+ .command(+ "_default",+ MockResponse::output(+ "feat(auth): Implement JWT authentication systemAdd comprehensive JWT token handling including validation, refresh logic,and authentication tests. This establishes the foundation for secure@@ -143,72 +231,81 @@ API authentication.- Implement token refresh mechanism with expiry handling- Add JWT encoding/decoding with signature verification-- Create test suite covering all authentication flows"#,- 0,- );+- Create test suite covering all authentication flows",+ ),+ )+ .write(bin_dir);}/// Create a mock llm command for API endpoint commits.pub fn create_mock_llm_api(bin_dir: &Path) {- create_simple_mock(- bin_dir,- "llm",- r#"feat(api): Add user authentication endpoints+ MockConfig::new("llm")+ .command(+ "_default",+ MockResponse::output(+ "feat(api): Add user authentication endpointsImplement login and token refresh endpoints with JWT validation.-Includes comprehensive test coverage and input validation."#,- 0,- );+Includes comprehensive test coverage and input validation.",+ ),+ )+ .write(bin_dir);}/// Create a mock uv command for dependency sync and dev server.-///-/// Handles: `uv sync` (1 arg) and `uv run dev` (2 args).pub fn create_mock_uv_sync(bin_dir: &Path) {- write_mock_script(- bin_dir,- "uv",- r#"#!/bin/sh-if [ "$1" = "sync" ]; then- echo ''- echo ' Resolved 24 packages in 145ms'- echo ' Installed 24 packages in 1.2s'-elif [ "$1" = "run" ] && [ "$2" = "dev" ]; then- echo ''- echo ' Starting dev server on http://localhost:3000...'-else- echo "uv: unknown command '$1 $2'"- exit 1-fi-"#,- );+ MockConfig::new("uv")+ .command(+ "sync",+ MockResponse::output(+ "+ Resolved 24 packages in 145ms+ Installed 24 packages in 1.2s+",+ ),+ )+ .command(+ "run",+ MockResponse::output(+ "+ Starting dev server on http://localhost:3000...+",+ ),+ )+ .write(bin_dir);}/// Create mock uv that delegates to pytest/ruff commands.+///+/// Note: This mock doesn't actually delegate - it provides fixed output.+/// For tests needing real delegation, set up both commands separately.pub fn create_mock_uv_pytest_ruff(bin_dir: &Path) {- write_mock_script(- bin_dir,- "uv",- 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-"#,- );+ MockConfig::new("uv")+ .command(+ "run",+ MockResponse::output(+ "+============================= 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 ===============================+",+ ),+ )+ .write(bin_dir);}/// Create a mock pytest command with test output.pub fn create_mock_pytest(bin_dir: &Path) {- create_simple_mock(- bin_dir,- "pytest",- r#"+ MockConfig::new("pytest")+ .command(+ "_default",+ MockResponse::output(+ "============================= test session starts ==============================collected 3 items@@ -217,29 +314,17 @@ tests/test_auth.py::test_login_invalid_password PASSED [ 66%]tests/test_auth.py::test_token_validation PASSED [100%]============================== 3 passed in 0.8s ===============================-"#,- 0,- );+",+ ),+ )+ .write(bin_dir);}/// Create a mock ruff command.pub fn create_mock_ruff(bin_dir: &Path) {- write_mock_script(- bin_dir,- "ruff",- r#"#!/bin/sh-case "$1" in- check)- echo ''- echo 'All checks passed!'- echo ''- ;;- *)- exit 1- ;;-esac-"#,- );+ MockConfig::new("ruff")+ .command("check", MockResponse::output("\nAll checks passed!\n\n"))+ .write(bin_dir);}#[cfg(test)]@@ -248,40 +333,28 @@ mod tests {use tempfile::TempDir;#[test]- fn test_write_mock_script() {+ fn test_mock_config_write() {let temp = TempDir::new().unwrap();let bin_dir = temp.path();- write_mock_script(bin_dir, "test-cmd", "#!/bin/sh\necho 'hello'\n");-- #[cfg(unix)]- assert!(bin_dir.join("test-cmd").exists());-- #[cfg(windows)]- {- assert!(bin_dir.join("test-cmd").exists());- assert!(bin_dir.join("test-cmd.exe").exists());- assert!(bin_dir.join("test-cmd.cmd").exists());- assert!(bin_dir.join("test-cmd.bat").exists());- }- }+ MockConfig::new("test-cmd")+ .version("test-cmd version 1.0")+ .command("foo", MockResponse::output("hello"))+ .command("bar", MockResponse::exit(42))+ .write(bin_dir);- #[test]- fn test_create_simple_mock() {- let temp = TempDir::new().unwrap();- let bin_dir = temp.path();-- create_simple_mock(bin_dir, "simple-cmd", "Line 1\nLine 2\nLine 3", 0);+ // Check config file exists and is valid JSON+ let config_path = bin_dir.join("test-cmd.json");+ assert!(config_path.exists());+ let content = fs::read_to_string(&config_path).unwrap();+ let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();+ assert_eq!(parsed["version"], "test-cmd version 1.0");+ // Check binary exists#[cfg(unix)]- assert!(bin_dir.join("simple-cmd").exists());+ assert!(bin_dir.join("test-cmd").exists());#[cfg(windows)]- {- assert!(bin_dir.join("simple-cmd").exists());- assert!(bin_dir.join("simple-cmd.exe").exists());- assert!(bin_dir.join("simple-cmd.cmd").exists());- assert!(bin_dir.join("simple-cmd.bat").exists());- }+ assert!(bin_dir.join("test-cmd.exe").exists());}}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 56f41636e..8ddf69616 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -1502,67 +1502,27 @@ impl TestRepo {/// - `glab --version`: succeeds (installed)/// - `glab auth status`: fails (not authenticated)pub fn setup_mock_ci_tools_unauthenticated(&mut self) {- use crate::common::mock_commands::write_mock_script;+ use crate::common::mock_commands::{MockConfig, MockResponse};let mock_bin = self.temp_dir.path().join("mock-bin");std::fs::create_dir_all(&mock_bin).unwrap();- // Create mock gh script - installed but not authenticated- write_mock_script(- &mock_bin,- "gh",- r#"#!/bin/sh-# Mock gh: installed but not authenticated--case "$1" in- --version)- echo "gh version 2.0.0 (mock)"- exit 0- ;;- auth)- # gh auth status - fail (not authenticated)- exit 1- ;;- *)- exit 1- ;;-esac-"#,- );+ // gh: installed but not authenticated+ MockConfig::new("gh")+ .version("gh version 2.0.0 (mock)")+ .command("auth", MockResponse::exit(1))+ .write(&mock_bin);- // Create mock glab script - installed but not authenticated- write_mock_script(- &mock_bin,- "glab",- r#"#!/bin/sh-# Mock glab: installed but not authenticated--case "$1" in- --version)- echo "glab version 1.0.0 (mock)"- exit 0- ;;- auth)- # glab auth status - fail (not authenticated)- exit 1- ;;- *)- exit 1- ;;-esac-"#,- );+ // glab: installed but not authenticated+ MockConfig::new("glab")+ .version("glab version 1.0.0 (mock)")+ .command("auth", MockResponse::exit(1))+ .write(&mock_bin);- // Create mock claude script - not installed (exit 1 on --version)- // Tests can override with setup_mock_claude_installed() if needed- write_mock_script(- &mock_bin,- "claude",- r#"#!/bin/sh-# Mock claude: not installed-exit 1-"#,- );+ // claude: not installed+ MockConfig::new("claude")+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);self.mock_bin_path = Some(mock_bin);}@@ -1572,29 +1532,18 @@ exit 1/// Call this after setup_mock_ci_tools_unauthenticated() to simulate/// Claude Code being available on the system.pub fn setup_mock_claude_installed(&mut self) {- use crate::common::mock_commands::write_mock_script;+ use crate::common::mock_commands::{MockConfig, MockResponse};let mock_bin = self.mock_bin_path.as_ref().expect("Call setup_mock_ci_tools_unauthenticated first");- write_mock_script(- mock_bin,- "claude",- r#"#!/bin/sh-# Mock claude: installed-case "$1" in- --version)- echo "Claude Code 1.0.0 (mock)"- exit 0- ;;- *)- exit 0- ;;-esac-"#,- );+ // claude: installed+ MockConfig::new("claude")+ .version("Claude Code 1.0.0 (mock)")+ .command("_default", MockResponse::exit(0))+ .write(mock_bin);}/// Setup the worktrunk plugin as installed in Claude Code@@ -1620,83 +1569,27 @@ esac/// * `pr_json` - JSON string to return for `gh pr list --json ...`/// * `run_json` - JSON string to return for `gh run list --json ...`pub fn setup_mock_gh_with_ci_data(&mut self, pr_json: &str, run_json: &str) {- use crate::common::mock_commands::write_mock_script;+ use crate::common::mock_commands::{MockConfig, MockResponse};let mock_bin = self.temp_dir.path().join("mock-bin");std::fs::create_dir_all(&mock_bin).unwrap();- // Write JSON to separate files to avoid all escaping issues- let pr_json_file = mock_bin.join("pr_data.json");- let run_json_file = mock_bin.join("run_data.json");- std::fs::write(&pr_json_file, pr_json).unwrap();- std::fs::write(&run_json_file, run_json).unwrap();-- // Convert mock_bin path to a format bash can read.- // On Windows, convert D:\foo\bar to /d/foo/bar (MSYS2 style).- // On Unix, just use the path as-is.- let script_dir = {- let path_str = mock_bin.to_string_lossy();- #[cfg(windows)]- {- let chars: Vec<char> = path_str.chars().collect();- if chars.len() >= 2 && chars[1] == ':' {- // D:\foo\bar -> /d/foo/bar- let drive = chars[0].to_ascii_lowercase();- format!("/{}{}", drive, path_str[2..].replace('\\', "/"))- } else {- path_str.replace('\\', "/")- }- }- #[cfg(not(windows))]- {- path_str.to_string()- }- };+ // Write JSON data files+ std::fs::write(mock_bin.join("pr_data.json"), pr_json).unwrap();+ std::fs::write(mock_bin.join("run_data.json"), run_json).unwrap();- // Embed SCRIPT_DIR directly to avoid path resolution issues on Windows.- // Debug mode: set MOCK_GH_DEBUG=1 to see path resolution info.- let script = format!(- r#"#!/bin/bash-# Mock gh command that returns configured JSON data-# JSON files are in the same directory as this script-SCRIPT_DIR="{script_dir}"--case "$1" in- --version)- echo "gh version 2.0.0 (mock)"- exit 0- ;;- auth)- # gh auth status - succeed immediately- exit 0- ;;- pr)- # gh pr list - return PR data from file- cat "$SCRIPT_DIR/pr_data.json"- exit 0- ;;- run)- # gh run list - return run data from file- cat "$SCRIPT_DIR/run_data.json"- exit 0- ;;- *)- exit 1- ;;-esac-"#- );- write_mock_script(&mock_bin, "gh", &script);-- // Create mock glab script (fails immediately - no GitLab support in this mock)- write_mock_script(- &mock_bin,- "glab",- r#"#!/bin/sh-# Mock glab command that fails fast-exit 1-"#,- );+ // Configure gh mock+ MockConfig::new("gh")+ .version("gh version 2.0.0 (mock)")+ .command("auth", MockResponse::exit(0))+ .command("pr", MockResponse::file("pr_data.json"))+ .command("run", MockResponse::file("run_data.json"))+ .write(&mock_bin);++ // Configure glab mock (fails - no GitLab support)+ MockConfig::new("glab")+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);self.mock_bin_path = Some(mock_bin);}@@ -1710,86 +1603,33 @@ exit 1/// * `mr_json` - JSON string to return for `glab mr list --output json`/// * `project_id` - Optional project ID to return from `glab repo view`pub fn setup_mock_glab_with_ci_data(&mut self, mr_json: &str, project_id: Option<u64>) {- use crate::common::mock_commands::write_mock_script;+ use crate::common::mock_commands::{MockConfig, MockResponse};let mock_bin = self.temp_dir.path().join("mock-bin");std::fs::create_dir_all(&mock_bin).unwrap();- // Write JSON to a file to avoid escaping issues- let mr_json_file = mock_bin.join("mr_data.json");- std::fs::write(&mr_json_file, mr_json).unwrap();-- // Convert mock_bin path to a format bash can read- let script_dir = {- let path_str = mock_bin.to_string_lossy();- #[cfg(windows)]- {- let chars: Vec<char> = path_str.chars().collect();- if chars.len() >= 2 && chars[1] == ':' {- let drive = chars[0].to_ascii_lowercase();- format!("/{}{}", drive, path_str[2..].replace('\\', "/"))- } else {- path_str.replace('\\', "/")- }- }- #[cfg(not(windows))]- {- path_str.to_string()- }- };+ // Write JSON data file+ std::fs::write(mock_bin.join("mr_data.json"), mr_json).unwrap();- // Build glab mock script+ // Build project ID responselet project_id_response = match project_id {Some(id) => format!(r#"{{"id": {}}}"#, id),None => r#"{"error": "not found"}"#.to_string(),};- let script = format!(- r#"#!/bin/bash-# Mock glab command that returns configured JSON data-SCRIPT_DIR="{script_dir}"--case "$1" in- --version)- echo "glab version 1.0.0 (mock)"- exit 0- ;;- auth)- # glab auth status - succeed immediately- exit 0- ;;- mr)- # glab mr list - return MR data from file- cat "$SCRIPT_DIR/mr_data.json"- exit 0- ;;- repo)- # glab repo view --output json - return project info- echo '{project_id_response}'- exit 0- ;;- ci)- # glab ci list - return empty for now- echo '[]'- exit 0- ;;- *)- exit 1- ;;-esac-"#- );- write_mock_script(&mock_bin, "glab", &script);-- // Create mock gh script that fails (GitHub not available)- write_mock_script(- &mock_bin,- "gh",- r#"#!/bin/sh-# Mock gh command that fails fast-exit 1-"#,- );+ // Configure glab mock+ MockConfig::new("glab")+ .version("glab version 1.0.0 (mock)")+ .command("auth", MockResponse::exit(0))+ .command("mr", MockResponse::file("mr_data.json"))+ .command("repo", MockResponse::output(&project_id_response))+ .command("ci", MockResponse::output("[]"))+ .write(&mock_bin);++ // Configure gh mock (fails - no GitHub support)+ MockConfig::new("gh")+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);self.mock_bin_path = Some(mock_bin);}diff --git a/tests/helpers/mock-stub/Cargo.toml b/tests/helpers/mock-stub/Cargo.tomlindex 3f3f248bc..c7b6a2708 100644--- a/tests/helpers/mock-stub/Cargo.toml+++ b/tests/helpers/mock-stub/Cargo.toml@@ -1,8 +1,9 @@-# Windows-compatible mock executable stub for integration tests.+# Config-driven mock executable for integration tests.#-# On Windows, Rust's Command::new() uses CreateProcessW which only finds .exe files.-# This stub executable delegates to bash with a companion shell script:-# gh.exe + gh (script) -> gh.exe runs: bash gh <args>+# Reads a JSON config file to determine responses. When invoked as `gh`,+# looks for `gh.json` in the same directory and responds based on config.+#+# Works on all platforms (no bash dependency).## WHY A SEPARATE PACKAGE?# cargo-dist automatically discovers all [[bin]] entries and expects to distributediff --git a/tests/helpers/mock-stub/src/main.rs b/tests/helpers/mock-stub/src/main.rsindex 3fdbcc2f8..8a9efb51a 100644--- a/tests/helpers/mock-stub/src/main.rs+++ b/tests/helpers/mock-stub/src/main.rs@@ -1,141 +1,329 @@-//! Windows-compatible mock executable stub.+//! Config-driven mock executable for integration tests.//!-//! When invoked as `foo.exe`, runs `bash foo <args>` where `foo` is a companion-//! shell script in the same directory. This allows Rust's Command::new() to find-//! mock commands on Windows (CreateProcessW only searches for .exe files).+//! Reads a JSON config file to determine responses. When invoked as `gh`,+//! looks for `gh.json` in the same directory and responds based on config.+//!+//! Config format:+//! ```json+//! {+//! "version": "gh version 2.0.0 (mock)",+//! "commands": {+//! "auth": { "exit_code": 0 },+//! "pr": { "file": "pr_data.json" },+//! "run": { "output": "[{\"status\": \"completed\"}]" }+//! }+//! }+//! ```+//!+//! Command matching:+//! - `gh --version` → outputs version string+//! - `gh auth ...` → matches "auth" command+//! - `gh pr list ...` → matches "pr" command+//!+//! Response types:+//! - `file`: read and output contents of specified file (relative to config dir)+//! - `output`: output literal string+//! - `exit_code`: exit with specified code (default 0)//!//! Usage in tests:-//! 1. Copy mock-stub.exe to bin_dir/gh.exe-//! 2. Write shell script to bin_dir/gh-//! 3. Command::new("gh") now works on Windows+//! 1. Write config to bin_dir/gh.json+//! 2. Write data files to bin_dir/ (e.g., pr_data.json)+//! 3. Copy mock-stub binary as bin_dir/gh (Unix) or bin_dir/gh.exe (Windows)+//! 4. Command::new("gh") now works on all platforms+use std::collections::HashMap;use std::env;+use std::fs;use std::io::{self, Write};-use std::path::{Path, PathBuf};-use std::process::{Command, Stdio, exit};--/// Convert Windows path to MSYS2/Git Bash style path.-///-/// Git Bash expects Unix-style paths. When we pass a Windows path like-/// `D:\temp\bin\gh` to bash, it doesn't understand it. Convert to `/d/temp/bin/gh`.-fn to_msys_path(path: &Path) -> String {- let path_str = path.to_string_lossy();-- // Check for Windows drive letter (e.g., "D:\...")- let chars: Vec<char> = path_str.chars().collect();- if chars.len() >= 2 && chars[1] == ':' {- // D:\foo\bar -> /d/foo/bar- let drive = chars[0].to_ascii_lowercase();- format!("/{}{}", drive, path_str[2..].replace('\\', "/"))- } else {- // Already Unix-style or relative path- path_str.replace('\\', "/")- }-}+use std::path::PathBuf;+use std::process::exit;-/// Find Git Bash on Windows (avoid WSL bash wrapper at `C:\Windows\System32\bash.exe`).-#[cfg(windows)]-fn find_bash() -> PathBuf {- // GitHub Actions and most Windows installations have Git here- let git_bash = PathBuf::from(r"C:\Program Files\Git\bin\bash.exe");- if git_bash.exists() {- git_bash- } else {- PathBuf::from("bash")- }+/// Configuration for the mock command+#[derive(Debug)]+struct Config {+ version: Option<String>,+ commands: HashMap<String, CommandResponse>,}-#[cfg(not(windows))]-fn find_bash() -> PathBuf {- PathBuf::from("bash")+/// How to respond to a command+#[derive(Debug)]+struct CommandResponse {+ file: Option<String>,+ output: Option<String>,+ exit_code: i32,}fn main() {let exe_path = env::current_exe().expect("failed to get executable path");-- // Strip .exe extension to get companion script path- // e.g., /tmp/bin/gh.exe -> /tmp/bin/gh- let script_path = exe_path.with_extension("");- let script_dir = script_path+ let exe_dir = exe_path.parent()- .expect("mock-stub: script path has no parent directory");+ .expect("mock: executable has no parent directory");- // Distinguish setup errors from environment errors- if !script_path.exists() {- eprintln!(- "mock-stub: companion script not found: {}",- script_path.display()- );- eprintln!("Check that write_mock_script() created the script file.");- exit(1);+ // Get command name by stripping path and extension+ // e.g., /tmp/bin/gh.exe -> gh, /tmp/bin/gh -> gh+ let cmd_name = exe_path+ .file_stem()+ .expect("mock: executable has no file stem")+ .to_string_lossy();++ // Look for config file: gh.json for gh command+ let config_path = exe_dir.join(format!("{}.json", cmd_name));++ let debug = env::var("MOCK_DEBUG").is_ok();+ if debug {+ eprintln!("mock: exe_path={}", exe_path.display());+ eprintln!("mock: cmd_name={}", cmd_name);+ eprintln!("mock: config_path={}", config_path.display());}- // Convert to MSYS2-style path for bash on Windows- let script_path_str = to_msys_path(&script_path);- let script_dir_str = to_msys_path(script_dir);+ if !config_path.exists() {+ eprintln!("mock: config not found: {}", config_path.display());+ eprintln!("Expected JSON config file for mock command.");+ exit(1);+ }- // Forward all arguments to bash with the script+ let config = parse_config(&config_path);let args: Vec<String> = env::args().skip(1).collect();- // Find Git Bash on Windows (avoid WSL bash wrapper)- let bash_path = find_bash();-- // Debug: Show what we're about to execute (only when MOCK_DEBUG is set)- if env::var("MOCK_DEBUG").is_ok() {- eprintln!("mock-stub: exe_path={}", exe_path.display());- eprintln!("mock-stub: script_path={}", script_path.display());- eprintln!("mock-stub: script_path_str={}", script_path_str);- eprintln!("mock-stub: script_dir={}", script_dir.display());- eprintln!("mock-stub: script_dir_str={}", script_dir_str);- eprintln!("mock-stub: bash_path={}", bash_path.display());- eprintln!("mock-stub: args={:?}", args);+ if debug {+ eprintln!("mock: args={:?}", args);+ eprintln!("mock: config={:?}", config);}- // Use .output() to capture stdout/stderr, then forward them.- // This is more reliable than relying on handle inheritance on Windows,- // which can fail silently when pipes are involved.- //- // Pass MOCK_SCRIPT_DIR so scripts can reliably find sibling files.- // This avoids $0/dirname/pwd issues in Git Bash on Windows CI.- let output = Command::new(&bash_path)- .arg(&script_path_str)- .args(&args)- .env("MOCK_SCRIPT_DIR", &script_dir_str)- .stdin(Stdio::inherit())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .output()- .unwrap_or_else(|e| {- eprintln!(- "mock-stub: failed to execute bash at {}: {e}",- bash_path.display()- );- eprintln!("Is Git Bash installed?");- exit(1);- });-- // Debug: Show exit code and output lengths- if env::var("MOCK_DEBUG").is_ok() {- eprintln!(- "mock-stub: exit={} stdout_len={} stderr_len={}",- output.status.code().unwrap_or(-1),- output.stdout.len(),- output.stderr.len()- );- if !output.stderr.is_empty() {- eprintln!(- "mock-stub: stderr={}",- String::from_utf8_lossy(&output.stderr)- );+ // Handle --version flag+ if args.first().map(|s| s.as_str()) == Some("--version")+ && let Some(version) = &config.version+ {+ println!("{}", version);+ exit(0);+ }++ // Match first argument against commands, fall back to _default+ let default_response = CommandResponse {+ file: None,+ output: None,+ exit_code: 1,+ };+ let response = args+ .first()+ .and_then(|cmd| config.commands.get(cmd))+ .or_else(|| config.commands.get("_default"))+ .unwrap_or(&default_response);++ // Output response+ if let Some(file) = &response.file {+ let file_path = exe_dir.join(file);+ match fs::read_to_string(&file_path) {+ Ok(contents) => {+ print!("{}", contents);+ io::stdout().flush().unwrap();+ }+ Err(e) => {+ eprintln!("mock: failed to read {}: {}", file_path.display(), e);+ exit(1);+ }+ }+ } else if let Some(output) = &response.output {+ print!("{}", output);+ io::stdout().flush().unwrap();+ }++ exit(response.exit_code);+}++fn parse_config(path: &PathBuf) -> Config {+ let content = fs::read_to_string(path).unwrap_or_else(|e| {+ eprintln!("mock: failed to read config {}: {}", path.display(), e);+ exit(1);+ });++ // Simple JSON parsing without serde dependency+ // Format: { "version": "...", "commands": { "cmd": { "file": "...", "output": "...", "exit_code": N } } }+ parse_json_config(&content).unwrap_or_else(|e| {+ eprintln!("mock: failed to parse config {}: {}", path.display(), e);+ exit(1);+ })+}++fn parse_json_config(json: &str) -> Result<Config, String> {+ // Very simple JSON parser - just enough for our config format+ // Avoids serde dependency to keep binary small and fast to compile++ let json = json.trim();+ if !json.starts_with('{') || !json.ends_with('}') {+ return Err("expected JSON object".to_string());+ }++ let mut version = None;+ let mut commands = HashMap::new();++ // Extract version if present+ if let Some(start) = json.find("\"version\"")+ && let Some(value) = extract_string_value(&json[start..])+ {+ version = Some(value);+ }++ // Extract commands object+ if let Some(start) = json.find("\"commands\"") {+ let rest = &json[start + 10..]; // skip "commands"+ if let Some(obj_start) = rest.find('{') {+ let obj_rest = &rest[obj_start..];+ if let Some(obj_end) = find_matching_brace(obj_rest) {+ let commands_json = &obj_rest[1..obj_end];+ parse_commands(commands_json, &mut commands)?;+ }+ }+ }++ Ok(Config { version, commands })+}++fn extract_string_value(json: &str) -> Option<String> {+ // Find the colon after the key+ let colon = json.find(':')?;+ let rest = json[colon + 1..].trim_start();++ // Find the opening quote+ if !rest.starts_with('"') {+ return None;+ }++ // Find the closing quote (handle escaped quotes)+ let mut chars = rest[1..].chars().peekable();+ let mut value = String::new();+ while let Some(c) = chars.next() {+ if c == '\\' {+ if let Some(&next) = chars.peek() {+ chars.next();+ match next {+ 'n' => value.push('\n'),+ 't' => value.push('\t'),+ 'r' => value.push('\r'),+ '"' => value.push('"'),+ '\\' => value.push('\\'),+ _ => {+ value.push('\\');+ value.push(next);+ }+ }+ }+ } else if c == '"' {+ return Some(value);+ } else {+ value.push(c);}}+ None+}++fn find_matching_brace(json: &str) -> Option<usize> {+ let mut depth = 0;+ let mut in_string = false;+ let mut escape_next = false;++ for (i, c) in json.chars().enumerate() {+ if escape_next {+ escape_next = false;+ continue;+ }+ if c == '\\' && in_string {+ escape_next = true;+ continue;+ }+ if c == '"' {+ in_string = !in_string;+ continue;+ }+ if in_string {+ continue;+ }+ match c {+ '{' => depth += 1,+ '}' => {+ depth -= 1;+ if depth == 0 {+ return Some(i);+ }+ }+ _ => {}+ }+ }+ None+}- // Forward captured output to our stdout/stderr.- // Must flush before exit() since exit() doesn't run destructors.- io::stdout().write_all(&output.stdout).unwrap();- io::stdout().flush().unwrap();- io::stderr().write_all(&output.stderr).unwrap();- io::stderr().flush().unwrap();+fn parse_commands(+ json: &str,+ commands: &mut HashMap<String, CommandResponse>,+) -> Result<(), String> {+ // Parse command entries: "cmd": { ... }+ let mut rest = json.trim();++ while !rest.is_empty() {+ // Skip whitespace and commas+ rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == ',');+ if rest.is_empty() {+ break;+ }++ // Find command name+ if !rest.starts_with('"') {+ break;+ }+ let name_end = rest[1..].find('"').ok_or("unterminated command name")?;+ let name = rest[1..=name_end].to_string();+ rest = &rest[name_end + 2..];++ // Find colon and opening brace+ rest = rest.trim_start();+ if !rest.starts_with(':') {+ return Err(format!("expected ':' after command name '{}'", name));+ }+ rest = rest[1..].trim_start();++ if !rest.starts_with('{') {+ return Err(format!("expected '{{' for command '{}'", name));+ }++ let brace_end = find_matching_brace(rest).ok_or("unterminated command object")?;+ let cmd_json = &rest[1..brace_end];+ rest = &rest[brace_end + 1..];++ // Parse command response+ let mut file = None;+ let mut output = None;+ let mut exit_code = 0;++ if let Some(start) = cmd_json.find("\"file\"") {+ file = extract_string_value(&cmd_json[start..]);+ }+ if let Some(start) = cmd_json.find("\"output\"") {+ output = extract_string_value(&cmd_json[start..]);+ }+ if let Some(start) = cmd_json.find("\"exit_code\"") {+ let after_key = &cmd_json[start + 11..];+ if let Some(colon) = after_key.find(':') {+ let value_str = after_key[colon + 1..].trim_start();+ // Parse integer until non-digit+ let num_str: String = value_str+ .chars()+ .take_while(|c| c.is_ascii_digit() || *c == '-')+ .collect();+ if let Ok(n) = num_str.parse() {+ exit_code = n;+ }+ }+ }++ commands.insert(+ name,+ CommandResponse {+ file,+ output,+ exit_code,+ },+ );+ }- exit(output.status.code().unwrap_or(1));+ Ok(())}diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 1d26d4ffb..e68398540 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1071,8 +1071,8 @@ mod tests {repo.run_git_in(&feature_wt, &["commit", "-m", "Add authentication tests"]);// Configure LLM in worktrunk config for deterministic, high-quality commit messages- // On Windows, direct execution needs .cmd extension; use forward slashes for shell compatibility- let llm_name = if cfg!(windows) { "llm.cmd" } else { "llm" };+ // On Windows, use .exe extension for the config-driven mock binary+ let llm_name = if cfg!(windows) { "llm.exe" } else { "llm" };let llm_path = bin_dir.join(llm_name);let llm_path_str = llm_path.to_string_lossy().replace('\\', "/");let worktrunk_config = format!(