Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Consolidate performance testing into wt-perf helper crate (#577)

Maximilian Roos5fc4459323ac
diff --git a/Cargo.lock b/Cargo.lock
index 47a31fa0a..8024d9a2b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1719,15 +1719,6 @@ dependencies = [
"crossbeam-utils",
]
-[[package]]
-name = "rayon-join-macro"
-version = "0.1.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d64d145ddcd53ddc86a24a4ad646702cf9a08ea7f708bee54b8893fa67cb59a1"
-dependencies = [
- "rayon",
-]
-
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -1954,13 +1945,6 @@ dependencies = [
"winapi",
]
-[[package]]
-name = "setup-select-test"
-version = "0.1.0"
-dependencies = [
- "dunce",
-]
-
[[package]]
name = "sha2"
version = "0.10.9"
@@ -3073,7 +3057,6 @@ dependencies = [
"pathdiff",
"portable-pty",
"rayon",
- "rayon-join-macro",
"reflink-copy",
"regex",
"rstest",
@@ -3101,6 +3084,7 @@ dependencies = [
"vt100",
"which 8.0.0",
"wrap-ansi",
+ "wt-perf",
]
[[package]]
@@ -3115,6 +3099,16 @@ dependencies = [
"thiserror 2.0.17",
]
+[[package]]
+name = "wt-perf"
+version = "0.1.0"
+dependencies = [
+ "clap",
+ "dunce",
+ "tempfile",
+ "worktrunk",
+]
+
[[package]]
name = "zerocopy"
version = "0.8.28"
diff --git a/Cargo.toml b/Cargo.toml
index 48651a698..90f30e7b9 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["tests/helpers/setup-select-test", "tests/helpers/mock-stub"]
+members = ["tests/helpers/wt-perf", "tests/helpers/mock-stub"]
# Include mock-stub so `cargo test` builds its binary (via its integration test)
default-members = [".", "tests/helpers/mock-stub"]
@@ -60,12 +60,6 @@ name = "git-wt"
path = "src/git_wt.rs"
required-features = ["git-wt"]
-# Trace log analyzer for performance debugging
-[[bin]]
-name = "analyze-trace"
-path = "src/bin/analyze-trace.rs"
-test = false
-
[dependencies]
anyhow = "1.0"
anstream = "0.6"
@@ -117,7 +111,6 @@ which = "8.0"
# which external tools like git cannot handle. On Unix, it's a no-op wrapper.
dunce = "1.0"
termimad = "0.34.1"
-rayon-join-macro = "0.1.1"
urlencoding = "2.1"
regex = "1.12"
ignore = "0.4"
@@ -143,6 +136,7 @@ portable-pty = "0.9"
regex = "1.12"
vt100 = "0.16"
ansi-to-html = "0.2.2"
+wt-perf = { path = "tests/helpers/wt-perf" }
[[bench]]
name = "completion"
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index 301d20929..44165282f 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -51,14 +51,33 @@ cargo bench --bench list -- --skip cold # Warm cache only
- Cached rust repo: `target/bench-repos/rust/`
- HTML reports: `target/criterion/*/report/index.html`
-## Performance Investigation with analyze-trace
+## Performance Investigation with wt-perf
-Use `analyze-trace` to generate Chrome Trace Format for visualization:
+Use `wt-perf` to set up benchmark repos and generate Chrome Trace Format for visualization.
+
+### Setting up benchmark repos
+
+```bash
+# Set up a repo with 8 worktrees (persists at /tmp/wt-perf-typical-8)
+cargo run -p wt-perf -- setup typical-8 --persist
+
+# Available configs:
+# typical-N - 500 commits, 100 files, N worktrees
+# branches-N - N branches, 1 commit each
+# branches-N-M - N branches, M commits each
+# divergent - 200 branches × 20 commits (GH #461 scenario)
+# select-test - Config for wt select testing
+
+# Invalidate caches for cold run
+cargo run -p wt-perf -- invalidate /tmp/wt-perf-typical-8/main
+```
+
+### Generating traces
```bash
# Generate trace.json for Perfetto/Chrome
RUST_LOG=debug wt list --branches 2>&1 | grep '\[wt-trace\]' | \
- cargo run --release -q --bin analyze-trace > trace.json
+ cargo run -p wt-perf -- trace > trace.json
# Open in https://ui.perfetto.dev or chrome://tracing
```
@@ -120,7 +139,7 @@ trace_processor trace.json -q /tmp/q.sql
```bash
# Trace on rust-lang/rust (must run benchmark first to clone)
RUST_LOG=debug cargo run --release -q -- -C target/bench-repos/rust list --branches 2>&1 | \
- grep '\[wt-trace\]' | cargo run --release -q --bin analyze-trace > rust-trace.json
+ grep '\[wt-trace\]' | cargo run -p wt-perf -- trace > rust-trace.json
```
## Key Performance Insights
diff --git a/benches/list.rs b/benches/list.rs
index 4a645082b..a60917099 100644
--- a/benches/list.rs
+++ b/benches/list.rs
@@ -24,67 +24,33 @@
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use std::path::{Path, PathBuf};
use std::process::Command;
-use std::sync::OnceLock;
-use tempfile::TempDir;
+use wt_perf::{RepoConfig, create_repo, ensure_rust_repo, invalidate_caches, setup_fake_remote};
-/// Lazy-initialized rust repo path.
-static RUST_REPO: OnceLock<PathBuf> = OnceLock::new();
-
-/// Unified benchmark configuration.
+/// Benchmark configuration wrapping RepoConfig with cache state.
#[derive(Clone)]
struct BenchConfig {
- // Repo structure
- commits_on_main: usize,
- files: usize,
- branches: usize,
- commits_per_branch: usize,
- // Worktrees (0 = none)
- worktrees: usize,
- worktree_commits_ahead: usize,
- worktree_uncommitted_files: usize,
- // Cache state
+ repo: RepoConfig,
cold_cache: bool,
}
impl BenchConfig {
- /// Typical repo with worktrees (for skeleton, complete, worktree_scaling)
const fn typical(worktrees: usize, cold_cache: bool) -> Self {
Self {
- commits_on_main: 500,
- files: 100,
- branches: 0,
- commits_per_branch: 0,
- worktrees,
- worktree_commits_ahead: 10,
- worktree_uncommitted_files: 3,
+ repo: RepoConfig::typical(worktrees),
cold_cache,
}
}
- /// Branch-only config (for many_branches)
const fn branches(count: usize, commits_per_branch: usize, cold_cache: bool) -> Self {
Self {
- commits_on_main: 1,
- files: 1,
- branches: count,
- commits_per_branch,
- worktrees: 0,
- worktree_commits_ahead: 0,
- worktree_uncommitted_files: 0,
+ repo: RepoConfig::branches(count, commits_per_branch),
cold_cache,
}
}
- /// Many divergent branches (GH #461 scenario: 200 branches × 20 commits)
const fn many_divergent_branches(cold_cache: bool) -> Self {
Self {
- commits_on_main: 100,
- files: 50,
- branches: 200,
- commits_per_branch: 20,
- worktrees: 0,
- worktree_commits_ahead: 0,
- worktree_uncommitted_files: 0,
+ repo: RepoConfig::many_divergent_branches(),
cold_cache,
}
}
@@ -123,161 +89,6 @@ fn get_release_binary() -> PathBuf {
std::env::current_dir().unwrap().join("target/release/wt")
}
-/// Create a test repository from config.
-fn create_test_repo(config: &BenchConfig) -> TempDir {
- let temp_dir = tempfile::tempdir().unwrap();
- let repo_path = temp_dir.path().join("main");
- std::fs::create_dir(&repo_path).unwrap();
-
- run_git(&repo_path, &["init", "-b", "main"]);
- run_git(&repo_path, &["config", "user.name", "Benchmark"]);
- run_git(&repo_path, &["config", "user.email", "[email protected]"]);
-
- // Create initial file structure
- let num_files = config.files.max(1);
- for i in 0..num_files {
- let file_path = repo_path.join(format!("src/file_{}.rs", i));
- std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
- std::fs::write(
- &file_path,
- format!(
- "// File {i}\npub struct Module{i} {{ data: Vec<String> }}\npub fn function_{i}() -> i32 {{ {} }}\n",
- i * 42
- ),
- )
- .unwrap();
- }
-
- run_git(&repo_path, &["add", "."]);
- run_git(&repo_path, &["commit", "-m", "Initial commit"]);
-
- // Build commit history on main
- for i in 1..config.commits_on_main {
- let num_files_to_modify = 2 + (i % 2);
- for j in 0..num_files_to_modify {
- let file_idx = (i * 7 + j * 13) % num_files;
- let file_path = repo_path.join(format!("src/file_{}.rs", file_idx));
- let mut content = std::fs::read_to_string(&file_path).unwrap();
- content.push_str(&format!(
- "\npub fn function_{file_idx}_{i}() -> i32 {{ {} }}\n",
- i * 100 + j
- ));
- std::fs::write(&file_path, content).unwrap();
- }
- run_git(&repo_path, &["add", "."]);
- run_git(&repo_path, &["commit", "-m", &format!("Commit {i}")]);
- }
-
- // Create branches
- for i in 0..config.branches {
- let branch_name = format!("feature-{i:03}");
- run_git(&repo_path, &["checkout", "-b", &branch_name, "main"]);
-
- for j in 0..config.commits_per_branch {
- let feature_file = repo_path.join(format!("feature_{i:03}_{j}.rs"));
- std::fs::write(
- &feature_file,
- format!(
- "// Feature {i} file {j}\npub fn feature_{i}_func_{j}() -> i32 {{ {} }}\n",
- i * 100 + j
- ),
- )
- .unwrap();
- run_git(&repo_path, &["add", "."]);
- run_git(
- &repo_path,
- &["commit", "-m", &format!("Feature {branch_name} commit {j}")],
- );
- }
- }
-
- if config.branches > 0 {
- run_git(&repo_path, &["checkout", "main"]);
- }
-
- // Add worktrees
- for wt_num in 1..config.worktrees {
- let branch = format!("feature-wt-{wt_num}");
- let wt_path = temp_dir.path().join(format!("wt-{wt_num}"));
-
- let head_output = Command::new("git")
- .args(["rev-parse", "HEAD"])
- .current_dir(&repo_path)
- .output()
- .unwrap();
- let base_commit = String::from_utf8_lossy(&head_output.stdout)
- .trim()
- .to_string();
-
- run_git(
- &repo_path,
- &[
- "worktree",
- "add",
- "-b",
- &branch,
- wt_path.to_str().unwrap(),
- &base_commit,
- ],
- );
-
- // Add diverging commits
- for i in 0..config.worktree_commits_ahead {
- let file_path = wt_path.join(format!("feature_{wt_num}_file_{i}.txt"));
- std::fs::write(&file_path, format!("Feature {wt_num} content {i}\n")).unwrap();
- run_git(&wt_path, &["add", "."]);
- run_git(
- &wt_path,
- &["commit", "-m", &format!("Feature {wt_num} commit {i}")],
- );
- }
-
- // Add uncommitted changes
- for i in 0..config.worktree_uncommitted_files {
- let file_path = wt_path.join(format!("uncommitted_{i}.txt"));
- std::fs::write(&file_path, "Uncommitted content\n").unwrap();
- }
- }
-
- temp_dir
-}
-
-/// Invalidate git caches for cold benchmarks.
-fn invalidate_caches(repo_path: &Path, num_worktrees: usize) {
- let git_dir = repo_path.join(".git");
-
- // Remove index files
- let _ = std::fs::remove_file(git_dir.join("index"));
- for i in 1..num_worktrees {
- let _ = std::fs::remove_file(
- git_dir
- .join("worktrees")
- .join(format!("wt-{i}"))
- .join("index"),
- );
- }
-
- // Remove commit graph
- let _ = std::fs::remove_file(git_dir.join("objects/info/commit-graph"));
- let _ = std::fs::remove_dir_all(git_dir.join("objects/info/commit-graphs"));
-
- // Remove packed refs
- let _ = std::fs::remove_file(git_dir.join("packed-refs"));
-}
-
-/// Set up fake remote for default branch detection.
-fn setup_fake_remote(repo_path: &Path) {
- let refs_dir = repo_path.join(".git/refs/remotes/origin");
- std::fs::create_dir_all(&refs_dir).unwrap();
- std::fs::write(refs_dir.join("HEAD"), "ref: refs/remotes/origin/main\n").unwrap();
- let head_sha = Command::new("git")
- .args(["rev-parse", "HEAD"])
- .current_dir(repo_path)
- .output()
- .unwrap();
- std::fs::write(refs_dir.join("main"), head_sha.stdout).unwrap();
-}
-
/// Run a benchmark with the given config.
fn run_benchmark(
b: &mut criterion::Bencher,
@@ -298,7 +109,7 @@ fn run_benchmark(
if config.cold_cache {
b.iter_batched(
- || invalidate_caches(repo_path, config.worktrees),
+ || invalidate_caches(repo_path, config.repo.worktrees),
|_| {
cmd_factory().output().unwrap();
},
@@ -318,7 +129,7 @@ fn bench_skeleton(c: &mut Criterion) {
for worktrees in [1, 4, 8] {
for cold in [false, true] {
let config = BenchConfig::typical(worktrees, cold);
- let temp = create_test_repo(&config);
+ let temp = create_repo(&config.repo);
let repo_path = temp.path().join("main");
setup_fake_remote(&repo_path);
@@ -349,7 +160,7 @@ fn bench_complete(c: &mut Criterion) {
for worktrees in [1, 4, 8] {
for cold in [false, true] {
let config = BenchConfig::typical(worktrees, cold);
- let temp = create_test_repo(&config);
+ let temp = create_repo(&config.repo);
let repo_path = temp.path().join("main");
setup_fake_remote(&repo_path);
@@ -373,7 +184,7 @@ fn bench_worktree_scaling(c: &mut Criterion) {
for worktrees in [1, 4, 8] {
for cold in [false, true] {
let config = BenchConfig::typical(worktrees, cold);
- let temp = create_test_repo(&config);
+ let temp = create_repo(&config.repo);
let repo_path = temp.path().join("main");
run_git(&repo_path, &["status"]);
@@ -390,45 +201,6 @@ fn bench_worktree_scaling(c: &mut Criterion) {
group.finish();
}
-fn get_or_clone_rust_repo() -> PathBuf {
- RUST_REPO
- .get_or_init(|| {
- let cache_dir = std::env::current_dir().unwrap().join("target/bench-repos");
- let rust_repo = cache_dir.join("rust");
-
- if rust_repo.exists() {
- let output = Command::new("git")
- .args(["rev-parse", "HEAD"])
- .current_dir(&rust_repo)
- .output();
-
- if output.is_ok_and(|o| o.status.success()) {
- println!("Using cached rust repo at {}", rust_repo.display());
- return rust_repo;
- }
- println!("Cached rust repo corrupted, re-cloning...");
- std::fs::remove_dir_all(&rust_repo).unwrap();
- }
-
- std::fs::create_dir_all(&cache_dir).unwrap();
- println!("Cloning rust-lang/rust (this will take several minutes)...");
-
- let clone_output = Command::new("git")
- .args([
- "clone",
- "https://github.com/rust-lang/rust.git",
- rust_repo.to_str().unwrap(),
- ])
- .output()
- .unwrap();
-
- assert!(clone_output.status.success(), "Failed to clone rust repo");
- println!("Rust repo cloned successfully");
- rust_repo
- })
- .clone()
-}
-
fn bench_real_repo(c: &mut Criterion) {
let mut group = c.benchmark_group("real_repo");
let binary = get_release_binary();
@@ -441,7 +213,7 @@ fn bench_real_repo(c: &mut Criterion) {
BenchmarkId::new(label, worktrees),
&(worktrees, cold),
|b, &(worktrees, cold)| {
- let rust_repo = get_or_clone_rust_repo();
+ let rust_repo = ensure_rust_repo();
let temp = tempfile::tempdir().unwrap();
let workspace_main = temp.path().join("main");
@@ -462,7 +234,7 @@ fn bench_real_repo(c: &mut Criterion) {
run_git(&workspace_main, &["config", "user.name", "Benchmark"]);
run_git(&workspace_main, &["config", "user.email", "[email protected]"]);
- // Add worktrees manually (can't use create_test_repo for external repo)
+ // Add worktrees manually (can't use create_repo for external repo)
for wt_num in 1..worktrees {
let branch = format!("feature-wt-{wt_num}");
let wt_path = temp.path().join(format!("wt-{wt_num}"));
@@ -541,7 +313,7 @@ fn bench_many_branches(c: &mut Criterion) {
for cold in [false, true] {
let config = BenchConfig::branches(100, 2, cold);
- let temp = create_test_repo(&config);
+ let temp = create_repo(&config.repo);
let repo_path = temp.path().join("main");
run_git(&repo_path, &["status"]);
@@ -569,7 +341,7 @@ fn bench_divergent_branches(c: &mut Criterion) {
for cold in [false, true] {
let config = BenchConfig::many_divergent_branches(cold);
- let temp = create_test_repo(&config);
+ let temp = create_repo(&config.repo);
let repo_path = temp.path().join("main");
run_git(&repo_path, &["status"]);
@@ -591,7 +363,7 @@ fn bench_divergent_branches(c: &mut Criterion) {
/// Helper to set up rust repo workspace with branches at different history depths.
/// Returns the workspace path (temp dir must outlive usage).
fn setup_rust_workspace_with_branches(temp: &tempfile::TempDir, num_branches: usize) -> PathBuf {
- let rust_repo = get_or_clone_rust_repo();
+ let rust_repo = ensure_rust_repo();
let workspace_main = temp.path().join("main");
// Clone rust repo locally
diff --git a/src/bin/analyze-trace.rs b/src/bin/analyze-trace.rs
deleted file mode 100644
index 9d6245817..000000000
--- a/src/bin/analyze-trace.rs
+++ /dev/null
@@ -1,90 +0,0 @@
-//! Analyze wt-trace logs for concurrency visualization.
-//!
-//! # Usage
-//!
-//! ```bash
-//! # Generate Chrome Trace Format for visualization
-//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json
-//!
-//! # Visualize: open trace.json in chrome://tracing or https://ui.perfetto.dev
-//!
-//! # Analyze with SQL (requires: curl -LO https://get.perfetto.dev/trace_processor)
-//! trace_processor trace.json -Q 'SELECT COUNT(*), SUM(dur)/1e6 as cpu_ms FROM slice'
-//! trace_processor trace.json -Q 'SELECT name, COUNT(*) as n, SUM(dur)/1e6 as ms FROM slice GROUP BY name ORDER BY ms DESC'
-//!
-//! # Find milestone events (instant events have dur=0)
-//! trace_processor trace.json -Q 'SELECT name, ts/1e6 as ms FROM slice WHERE dur = 0'
-//! ```
-
-use std::io::{IsTerminal, Read};
-use std::path::PathBuf;
-
-use clap::Parser;
-use worktrunk::trace;
-
-/// Analyze wt-trace logs for concurrency visualization
-#[derive(Parser)]
-#[command(name = "analyze-trace")]
-#[command(about = "Convert wt-trace logs to Chrome Trace Format for visualization")]
-#[command(after_long_help = r#"EXAMPLES:
- # Generate trace from wt command
- RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json
-
- # Then either:
- # - Open trace.json in chrome://tracing or https://ui.perfetto.dev
- # - Query with: trace_processor trace.json -Q 'SELECT * FROM slice LIMIT 10'
-
- # Find milestone events (instant events have dur=0)
- trace_processor trace.json -Q 'SELECT name, ts/1e6 as ms FROM slice WHERE dur = 0'
-
- # Install trace_processor for SQL analysis:
- curl -LO https://get.perfetto.dev/trace_processor && chmod +x trace_processor
-"#)]
-struct Args {
- /// Path to trace log file (reads from stdin if omitted)
- file: Option<PathBuf>,
-}
-
-fn main() {
- let args = Args::parse();
-
- let input = match args.file {
- Some(path) if path.as_os_str() != "-" => match std::fs::read_to_string(&path) {
- Ok(content) => content,
- Err(e) => {
- eprintln!("Error reading {}: {}", path.display(), e);
- std::process::exit(1);
- }
- },
- _ => {
- if std::io::stdin().is_terminal() {
- eprintln!("Reading from stdin... (pipe trace data or use Ctrl+D to end)");
- eprintln!();
- eprintln!("Hint: RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace");
- }
-
- let mut content = String::new();
- std::io::stdin()
- .lock()
- .read_to_string(&mut content)
- .expect("Failed to read stdin");
- content
- }
- };
-
- let entries = trace::parse_lines(&input);
-
- if entries.is_empty() {
- eprintln!("No trace entries found in input.");
- eprintln!();
- eprintln!("Trace lines should look like:");
- eprintln!(" [wt-trace] ts=1234567890 tid=3 cmd=\"git status\" dur=12.3ms ok=true");
- eprintln!(" [wt-trace] ts=1234567890 tid=3 event=\"Showed skeleton\"");
- eprintln!();
- eprintln!("To capture traces, run with RUST_LOG=debug:");
- eprintln!(" RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace");
- std::process::exit(1);
- }
-
- println!("{}", trace::to_chrome_trace(&entries));
-}
diff --git a/src/trace/mod.rs b/src/trace/mod.rs
index d9094af84..65683ab67 100644
--- a/src/trace/mod.rs
+++ b/src/trace/mod.rs
@@ -13,7 +13,7 @@
//!
//! ```bash
//! # Generate Chrome Trace Format
-//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | analyze-trace > trace.json
+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | cargo run -p wt-perf -- trace > trace.json
//!
//! # Visualize: open trace.json in chrome://tracing or https://ui.perfetto.dev
//!
diff --git a/tests/helpers/setup-select-test/Cargo.toml b/tests/helpers/setup-select-test/Cargo.toml
deleted file mode 100644
index ba6d5e2aa..000000000
--- a/tests/helpers/setup-select-test/Cargo.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-# Helper binary to setup test environment for debugging `wt select`.
-# This is a workspace member (not a separate workspace) to share target/ and Cargo.lock.
-# Never published to crates.io (publish = false) - only used during development.
-[package]
-name = "setup-select-test"
-version = "0.1.0"
-edition = "2024"
-publish = false
-autotests = false
-
-[[bin]]
-name = "setup-select-test"
-path = "src/main.rs"
-test = false
-
-[dependencies]
-dunce = "1.0"
diff --git a/tests/helpers/setup-select-test/src/main.rs b/tests/helpers/setup-select-test/src/main.rs
deleted file mode 100644
index 50c278214..000000000
--- a/tests/helpers/setup-select-test/src/main.rs
+++ /dev/null
@@ -1,187 +0,0 @@
-//! Helper binary to setup a test environment for debugging `wt select`
-//!
-//! This creates a temporary git repository with a known state:
-//! - main branch with 3 commits
-//! - feature branch with 15 commits ahead of main (100 lines per file)
-//! - Multiple worktrees with varying amounts of work
-//! - Some uncommitted changes in the feature worktree
-//!
-//! Run with: cargo run --bin setup-select-test
-//! Then cd into the printed path and run: wt select
-
-use std::fs;
-use std::io::{self, Write};
-use std::path::{Path, PathBuf};
-use std::process::Command;
-
-/// Canonicalize path without Windows `\\?\` prefix.
-fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
- dunce::canonicalize(path)
-}
-
-fn main() {
- println!("Setting up test environment for `wt select`...\n");
-
- // Create temp directory in /tmp
- let temp_base = std::env::temp_dir().join("wt-select-test");
- if temp_base.exists() {
- fs::remove_dir_all(&temp_base).unwrap();
- }
- fs::create_dir(&temp_base).unwrap();
-
- let root = temp_base.join("repo");
- fs::create_dir(&root).unwrap();
- let root = canonicalize(&root).unwrap();
-
- // Initialize git repo
- git(&root, &["init", "-b", "main"]);
- git(&root, &["config", "user.name", "Test User"]);
- git(&root, &["config", "user.email", "[email protected]"]);
-
- // Create commits on main
- for i in 1..=3 {
- fs::write(
- root.join(format!("file{}.txt", i)),
- format!("content {}", i),
- )
- .unwrap();
- git(&root, &["add", "."]);
- git(&root, &["commit", "-m", &format!("Main commit {}", i)]);
- }
-
- // Create feature branch with commits ahead - MORE COMMITS AND BIGGER FILES
- git(&root, &["switch", "-c", "feature"]);
- for i in 1..=15 {
- // Create larger files with more content
- let mut content = String::new();
- for line in 1..=100 {
- content.push_str(&format!("Line {} of feature file {}\n", line, i));
- }
- fs::write(root.join(format!("feature{}.txt", i)), content).unwrap();
- git(&root, &["add", "."]);
- git(
- &root,
- &[
- "commit",
- "-m",
- &format!("Feature commit {}: Add feature{}.txt with 100 lines", i, i),
- ],
- );
- }
-
- // Switch back to main in primary worktree BEFORE creating worktrees
- git(&root, &["switch", "main"]);
-
- // Create multiple worktrees to simulate realistic scenario
-
- // Feature worktree (15 commits ahead)
- let feature_wt = temp_base.join("feature-wt");
- git(
- &root,
- &["worktree", "add", feature_wt.to_str().unwrap(), "feature"],
- );
-
- // Create more branches with different amounts of work
- for (i, num_commits) in [(2, 5), (3, 3), (4, 8), (5, 2)].iter() {
- let branch_name = format!("branch{}", i);
- git(&root, &["branch", &branch_name, "main"]);
-
- let wt_path = temp_base.join(format!("branch{}-wt", i));
- git(
- &root,
- &["worktree", "add", wt_path.to_str().unwrap(), &branch_name],
- );
-
- // Add commits to this branch via its worktree
- for j in 1..=*num_commits {
- let file_content = format!("Content for {} commit {}\n", branch_name, j);
- fs::write(wt_path.join(format!("file{}.txt", j)), file_content).unwrap();
- let mut cmd = Command::new("git");
- git_env(&mut cmd);
- cmd.args(["add", "."])
- .current_dir(&wt_path)
- .output()
- .unwrap();
-
- let mut cmd = Command::new("git");
- git_env(&mut cmd);
- cmd.args(["commit", "-m", &format!("{} commit {}", branch_name, j)])
- .current_dir(&wt_path)
- .output()
- .unwrap();
- }
- }
-
- // Add uncommitted changes to feature worktree
- let feature_wt = canonicalize(&feature_wt).unwrap();
- fs::write(feature_wt.join("uncommitted.txt"), "uncommitted changes").unwrap();
-
- // Create some branches without worktrees
- git(&root, &["branch", "no-worktree-1", "main"]);
- git(&root, &["branch", "no-worktree-2", "main"]);
-
- println!("✅ Test environment ready!\n");
- println!("Repository path: {}", root.display());
- println!();
- println!("Worktrees created:");
- println!(" - main (primary): {}", root.display());
- println!(" - feature: 15 commits ahead, 1 uncommitted file");
- println!(" - branch2: 5 commits ahead");
- println!(" - branch3: 3 commits ahead");
- println!(" - branch4: 8 commits ahead");
- println!(" - branch5: 2 commits ahead");
- println!();
- println!("Branches without worktrees:");
- println!(" - no-worktree-1, no-worktree-2");
- println!();
- println!("Total: 6 worktrees + 2 branches = 8 items in list");
- println!();
- println!("To test:");
- println!();
- println!("Method 1 - Using cd:");
- println!(" cd {}", root.display());
- println!(" cargo run --quiet -- select");
- println!();
- println!("Method 2 - Using -C flag:");
- println!(" cargo run --quiet -- -C {} select", root.display());
- println!();
- println!("Expected behavior:");
- println!(" - Navigate with arrow keys through 8 items");
- println!(" - Press 3 on 'feature': Shows LARGE diff (15 files, 1500 lines)");
- println!(" - Press 3 on other branches: Shows smaller diffs");
- println!();
- println!("Press Enter to clean up and exit (or Ctrl+C to leave the test repo)...");
-
- io::stdout().flush().unwrap();
- let mut input = String::new();
- io::stdin().read_line(&mut input).unwrap();
-
- println!("Cleaning up...");
- if let Err(e) = fs::remove_dir_all(&temp_base) {
- eprintln!("Warning: Failed to clean up test directory: {}", e);
- eprintln!("You may need to manually remove: {}", temp_base.display());
- } else {
- println!("Test environment cleaned up.");
- }
-}
-
-fn git_env(cmd: &mut Command) {
- // Set git config for test environment
- cmd.env("GIT_CONFIG_GLOBAL", "/dev/null");
- cmd.env("GIT_CONFIG_SYSTEM", "/dev/null");
- cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");
- cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");
-}
-
-fn git(repo: &PathBuf, args: &[&str]) {
- let mut cmd = Command::new("git");
- git_env(&mut cmd);
- let output = cmd.args(args).current_dir(repo).output().unwrap();
-
- if !output.status.success() {
- eprintln!("Git command failed: git {}", args.join(" "));
- eprintln!("stdout: {}", String::from_utf8_lossy(&output.stdout));
- eprintln!("stderr: {}", String::from_utf8_lossy(&output.stderr));
- std::process::exit(1);
- }
-}
diff --git a/tests/helpers/wt-perf/Cargo.toml b/tests/helpers/wt-perf/Cargo.toml
new file mode 100644
index 000000000..1ec57bdb1
--- /dev/null
+++ b/tests/helpers/wt-perf/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+name = "wt-perf"
+version = "0.1.0"
+edition = "2024"
+rust-version = "1.89"
+publish = false
+description = "Performance testing and tracing tools for worktrunk"
+
+[dependencies]
+# For repo setup
+tempfile = "3.19"
+dunce = "1"
+
+# For CLI
+clap = { version = "4", features = ["derive"] }
+
+# For trace parsing (reuse worktrunk's trace module)
+worktrunk = { path = "../../.." }
+
+[lib]
+name = "wt_perf"
+path = "src/lib.rs"
+
+[[bin]]
+name = "wt-perf"
+path = "src/main.rs"
diff --git a/tests/helpers/wt-perf/src/lib.rs b/tests/helpers/wt-perf/src/lib.rs
new file mode 100644
index 000000000..271ced875
--- /dev/null
+++ b/tests/helpers/wt-perf/src/lib.rs
@@ -0,0 +1,418 @@
+//! Performance testing and tracing tools for worktrunk.
+//!
+//! This crate provides:
+//! - Benchmark repository setup (used by `benches/list.rs`)
+//! - Cache invalidation for cold benchmark runs
+//! - Trace analysis utilities
+//!
+//! # Library Usage
+//!
+//! ```rust,ignore
+//! use wt_perf::{RepoConfig, create_repo, invalidate_caches};
+//!
+//! // Create a test repo with 8 worktrees
+//! let temp = create_repo(&RepoConfig::typical(8));
+//! let repo_path = temp.path().join("main");
+//!
+//! // Invalidate caches for cold benchmark
+//! invalidate_caches(&repo_path, 8);
+//! ```
+//!
+//! # CLI Usage
+//!
+//! ```bash
+//! # Set up a benchmark repo
+//! cargo run -p wt-perf -- setup typical-8
+//!
+//! # Invalidate caches
+//! cargo run -p wt-perf -- invalidate /path/to/repo
+//!
+//! # Parse trace logs
+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | cargo run -p wt-perf -- trace
+//! ```
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+use std::sync::OnceLock;
+use tempfile::TempDir;
+
+/// Lazy-initialized rust repo path.
+static RUST_REPO: OnceLock<PathBuf> = OnceLock::new();
+
+/// Configuration for creating a benchmark repository.
+#[derive(Clone, Debug)]
+pub struct RepoConfig {
+ /// Number of commits on main branch
+ pub commits_on_main: usize,
+ /// Number of files in the repo
+ pub files: usize,
+ /// Number of branches (without worktrees)
+ pub branches: usize,
+ /// Commits per branch
+ pub commits_per_branch: usize,
+ /// Number of worktrees (including main)
+ pub worktrees: usize,
+ /// Commits ahead of main per worktree
+ pub worktree_commits_ahead: usize,
+ /// Uncommitted files per worktree
+ pub worktree_uncommitted_files: usize,
+}
+
+impl RepoConfig {
+ /// Typical repo with worktrees (500 commits, 100 files).
+ ///
+ /// Good for skeleton rendering and general worktree benchmarks.
+ pub const fn typical(worktrees: usize) -> Self {
+ Self {
+ commits_on_main: 500,
+ files: 100,
+ branches: 0,
+ commits_per_branch: 0,
+ worktrees,
+ worktree_commits_ahead: 10,
+ worktree_uncommitted_files: 3,
+ }
+ }
+
+ /// Branch-focused config (minimal history, many branches).
+ pub const fn branches(count: usize, commits_per_branch: usize) -> Self {
+ Self {
+ commits_on_main: 1,
+ files: 1,
+ branches: count,
+ commits_per_branch,
+ worktrees: 0,
+ worktree_commits_ahead: 0,
+ worktree_uncommitted_files: 0,
+ }
+ }
+
+ /// Many divergent branches (GH #461 scenario: 200 branches × 20 commits).
+ pub const fn many_divergent_branches() -> Self {
+ Self {
+ commits_on_main: 100,
+ files: 50,
+ branches: 200,
+ commits_per_branch: 20,
+ worktrees: 0,
+ worktree_commits_ahead: 0,
+ worktree_uncommitted_files: 0,
+ }
+ }
+
+ /// Config for testing `wt select` (6 worktrees with varying commits).
+ pub const fn select_test() -> Self {
+ Self {
+ commits_on_main: 3,
+ files: 3,
+ branches: 2, // no-worktree-1, no-worktree-2
+ commits_per_branch: 0,
+ worktrees: 6,
+ worktree_commits_ahead: 15, // feature worktree has many commits
+ worktree_uncommitted_files: 1,
+ }
+ }
+}
+
+/// Run a git command in the given directory.
+fn run_git(path: &Path, args: &[&str]) {
+ let output = Command::new("git")
+ .args(args)
+ .current_dir(path)
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "Git command failed: {:?}\nstderr: {}\nstdout: {}\npath: {}",
+ args,
+ String::from_utf8_lossy(&output.stderr),
+ String::from_utf8_lossy(&output.stdout),
+ path.display()
+ );
+}
+
+/// Create a test repository from config.
+///
+/// Returns a `TempDir` containing the repo. The main worktree is at `temp.path().join("repo")`.
+/// Additional worktrees are siblings: `temp.path().join("repo.feature-wt-N")`.
+pub fn create_repo(config: &RepoConfig) -> TempDir {
+ let temp_dir = tempfile::tempdir().unwrap();
+ create_repo_at(config, &temp_dir.path().join("repo"));
+ temp_dir
+}
+
+/// Create a test repository at a specific path.
+///
+/// Uses worktrunk naming convention:
+/// - Main worktree: `base_path`
+/// - Feature worktrees: `base_path.feature-wt-N` (siblings in parent directory)
+pub fn create_repo_at(config: &RepoConfig, base_path: &Path) {
+ let repo_path = base_path.to_path_buf();
+ std::fs::create_dir_all(&repo_path).unwrap();
+
+ run_git(&repo_path, &["init", "-b", "main"]);
+ run_git(&repo_path, &["config", "user.name", "Benchmark"]);
+ run_git(&repo_path, &["config", "user.email", "[email protected]"]);
+
+ // Create initial file structure
+ let num_files = config.files.max(1);
+ for i in 0..num_files {
+ let file_path = repo_path.join(format!("src/file_{}.rs", i));
+ std::fs::create_dir_all(file_path.parent().unwrap()).unwrap();
+ std::fs::write(
+ &file_path,
+ format!(
+ "// File {i}\npub struct Module{i} {{ data: Vec<String> }}\npub fn function_{i}() -> i32 {{ {} }}\n",
+ i * 42
+ ),
+ )
+ .unwrap();
+ }
+
+ run_git(&repo_path, &["add", "."]);
+ run_git(&repo_path, &["commit", "-m", "Initial commit"]);
+
+ // Build commit history on main
+ for i in 1..config.commits_on_main {
+ let num_files_to_modify = 2 + (i % 2);
+ for j in 0..num_files_to_modify {
+ let file_idx = (i * 7 + j * 13) % num_files;
+ let file_path = repo_path.join(format!("src/file_{}.rs", file_idx));
+ let mut content = std::fs::read_to_string(&file_path).unwrap();
+ content.push_str(&format!(
+ "\npub fn function_{file_idx}_{i}() -> i32 {{ {} }}\n",
+ i * 100 + j
+ ));
+ std::fs::write(&file_path, content).unwrap();
+ }
+ run_git(&repo_path, &["add", "."]);
+ run_git(&repo_path, &["commit", "-m", &format!("Commit {i}")]);
+ }
+
+ // Create branches (without worktrees)
+ for i in 0..config.branches {
+ let branch_name = format!("feature-{i:03}");
+ run_git(&repo_path, &["checkout", "-b", &branch_name, "main"]);
+
+ for j in 0..config.commits_per_branch {
+ let feature_file = repo_path.join(format!("feature_{i:03}_{j}.rs"));
+ std::fs::write(
+ &feature_file,
+ format!(
+ "// Feature {i} file {j}\npub fn feature_{i}_func_{j}() -> i32 {{ {} }}\n",
+ i * 100 + j
+ ),
+ )
+ .unwrap();
+ run_git(&repo_path, &["add", "."]);
+ run_git(
+ &repo_path,
+ &["commit", "-m", &format!("Feature {branch_name} commit {j}")],
+ );
+ }
+ }
+
+ if config.branches > 0 {
+ run_git(&repo_path, &["checkout", "main"]);
+ }
+
+ // Add worktrees
+ for wt_num in 1..config.worktrees {
+ let branch = format!("feature-wt-{wt_num}");
+ let wt_path = base_path.join(format!("wt-{wt_num}"));
+
+ let head_output = Command::new("git")
+ .args(["rev-parse", "HEAD"])
+ .current_dir(&repo_path)
+ .output()
+ .unwrap();
+ let base_commit = String::from_utf8_lossy(&head_output.stdout)
+ .trim()
+ .to_string();
+
+ run_git(
+ &repo_path,
+ &[
+ "worktree",
+ "add",
+ "-b",
+ &branch,
+ wt_path.to_str().unwrap(),
+ &base_commit,
+ ],
+ );
+
+ // Add diverging commits
+ for i in 0..config.worktree_commits_ahead {
+ let file_path = wt_path.join(format!("feature_{wt_num}_file_{i}.txt"));
+ std::fs::write(&file_path, format!("Feature {wt_num} content {i}\n")).unwrap();
+ run_git(&wt_path, &["add", "."]);
+ run_git(
+ &wt_path,
+ &["commit", "-m", &format!("Feature {wt_num} commit {i}")],
+ );
+ }
+
+ // Add uncommitted changes
+ for i in 0..config.worktree_uncommitted_files {
+ let file_path = wt_path.join(format!("uncommitted_{i}.txt"));
+ std::fs::write(&file_path, "Uncommitted content\n").unwrap();
+ }
+ }
+
+ // Set up fake remote for default branch detection
+ setup_fake_remote(&repo_path);
+}
+
+/// Set up a fake remote for default branch detection.
+pub fn setup_fake_remote(repo_path: &Path) {
+ let refs_dir = repo_path.join(".git/refs/remotes/origin");
+ std::fs::create_dir_all(&refs_dir).unwrap();
+ std::fs::write(refs_dir.join("HEAD"), "ref: refs/remotes/origin/main\n").unwrap();
+ let head_sha = Command::new("git")
+ .args(["rev-parse", "HEAD"])
+ .current_dir(repo_path)
+ .output()
+ .unwrap();
+ std::fs::write(refs_dir.join("main"), head_sha.stdout).unwrap();
+}
+
+/// Invalidate git caches for cold benchmarks.
+///
+/// Removes:
+/// - Index files (main + worktrees)
+/// - Commit graph
+/// - Packed refs
+pub fn invalidate_caches(repo_path: &Path, num_worktrees: usize) {
+ let git_dir = repo_path.join(".git");
+
+ // Remove index files
+ let _ = std::fs::remove_file(git_dir.join("index"));
+ for i in 1..num_worktrees {
+ let _ = std::fs::remove_file(
+ git_dir
+ .join("worktrees")
+ .join(format!("wt-{i}"))
+ .join("index"),
+ );
+ }
+
+ // Remove commit graph
+ let _ = std::fs::remove_file(git_dir.join("objects/info/commit-graph"));
+ let _ = std::fs::remove_dir_all(git_dir.join("objects/info/commit-graphs"));
+
+ // Remove packed refs
+ let _ = std::fs::remove_file(git_dir.join("packed-refs"));
+}
+
+/// Invalidate caches for any repo (auto-detects worktrees).
+pub fn invalidate_caches_auto(repo_path: &Path) {
+ let git_dir = repo_path.join(".git");
+
+ // Remove main index
+ let _ = std::fs::remove_file(git_dir.join("index"));
+
+ // Remove all worktree indexes
+ let worktrees_dir = git_dir.join("worktrees");
+ if worktrees_dir.exists()
+ && let Ok(entries) = std::fs::read_dir(&worktrees_dir)
+ {
+ for entry in entries.flatten() {
+ let index = entry.path().join("index");
+ let _ = std::fs::remove_file(index);
+ }
+ }
+
+ // Remove commit graph
+ let _ = std::fs::remove_file(git_dir.join("objects/info/commit-graph"));
+ let _ = std::fs::remove_dir_all(git_dir.join("objects/info/commit-graphs"));
+
+ // Remove packed refs
+ let _ = std::fs::remove_file(git_dir.join("packed-refs"));
+}
+
+/// Get or clone the rust-lang/rust repository for real-world benchmarks.
+///
+/// The repo is cached at `target/bench-repos/rust` and reused across runs.
+pub fn ensure_rust_repo() -> PathBuf {
+ RUST_REPO
+ .get_or_init(|| {
+ let cache_dir = std::env::current_dir().unwrap().join("target/bench-repos");
+ let rust_repo = cache_dir.join("rust");
+
+ if rust_repo.exists() {
+ let output = Command::new("git")
+ .args(["rev-parse", "HEAD"])
+ .current_dir(&rust_repo)
+ .output();
+
+ if output.is_ok_and(|o| o.status.success()) {
+ eprintln!("Using cached rust repo at {}", rust_repo.display());
+ return rust_repo;
+ }
+ eprintln!("Cached rust repo corrupted, re-cloning...");
+ std::fs::remove_dir_all(&rust_repo).unwrap();
+ }
+
+ std::fs::create_dir_all(&cache_dir).unwrap();
+ eprintln!("Cloning rust-lang/rust (this will take several minutes)...");
+
+ let clone_output = Command::new("git")
+ .args([
+ "clone",
+ "https://github.com/rust-lang/rust.git",
+ rust_repo.to_str().unwrap(),
+ ])
+ .output()
+ .unwrap();
+
+ assert!(clone_output.status.success(), "Failed to clone rust repo");
+ eprintln!("Rust repo cloned successfully");
+ rust_repo
+ })
+ .clone()
+}
+
+/// Canonicalize path without Windows `\\?\` prefix.
+pub fn canonicalize(path: &Path) -> std::io::Result<PathBuf> {
+ dunce::canonicalize(path)
+}
+
+/// Parse a config string into a RepoConfig.
+///
+/// Supported formats:
+/// - `typical-N` - typical repo with N worktrees
+/// - `branches-N` - N branches with 1 commit each
+/// - `branches-N-M` - N branches with M commits each
+/// - `divergent` - many divergent branches (GH #461)
+/// - `select-test` - config for wt select testing
+pub fn parse_config(s: &str) -> Option<RepoConfig> {
+ if let Some(n) = s.strip_prefix("typical-") {
+ let worktrees: usize = n.parse().ok()?;
+ return Some(RepoConfig::typical(worktrees));
+ }
+
+ if let Some(rest) = s.strip_prefix("branches-") {
+ let parts: Vec<&str> = rest.split('-').collect();
+ match parts.as_slice() {
+ [count] => {
+ let count: usize = count.parse().ok()?;
+ return Some(RepoConfig::branches(count, 1));
+ }
+ [count, commits] => {
+ let count: usize = count.parse().ok()?;
+ let commits: usize = commits.parse().ok()?;
+ return Some(RepoConfig::branches(count, commits));
+ }
+ _ => return None,
+ }
+ }
+
+ match s {
+ "divergent" => Some(RepoConfig::many_divergent_branches()),
+ "select-test" => Some(RepoConfig::select_test()),
+ _ => None,
+ }
+}
diff --git a/tests/helpers/wt-perf/src/main.rs b/tests/helpers/wt-perf/src/main.rs
new file mode 100644
index 000000000..da54fad91
--- /dev/null
+++ b/tests/helpers/wt-perf/src/main.rs
@@ -0,0 +1,216 @@
+//! CLI for worktrunk performance testing and tracing.
+//!
+//! # Usage
+//!
+//! ```bash
+//! # Set up a benchmark repo
+//! wt-perf setup typical-8 --path /tmp/bench
+//!
+//! # Invalidate caches for cold run
+//! wt-perf invalidate /tmp/bench/main
+//!
+//! # Parse trace logs (pipe from wt command)
+//! RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf trace > trace.json
+//!
+//! # Set up select test environment
+//! wt-perf setup select-test
+//! ```
+
+use std::io::{IsTerminal, Read, Write};
+use std::path::PathBuf;
+
+use clap::{Parser, Subcommand};
+use wt_perf::{canonicalize, create_repo_at, invalidate_caches_auto, parse_config};
+
+#[derive(Parser)]
+#[command(name = "wt-perf")]
+#[command(about = "Performance testing and tracing tools for worktrunk")]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Set up a benchmark repository
+ Setup {
+ /// Config name: typical-N, branches-N, branches-N-M, divergent, select-test
+ config: String,
+
+ /// Directory to create repo in (default: temp directory)
+ #[arg(long)]
+ path: Option<PathBuf>,
+
+ /// Keep the repo (don't wait for cleanup)
+ #[arg(long)]
+ persist: bool,
+ },
+
+ /// Invalidate git caches for cold benchmarks
+ Invalidate {
+ /// Path to the repository
+ repo: PathBuf,
+ },
+
+ /// Parse trace logs and output Chrome Trace Format JSON
+ #[command(after_long_help = r#"EXAMPLES:
+ # Generate trace from wt command
+ RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf trace > trace.json
+
+ # Then either:
+ # - Open trace.json in chrome://tracing or https://ui.perfetto.dev
+ # - Query with: trace_processor trace.json -Q 'SELECT * FROM slice LIMIT 10'
+
+ # Find milestone events (instant events have dur=0)
+ trace_processor trace.json -Q 'SELECT name, ts/1e6 as ms FROM slice WHERE dur = 0'
+
+ # Install trace_processor for SQL analysis:
+ curl -LO https://get.perfetto.dev/trace_processor && chmod +x trace_processor
+"#)]
+ Trace {
+ /// Path to trace log file (reads from stdin if omitted)
+ file: Option<PathBuf>,
+ },
+}
+
+fn main() {
+ let cli = Cli::parse();
+
+ match cli.command {
+ Commands::Setup {
+ config,
+ path,
+ persist,
+ } => {
+ let repo_config = parse_config(&config).unwrap_or_else(|| {
+ eprintln!("Unknown config: {}", config);
+ eprintln!();
+ eprintln!("Available configs:");
+ eprintln!(
+ " typical-N - Typical repo with N worktrees (500 commits, 100 files)"
+ );
+ eprintln!(" branches-N - N branches with 1 commit each");
+ eprintln!(" branches-N-M - N branches with M commits each");
+ eprintln!(" divergent - 200 branches × 20 commits (GH #461 scenario)");
+ eprintln!(" select-test - Config for wt select testing");
+ std::process::exit(1);
+ });
+
+ let base_path = if let Some(p) = path {
+ std::fs::create_dir_all(&p).unwrap();
+ canonicalize(&p).unwrap()
+ } else {
+ let temp = std::env::temp_dir().join(format!("wt-perf-{}", config));
+ if temp.exists() {
+ std::fs::remove_dir_all(&temp).unwrap();
+ }
+ std::fs::create_dir_all(&temp).unwrap();
+ canonicalize(&temp).unwrap()
+ };
+
+ eprintln!("Creating {} repo...", config);
+ create_repo_at(&repo_config, &base_path);
+
+ let repo_path = base_path.join("main");
+ eprintln!();
+ eprintln!("✅ Repository created");
+ eprintln!();
+ eprintln!("Main worktree: {}", repo_path.display());
+ if repo_config.worktrees > 1 {
+ eprintln!("Worktrees: {} total", repo_config.worktrees);
+ for i in 1..repo_config.worktrees {
+ eprintln!(
+ " - wt-{}: {}",
+ i,
+ base_path.join(format!("wt-{i}")).display()
+ );
+ }
+ }
+ if repo_config.branches > 0 {
+ eprintln!("Branches: {}", repo_config.branches);
+ }
+ eprintln!();
+ eprintln!("To run with tracing:");
+ eprintln!(
+ " RUST_LOG=debug wt -C {} list 2>&1 | grep wt-trace | wt-perf trace > trace.json",
+ repo_path.display()
+ );
+ eprintln!();
+ eprintln!("To invalidate caches (cold run):");
+ eprintln!(" wt-perf invalidate {}", repo_path.display());
+
+ if !persist {
+ eprintln!();
+ eprintln!("Press Enter to clean up (or Ctrl+C to keep)...");
+ std::io::stdout().flush().unwrap();
+ let mut input = String::new();
+ std::io::stdin().read_line(&mut input).unwrap();
+
+ eprintln!("Cleaning up...");
+ if let Err(e) = std::fs::remove_dir_all(&base_path) {
+ eprintln!("Warning: Failed to clean up: {}", e);
+ eprintln!("You may need to manually remove: {}", base_path.display());
+ }
+ }
+ }
+
+ Commands::Invalidate { repo } => {
+ let repo = canonicalize(&repo).unwrap_or_else(|e| {
+ eprintln!("Invalid repo path {}: {}", repo.display(), e);
+ std::process::exit(1);
+ });
+
+ if !repo.join(".git").exists() {
+ eprintln!("Not a git repository: {}", repo.display());
+ std::process::exit(1);
+ }
+
+ invalidate_caches_auto(&repo);
+ eprintln!("✅ Caches invalidated for {}", repo.display());
+ }
+
+ Commands::Trace { file } => {
+ let input = match file {
+ Some(path) if path.as_os_str() != "-" => match std::fs::read_to_string(&path) {
+ Ok(content) => content,
+ Err(e) => {
+ eprintln!("Error reading {}: {}", path.display(), e);
+ std::process::exit(1);
+ }
+ },
+ _ => {
+ if std::io::stdin().is_terminal() {
+ eprintln!("Reading from stdin... (pipe trace data or use Ctrl+D to end)");
+ eprintln!();
+ eprintln!(
+ "Hint: RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf trace"
+ );
+ }
+
+ let mut content = String::new();
+ std::io::stdin()
+ .lock()
+ .read_to_string(&mut content)
+ .expect("Failed to read stdin");
+ content
+ }
+ };
+
+ let entries = worktrunk::trace::parse_lines(&input);
+
+ if entries.is_empty() {
+ eprintln!("No trace entries found in input.");
+ eprintln!();
+ eprintln!("Trace lines should look like:");
+ eprintln!(" [wt-trace] ts=1234567890 tid=3 cmd=\"git status\" dur=12.3ms ok=true");
+ eprintln!(" [wt-trace] ts=1234567890 tid=3 event=\"Showed skeleton\"");
+ eprintln!();
+ eprintln!("To capture traces, run with RUST_LOG=debug:");
+ eprintln!(" RUST_LOG=debug wt list 2>&1 | grep wt-trace | wt-perf trace");
+ std::process::exit(1);
+ }
+
+ println!("{}", worktrunk::trace::to_chrome_trace(&entries));
+ }
+ }
+}
diff --git a/tests/integration_tests/analyze_trace.rs b/tests/integration_tests/analyze_trace.rs
index aab3b55c9..1cbc31609 100644
--- a/tests/integration_tests/analyze_trace.rs
+++ b/tests/integration_tests/analyze_trace.rs
@@ -1,11 +1,24 @@
-//! Integration tests for the analyze-trace binary.
+//! Integration tests for the wt-perf trace command.
use std::io::Write;
use std::process::{Command, Stdio};
+fn wt_perf_bin() -> std::path::PathBuf {
+ // Build and get path to wt-perf binary
+ let output = Command::new("cargo")
+ .args(["build", "-p", "wt-perf"])
+ .output()
+ .expect("Failed to build wt-perf");
+ assert!(output.status.success(), "Failed to build wt-perf");
+
+ std::env::current_dir()
+ .unwrap()
+ .join("target/debug/wt-perf")
+}
+
/// Test that the binary produces Chrome Trace Format JSON for sample trace input.
#[test]
-fn test_analyze_trace_from_stdin() {
+fn test_wt_perf_trace_from_stdin() {
let sample_trace = r#"[wt-trace] ts=1000000 tid=1 cmd="git status" dur=10.0ms ok=true
[wt-trace] ts=1010000 tid=1 cmd="git status" dur=15.0ms ok=true
[wt-trace] ts=1025000 tid=1 cmd="git diff" dur=100.0ms ok=true
@@ -13,12 +26,13 @@ fn test_analyze_trace_from_stdin() {
[wt-trace] ts=1125000 tid=1 cmd="git merge-base HEAD main" dur=500.0ms ok=true
[wt-trace] ts=1625000 tid=1 cmd="gh pr list" dur=200.0ms ok=true"#;
- let mut child = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
+ let mut child = Command::new(wt_perf_bin())
+ .arg("trace")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
- .expect("Failed to spawn analyze-trace");
+ .expect("Failed to spawn wt-perf");
child
.stdin
@@ -29,7 +43,7 @@ fn test_analyze_trace_from_stdin() {
let output = child.wait_with_output().expect("Failed to read output");
- assert!(output.status.success(), "analyze-trace should succeed");
+ assert!(output.status.success(), "wt-perf trace should succeed");
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -59,12 +73,12 @@ fn test_analyze_trace_from_stdin() {
/// Test that the binary shows usage when run interactively without input.
#[test]
-fn test_analyze_trace_no_input_shows_usage() {
+fn test_wt_perf_trace_no_input_shows_usage() {
// Test by passing a non-existent file
- let output = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
- .arg("/nonexistent/path/to/file.log")
+ let output = Command::new(wt_perf_bin())
+ .args(["trace", "/nonexistent/path/to/file.log"])
.output()
- .expect("Failed to run analyze-trace");
+ .expect("Failed to run wt-perf");
assert!(
!output.status.success(),
@@ -80,13 +94,14 @@ fn test_analyze_trace_no_input_shows_usage() {
/// Test that the binary handles empty trace input.
#[test]
-fn test_analyze_trace_empty_input() {
- let mut child = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
+fn test_wt_perf_trace_empty_input() {
+ let mut child = Command::new(wt_perf_bin())
+ .arg("trace")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
- .expect("Failed to spawn analyze-trace");
+ .expect("Failed to spawn wt-perf");
// Write empty input and close stdin
child.stdin.take().unwrap();
@@ -107,7 +122,7 @@ fn test_analyze_trace_empty_input() {
/// Test reading from a file.
#[test]
-fn test_analyze_trace_from_file() {
+fn test_wt_perf_trace_from_file() {
// Create a temp file with sample trace data
let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
let log_file = temp_dir.path().join("trace.log");
@@ -119,10 +134,10 @@ fn test_analyze_trace_from_file() {
std::fs::write(&log_file, sample_trace).expect("Failed to write sample log");
- let output = Command::new(env!("CARGO_BIN_EXE_analyze-trace"))
- .arg(&log_file)
+ let output = Command::new(wt_perf_bin())
+ .args(["trace", log_file.to_str().unwrap()])
.output()
- .expect("Failed to run analyze-trace");
+ .expect("Failed to run wt-perf");
assert!(output.status.success(), "Should succeed with sample log");