Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Unify wt-select demo with shared infrastructure (#276)
Maximilian Roos8e581cdf9344
diff --git a/docs/demos/shared/fixtures/alpha-utils.rs b/docs/demos/shared/fixtures/alpha-utils.rsnew file mode 100644index 000000000..59e27be8e--- /dev/null+++ b/docs/demos/shared/fixtures/alpha-utils.rs@@ -0,0 +1,242 @@+//! Utility functions for the Acme application.+//!+//! This module provides common utilities used throughout the codebase,+//! including string manipulation, path handling, and configuration helpers.++use std::path::{Path, PathBuf};++/// Normalize a path by resolving `.` and `..` components.+///+/// Unlike `std::fs::canonicalize`, this function does not require the path+/// to exist on the filesystem.+///+/// # Examples+///+/// ```+/// use acme::utils::normalize_path;+///+/// let path = normalize_path("/foo/bar/../baz");+/// assert_eq!(path, PathBuf::from("/foo/baz"));+/// ```+pub fn normalize_path(path: impl AsRef<Path>) -> PathBuf {+ let path = path.as_ref();+ let mut components = Vec::new();++ for component in path.components() {+ match component {+ std::path::Component::ParentDir => {+ if !components.is_empty() {+ components.pop();+ }+ }+ std::path::Component::CurDir => {}+ other => components.push(other),+ }+ }++ components.iter().collect()+}++/// Find the project root by searching for a marker file.+///+/// Walks up from the given directory looking for common project markers+/// like `Cargo.toml`, `.git`, or `package.json`.+///+/// # Arguments+///+/// * `start` - The directory to start searching from+/// * `markers` - A list of filenames to look for+///+/// # Returns+///+/// The path to the directory containing the marker, or `None` if not found.+pub fn find_project_root(start: &Path, markers: &[&str]) -> Option<PathBuf> {+ let mut current = start.to_path_buf();++ loop {+ for marker in markers {+ if current.join(marker).exists() {+ return Some(current);+ }+ }++ if !current.pop() {+ return None;+ }+ }+}++/// Configuration for string formatting options.+#[derive(Debug, Clone, Default)]+pub struct FormatConfig {+ /// Maximum line width before wrapping+ pub max_width: Option<usize>,+ /// Indentation string (spaces or tabs)+ pub indent: String,+ /// Whether to trim trailing whitespace+ pub trim_trailing: bool,+ /// Whether to normalize line endings to LF+ pub normalize_newlines: bool,+}++impl FormatConfig {+ /// Create a new configuration with default values.+ pub fn new() -> Self {+ Self {+ max_width: Some(80),+ indent: " ".to_string(),+ trim_trailing: true,+ normalize_newlines: true,+ }+ }++ /// Set the maximum line width.+ pub fn with_max_width(mut self, width: usize) -> Self {+ self.max_width = Some(width);+ self+ }++ /// Set the indentation string.+ pub fn with_indent(mut self, indent: impl Into<String>) -> Self {+ self.indent = indent.into();+ self+ }+}++/// Format a string according to the given configuration.+///+/// # Arguments+///+/// * `input` - The string to format+/// * `config` - The formatting configuration+///+/// # Returns+///+/// The formatted string.+pub fn format_string(input: &str, config: &FormatConfig) -> String {+ let mut output = input.to_string();++ // Normalize line endings+ if config.normalize_newlines {+ output = output.replace("\r\n", "\n").replace('\r', "\n");+ }++ // Trim trailing whitespace from each line+ if config.trim_trailing {+ output = output+ .lines()+ .map(|line| line.trim_end())+ .collect::<Vec<_>>()+ .join("\n");+ }++ // Wrap long lines if max_width is set+ if let Some(max_width) = config.max_width {+ output = wrap_lines(&output, max_width);+ }++ output+}++/// Wrap lines that exceed the maximum width.+fn wrap_lines(input: &str, max_width: usize) -> String {+ let mut result = Vec::new();++ for line in input.lines() {+ if line.len() <= max_width {+ result.push(line.to_string());+ } else {+ // Simple word wrapping+ let mut current_line = String::new();+ for word in line.split_whitespace() {+ if current_line.is_empty() {+ current_line = word.to_string();+ } else if current_line.len() + 1 + word.len() <= max_width {+ current_line.push(' ');+ current_line.push_str(word);+ } else {+ result.push(current_line);+ current_line = word.to_string();+ }+ }+ if !current_line.is_empty() {+ result.push(current_line);+ }+ }+ }++ result.join("\n")+}++/// Parse a duration string like "5m", "2h", "1d" into seconds.+///+/// Supported units:+/// - `s` - seconds+/// - `m` - minutes+/// - `h` - hours+/// - `d` - days+///+/// # Examples+///+/// ```+/// use acme::utils::parse_duration;+///+/// assert_eq!(parse_duration("5m"), Ok(300));+/// assert_eq!(parse_duration("2h"), Ok(7200));+/// ```+pub fn parse_duration(input: &str) -> Result<u64, String> {+ let input = input.trim();+ if input.is_empty() {+ return Err("empty duration string".to_string());+ }++ let (num_str, unit) = input.split_at(input.len() - 1);+ let num: u64 = num_str+ .parse()+ .map_err(|_| format!("invalid number: {}", num_str))?;++ let multiplier = match unit {+ "s" => 1,+ "m" => 60,+ "h" => 3600,+ "d" => 86400,+ _ => return Err(format!("unknown unit: {}", unit)),+ };++ Ok(num * multiplier)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_normalize_path() {+ assert_eq!(normalize_path("/foo/bar/../baz"), PathBuf::from("/foo/baz"));+ assert_eq!(normalize_path("/foo/./bar"), PathBuf::from("/foo/bar"));+ }++ #[test]+ fn test_parse_duration() {+ assert_eq!(parse_duration("5m"), Ok(300));+ assert_eq!(parse_duration("2h"), Ok(7200));+ assert_eq!(parse_duration("1d"), Ok(86400));+ assert!(parse_duration("").is_err());+ assert!(parse_duration("5x").is_err());+ }++ #[test]+ fn test_format_config() {+ let config = FormatConfig::new().with_max_width(100).with_indent(" ");+ assert_eq!(config.max_width, Some(100));+ assert_eq!(config.indent, " ");+ }++ #[test]+ fn test_format_string_trailing_whitespace() {+ let config = FormatConfig::new();+ let input = "hello \nworld ";+ let output = format_string(input, &config);+ assert!(!output.lines().any(|l| l.ends_with(' ')));+ }+}diff --git a/docs/demos/shared/lib.py b/docs/demos/shared/lib.pyindex 5e99577c4..2a859d092 100644--- a/docs/demos/shared/lib.py+++ b/docs/demos/shared/lib.py@@ -223,7 +223,7 @@ def prepare_demo_repo(env: DemoEnv, repo_root: Path, hooks_config: str = None):If None, uses default pre-merge hook.After calling this, main is at the latest commit and worktrees exist for- alpha, beta, hooks. Demos can then add their own branches/config.+ alpha, beta, hooks. Demos can then add their own config."""# Base setup: git repo, Rust project, bat wrapper, wt binaryprepare_base_repo(env, repo_root)@@ -298,6 +298,15 @@ Run `wt list` to see all worktrees.git(["-C", str(env.repo), "add", "README.md"])commit_dated(env.repo, "docs: add license", "3d")+ # Add utils module with substantial content+ shutil.copy(FIXTURES_DIR / "alpha-utils.rs", env.repo / "src" / "utils.rs")+ # Update lib.rs to include the module+ lib_rs = env.repo / "src" / "lib.rs"+ lib_content = lib_rs.read_text()+ lib_rs.write_text("pub mod utils;\n\n" + lib_content)+ git(["-C", str(env.repo), "add", "src/utils.rs", "src/lib.rs"])+ commit_dated(env.repo, "feat: add utility functions module", "3d")+git(["-C", str(env.repo), "push", "-u", "origin", branch, "-q"])git(["-C", str(env.repo), "checkout", "-q", "main"])git(["-C", str(env.repo), "worktree", "add", "-q", str(path), branch])diff --git a/docs/demos/wt-select/CLAUDE.md b/docs/demos/wt-select/CLAUDE.mdindex c9a619127..bdf7b8cae 100644--- a/docs/demos/wt-select/CLAUDE.md+++ b/docs/demos/wt-select/CLAUDE.md@@ -11,52 +11,18 @@ Creates:- `docs/demos/wt-select/out/wt-select-dark.gif` - Dark theme demo- Demo repo at `docs/demos/wt-select/out/.demo-select/` (gitignored)-Theme colors are defined in `docs/demos/themes.py` to match the doc site's CSS variables.--## Demo Goals--The demo showcases `wt select` with **realistic variety in all columns**:--```-Branch Status HEAD± main↕ main…± Remote⇅ CI Age-@ main ^ ○ now-+ streaming + +54 -5 ● now-+ doctor ↕ ↑1 ↓1 +320 -14 ● 2d-+ llm-templates ! ↕ +8 ↑1 ↓1 +263 -192 3d-```--Key demonstration points:-- **CI column**: hollow ○ (branch CI) vs filled ● (PR CI) vs none-- **HEAD± column**: Large staged diff (+54), small unstaged (+8), none-- **Status column**: Staged changes (+), unstaged (!), ahead/behind (↕)-- **main↕ column**: Some branches ahead-only, some ahead-and-behind-- **main…± column**: Meaningful commit diffs (small to 300+ lines)+Theme colors are defined in `docs/demos/shared/themes.py` to match the doc site's CSS variables.## How It Works-**IMPORTANT: The setup is carefully orchestrated. The sequence in `prepare_repo()` matters!**--Uses **actual commits from this repository** cherry-picked onto v0.1.11:--- **Base**: v0.1.11 tag (005db9ad)-- **Branches via cherry-pick** (simple names, no `/` to avoid path mismatch):- - `streaming` - cf667917 (Handle BrokenPipe)- - `doctor` - e286e847 (Add --doctor option, +320/-14)- - `llm-templates` - 74fe46ff (Enhance squash messages, +263/-192)--Special setup tricks:-1. **Soft reset** streaming to main creates large staged HEAD± diff-2. **Manual code additions** add more staged/unstaged changes-3. **Fake CI cache** with future timestamps prevents expiration during recording--## CI Cache Trick+Uses the **unified demo infrastructure** (`prepare_demo_repo()` from `shared/lib.py`), same as wt-core and wt-merge demos. The repo is a synthetic "acme" Rust project with alpha/beta/hooks branches designed to showcase column variety.-CI status is cached in `.git/wt-cache/ci-status/<branch>.json` files. To show CI without GitHub access:-1. Write fake cache entries directly to the cache files-2. Use **future timestamp** (1 hour ahead) so cache never expires-3. VHS recording reads cached status+Branch setup (from shared infrastructure):+- **alpha** - Large working tree changes, unpushed commits, PR CI+- **beta** - Staged changes, behind main, branch CI+- **hooks** - Staged+unstaged changes, no remote-Without the future timestamp, cache expires during recording → tries to fetch → fails → clears cache.+The demo navigates to alpha to show the large committed diff in the main…± panel.## Viewing Results@@ -114,29 +80,8 @@ ffmpeg -i demo.gif -vsync 0 /tmp/gif-frames/frame_%04d.png## Files-- `build` - Main build script+- `build` - Main build script (uses shared infrastructure from `docs/demos/shared/`)- `demo.tape` - VHS tape file with recording script- `out/` - Output directory (gitignored)-Starship config comes from shared `docs/demos/fixtures/`.--## Updating Commits--To update the cherry-picked commits, edit `CHERRY_PICKS` in `build`:--```python-CHERRY_PICKS = {- "branch-name": ("commit-hash", days_ago),- ...-}-```--Test cherry-picks apply cleanly before updating:--```bash-cd /tmp && git clone --quiet /path/to/worktrunk test-repo-cd test-repo && git checkout v0.1.11-git cherry-pick --no-commit <new-commit-hash>-```--**Note:** Use simple branch names without `/` (e.g., `streaming` not `feature/streaming`) to avoid path mismatch issues in wt list.+Starship config comes from shared `docs/demos/shared/fixtures/`.diff --git a/docs/demos/wt-select/build b/docs/demos/wt-select/buildindex 52a45093d..6b67bc77e 100755--- a/docs/demos/wt-select/build+++ b/docs/demos/wt-select/build@@ -1,36 +1,15 @@#!/usr/bin/env python3"""Build script for wt select demo GIF.-Creates a demo environment using cherry-picked commits from this repo,-records the GIF, and saves output to docs/demos/wt-select/out/.--DEMO GOALS-==========-The demo showcases `wt select` with realistic variety in the list columns.-The target output looks like:-- Branch Status HEAD± main↕ main…± Remote⇅ CI Age- @ main ^ ○ now- + streaming + +54 -5 ● now- + doctor ↕ ↑1 ↓1 +320 -14 ● 2d- + llm-templates ! ↕ +8 ↑1 ↓1 +263 -192 3d--Key demonstration points:-- **CI column variety**: hollow ○ (branch CI) vs filled ● (PR CI) vs none-- **HEAD± column**: Large staged diff (+54), small unstaged (+8), none-- **Status column**: Staged changes (+), unstaged (!), ahead/behind (↕)-- **main↕ column**: Some branches ahead-only, some ahead-and-behind-- **main…± column**: Meaningful commit diffs ranging from small to 300+ lines+Uses the shared prepare_demo_repo() infrastructure with alpha/beta/hooks branches,+same as wt-core and wt-merge demos.See CLAUDE.md for full setup details."""-import jsonimport osimport shutilimport sys-import time-from datetime import datetime, timedeltafrom pathlib import Path# Add docs/demos/ to path for shared library@@ -39,7 +18,8 @@ DEMOS_DIR = SCRIPT_DIR.parentsys.path.insert(0, str(DEMOS_DIR))from shared import (- DemoEnv, run, git, build_wt,+ DemoEnv,+ prepare_demo_repo,check_dependencies, setup_demo_output, record_all_themes,)@@ -55,252 +35,14 @@ OUTPUT_GIFS = {# Custom VHS binary with keystroke overlayVHS_BINARY = os.environ.get("VHS_KEYSTROKES", str(SCRIPT_DIR / "vhs-keystrokes" / "vhs-keystrokes"))-# Base point for demo - v0.1.11 release-BASE_COMMIT = "005db9ad"--# Commit to advance main (makes feature branches "behind" main)-MAIN_ADVANCE_COMMIT = "50ffe925" # feat(tests): test env vars (+19/-20)--# Branch configuration - real commits to cherry-pick onto branches-CHERRY_PICKS = {- "streaming": ("cf667917", 1), # Handle BrokenPipe when LLM ignores stdin- "doctor": ("e286e847", 2), # Add wt config show --doctor option- "llm-templates": ("74fe46ff", 3), # Enhance squash message generation-}---def commit_dated(repo, days_ago):- """Amend commit with a date offset in days."""- now = datetime.now()- delta = timedelta(days=days_ago)- date_str = (now - delta).strftime("%Y-%m-%dT%H:%M:%S")- env = os.environ.copy()- env["GIT_AUTHOR_DATE"] = date_str- env["GIT_COMMITTER_DATE"] = date_str- git(["-C", str(repo), "commit", "--amend", "--no-edit", "--date", date_str], env=env)---def prepare_repo(env: DemoEnv):- """Set up the demo repository with variety in all columns."""- # Clean previous- shutil.rmtree(env.root, ignore_errors=True)- env.root.mkdir(parents=True)- env.work_base.mkdir(parents=True)-- # Clone with enough depth to have the commits we need- print(f"Cloning to {env.repo}...")- run(["git", "clone", "--quiet", "--depth", "200", str(REPO_ROOT), str(env.repo)])-- # Configure repo- git(["-C", str(env.repo), "config", "user.name", "Demo User"])- git(["-C", str(env.repo), "config", "user.email", "[email protected]"])- git(["-C", str(env.repo), "config", "commit.gpgsign", "false"])-- # Get current branch name and rename to main if needed- current_branch = run(["git", "-C", str(env.repo), "rev-parse", "--abbrev-ref", "HEAD"], capture=True).strip()- if current_branch != "main":- git(["-C", str(env.repo), "branch", "-m", current_branch, "main"])-- # Reset main to base commit (v0.1.12)- git(["-C", str(env.repo), "reset", "--hard", BASE_COMMIT])-- # Remove origin to avoid remote comparisons- git(["-C", str(env.repo), "remote", "remove", "origin"])-- # User config for wt- config_dir = env.home / ".config" / "worktrunk"- config_dir.mkdir(parents=True)- (config_dir / "config.toml").write_text("""# Demo config-[worktree]-base-path = "~/w"-""")-- # Create feature branches with cherry-picked commits- for branch_name, (commit_hash, days_ago) in CHERRY_PICKS.items():- create_branch_with_cherry_pick(env, branch_name, commit_hash, days_ago)-- # Advance main so some branches are "behind"- advance_main(env)-- # Make streaming also have the advance commit (so it's only ahead, not behind)- add_commit_to_branch(env, "streaming", MAIN_ADVANCE_COMMIT)-- # Soft reset streaming to main - all committed work becomes uncommitted- soft_reset_to_main(env, "streaming")-- # Add uncommitted working tree changes- add_uncommitted_changes(env)-- # Add fake CI status for demo- add_ci_status(env)---def create_branch_with_cherry_pick(env: DemoEnv, branch_name: str, commit_hash: str, days_ago: int):- """Create a branch with a cherry-picked commit and worktree."""- print(f"Creating branch {branch_name} (cherry-pick {commit_hash})...")-- git(["-C", str(env.repo), "checkout", "-q", "main"])- git(["-C", str(env.repo), "checkout", "-q", "-b", branch_name])- git(["-C", str(env.repo), "cherry-pick", "--no-commit", commit_hash])-- msg = run(["git", "-C", str(env.repo), "log", "-1", "--format=%s", commit_hash], capture=True).strip()- git(["-C", str(env.repo), "commit", "-m", msg])- commit_dated(env.repo, days_ago)-- worktree_path = env.work_base / f"worktrunk.{branch_name}"- git(["-C", str(env.repo), "checkout", "-q", "main"])- git(["-C", str(env.repo), "worktree", "add", "-q", str(worktree_path), branch_name])---def advance_main(env: DemoEnv):- """Advance main branch so feature branches are behind."""- print(f"Advancing main with {MAIN_ADVANCE_COMMIT}...")- git(["-C", str(env.repo), "checkout", "-q", "main"])- git(["-C", str(env.repo), "cherry-pick", "--no-commit", MAIN_ADVANCE_COMMIT])- msg = run(["git", "-C", str(env.repo), "log", "-1", "--format=%s", MAIN_ADVANCE_COMMIT], capture=True).strip()- git(["-C", str(env.repo), "commit", "-m", msg])---def add_commit_to_branch(env: DemoEnv, branch_name: str, commit_hash: str):- """Add a commit to an existing branch (in its worktree)."""- print(f"Adding {commit_hash} to {branch_name}...")- worktree_path = env.work_base / f"worktrunk.{branch_name}"- git(["-C", str(worktree_path), "cherry-pick", "--no-commit", commit_hash])- msg = run(["git", "-C", str(worktree_path), "log", "-1", "--format=%s", commit_hash], capture=True).strip()- git(["-C", str(worktree_path), "commit", "-m", msg])---def soft_reset_to_main(env: DemoEnv, branch_name: str):- """Soft reset a branch to main, keeping all changes as uncommitted."""- print(f"Soft resetting {branch_name} to main...")- worktree_path = env.work_base / f"worktrunk.{branch_name}"- git(["-C", str(worktree_path), "reset", "--soft", "main"])---def add_uncommitted_changes(env: DemoEnv):- """Add uncommitted working tree changes manually."""- # streaming: Add substantial staged changes- streaming_path = env.work_base / "worktrunk.streaming"- error_file = streaming_path / "src" / "error_handling.rs"- print("Adding staged changes to streaming...")- error_file.write_text('''//! Error handling utilities for pipe operations.-//!-//! This module provides robust error handling for cases where-//! the LLM process ignores stdin or terminates unexpectedly.--use std::io::{self, ErrorKind};--/// Errors that can occur during pipe operations.-#[derive(Debug)]-pub enum PipeError {- /// The receiving end closed the pipe.- BrokenPipe,- /// The operation timed out.- Timeout { elapsed_ms: u64 },- /// An I/O error occurred.- Io(io::Error),-}--impl From<io::Error> for PipeError {- fn from(err: io::Error) -> Self {- match err.kind() {- ErrorKind::BrokenPipe => PipeError::BrokenPipe,- ErrorKind::TimedOut => PipeError::Timeout { elapsed_ms: 0 },- _ => PipeError::Io(err),- }- }-}--impl std::fmt::Display for PipeError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- PipeError::BrokenPipe => write!(f, "pipe closed by receiver"),- PipeError::Timeout { elapsed_ms } => {- write!(f, "operation timed out after {}ms", elapsed_ms)- }- PipeError::Io(e) => write!(f, "I/O error: {}", e),- }- }-}--impl std::error::Error for PipeError {}--/// Check if an error indicates the pipe was broken.-pub fn is_broken_pipe(err: &io::Error) -> bool {- err.kind() == ErrorKind::BrokenPipe-}-''')- git(["-C", str(streaming_path), "add", "src/error_handling.rs"])-- # llm-templates: Add unstaged changes- templates_path = env.work_base / "worktrunk.llm-templates"- llm_file = templates_path / "src" / "llm.rs"- if llm_file.exists():- print("Adding uncommitted changes to llm-templates...")- content = llm_file.read_text()- content = content.replace(- "use std::io::Write;",- """use std::io::Write;--// TODO(wip): Add template validation before rendering-fn validate_template(template: &str) -> Result<(), String> {- if template.is_empty() {- return Err("Template cannot be empty".to_string());- }- Ok(())-}""",- )- llm_file.write_text(content)---def add_ci_status(env: DemoEnv):- """Add fake CI status to file-based cache for demo."""- # Use future timestamp to prevent cache expiration- future_time = int(time.time()) + 3600-- def get_head(branch):- if branch == "main":- return run(["git", "-C", str(env.repo), "rev-parse", "HEAD"], capture=True).strip()- worktree = env.work_base / f"worktrunk.{branch}"- return run(["git", "-C", str(worktree), "rev-parse", "HEAD"], capture=True).strip()-- ci_configs = {- "main": {- "status": {"ci_status": "passed", "source": "branch", "is_stale": False, "url": None},- "checked_at": future_time,- "head": get_head("main"),- },- "streaming": {- "status": {"ci_status": "passed", "source": "pullrequest", "is_stale": False,- "url": "https://github.com/example/worktrunk/pull/85"},- "checked_at": future_time,- "head": get_head("streaming"),- },- "doctor": {- "status": {"ci_status": "running", "source": "pullrequest", "is_stale": False,- "url": "https://github.com/example/worktrunk/pull/92"},- "checked_at": future_time,- "head": get_head("doctor"),- },- }-- print("Adding CI status cache...")- cache_dir = env.repo / ".git" / "wt-cache" / "ci-status"- cache_dir.mkdir(parents=True, exist_ok=True)- for branch, config in ci_configs.items():- (cache_dir / f"{branch}.json").write_text(json.dumps(config))-def main():check_dependencies(["git"])setup_demo_output(OUT_DIR)- # Build wt binary- build_wt(REPO_ROOT)-- # Create demo environment- demo_env = DemoEnv(name="select", out_dir=OUT_DIR)- prepare_repo(demo_env)+ # Create demo environment (uses shared infrastructure like other demos)+ demo_env = DemoEnv(name="select", out_dir=OUT_DIR, repo_name="acme")+ prepare_demo_repo(demo_env, REPO_ROOT)print(f"\nDemo repo created at: {demo_env.repo}")print(f"Worktrees at: {demo_env.work_base}")diff --git a/docs/demos/wt-select/demo.tape b/docs/demos/wt-select/demo.tapeindex 227e4bf9f..77e5a69ca 100644--- a/docs/demos/wt-select/demo.tape+++ b/docs/demos/wt-select/demo.tape@@ -47,7 +47,7 @@ Type "wt select"EnterSleep 2s-# Navigate to doctor branch (has large main…± diff: +320 -14)+# Navigate to alpha branch (has large main…± diff and working tree changes)DownSleep 1sDown@@ -66,7 +66,7 @@ Ctrl+dSleep 1.5s# Filter to narrow down and select-Type "str"+Type "alp"Sleep 1.5sEnterSleep 2s