Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add subdoc expansion for nested command documentation
Maximilian Roos67cfcd0f6364
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex 4fac6a769..1005d9d68 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -200,6 +200,47 @@ To add web-only styling for new content, edit `colorize_ci_status_for_html()` inSimilarly, `md_help::colorize_status_symbols()` applies ANSI colors for terminal `--help` output.+### Subdoc expansion++Include subcommand documentation as H2 sections within a parent command's docs page using subdoc placeholders:++```markdown+<!-- subdoc: subcommand-name -->+```++In `cli.rs`, add the placeholder anywhere in the parent command's `after_long_help`:++```rust+after_long_help = r#"...main documentation...++<!-- subdoc: create -->++...more documentation..."#+```++This expands during `--help-page` generation to:++```markdown+## wt config create++### User config+[subcommand's after_long_help content with heading levels increased]++---++### Command reference+[subcommand's usage and options]+```++**How it works:**+- The placeholder is invisible in terminal `--help` output (HTML comment)+- Heading levels in the subcommand's `after_long_help` are increased by one (## → ###)+- The subcommand's help reference is formatted as a nested `### Command reference`++**Use cases:**+- `wt config create` — Shows the actual config file templates (via `include_str!`)+- `wt config var get` — Shows per-variable examples not in the parent+All AUTO-GENERATED markers use a consistent format with START and END tags:```html<!-- ⚠️ AUTO-GENERATED from <source> — edit <file> to update -->diff --git a/docs/content/config.md b/docs/content/config.mdindex aab8537ca..b22f6c118 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -213,6 +213,411 @@ WORKTRUNK_COMMIT_GENERATION__ARGS="test: automated commit" \| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) || `CLICOLOR_FORCE` | Force colored output even when not a TTY |+## wt config create++### User config++Creates `~/.config/worktrunk/config.toml` with the following content:++```+# Worktrunk Global Configuration+# Copy to: ~/.config/worktrunk/config.toml (or use `wt config create`)+#+# Alternative locations (XDG Base Directory spec):+# macOS/Linux: $XDG_CONFIG_HOME/worktrunk/config.toml+# Windows: %APPDATA%\worktrunk\config.toml++# Commit Message Generation (Optional)+# For generating commit messages during merge operations (wt merge)+[commit-generation]+# Example: Simon Willison's llm CLI (https://github.com/simonw/llm)+# Install: pip install llm llm-anthropic+command = "llm"+args = ["-m", "claude-haiku-4.5"]++# Alternative: AIChat - Rust-based, supports 20+ providers+# Install from: https://github.com/sigoden/aichat+# command = "aichat"+# args = ["-m", "claude:claude-haiku-4.5"]++# Optional: Load template from file (mutually exclusive with 'template')+# Supports ~ expansion: ~/.config/worktrunk/commit-template.txt+# template-file = "~/.config/worktrunk/commit-template.txt"++# Optional: Load squash template from file (mutually exclusive with 'squash-template')+# Supports ~ expansion: ~/.config/worktrunk/squash-template.txt+# squash-template-file = "~/.config/worktrunk/squash-template.txt"++# See "Custom Prompt Templates" section at end of file for inline template options.++# Worktree Path Template+# Variables:+# {{ main_worktree }} - Main worktree directory name (e.g., "myproject")+# {{ branch }} - Branch name with slashes replaced by dashes (feature/auth → feature-auth)+#+# Paths are relative to the main worktree root (original repository directory).+#+# Example paths created (main worktree at /Users/dev/myproject, branch feature/auth):+# "../{{ main_worktree }}.{{ branch }}" → /Users/dev/myproject.feature-auth+# ".worktrees/{{ branch }}" → /Users/dev/myproject/.worktrees/feature-auth+worktree-path = "../{{ main_worktree }}.{{ branch }}"++# Alternative: Inside repo (useful for bare repos)+# worktree-path = ".worktrees/{{ branch }}"++# List Command Defaults+# Configure default behavior for `wt list`+[list]+full = false # Show CI and `main` diffstat by default+branches = false # Include branches without worktrees by default+remotes = false # Include remote branches by default++# Commit Defaults (shared by `wt step commit`, `wt step squash`, and `wt merge`)+[commit]+stage = "all" # What to stage: "all", "tracked", or "none"++# Merge Command Defaults+# Note: `stage` defaults from [commit] section above+[merge]+squash = true # Squash commits when merging+commit = true # Commit, squash, and rebase during merge+remove = true # Remove worktree after merge+verify = true # Run project hooks++# Approved Commands+# Commands approved for automatic execution after switching worktrees+# Auto-populated when you use: wt switch --execute "command" --force+[projects."github.com/user/repo"]+approved-commands = ["npm install"]++# NOTE: For project-specific hooks (post-create, post-start, pre-merge, etc.),+# use a separate PROJECT config file at <repo>/.config/wt.toml+# Run `wt config create --project` to create one, or see https://worktrunk.dev/hooks/++# ============================================================================+# Custom Prompt Templates (Advanced)+# ============================================================================+# These options belong under [commit-generation] section above.+# NOTE: Templates are synced from src/llm.rs by `cargo test readme_sync`++# Optional: Custom prompt template (inline) - Uses minijinja syntax+# Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}+# If not specified, uses the default template shown below:+# <!-- DEFAULT_TEMPLATE_START -->+# template = """+# Format+# - First line: <50 chars, present tense, describes WHAT and WHY (not HOW).+# - Blank line after first line.+# - Optional details with proper line breaks explaining context. Commits with more substantial changes should have more details.+# - Return ONLY the formatted message without quotes, code blocks, or preamble.+#+# Style+# - Do not give normative statements or otherwise speculate on why the change was made.+# - Broadly match the style of the previous commit messages.+# - For example, if they're in conventional commit format, use conventional commits; if they're not, don't use conventional commits.+#+# The context contains:+# - <git-diff> with the staged changes. This is the ONLY content you should base your message on.+# - <git-info> with branch name and recent commit message titles for style reference ONLY. DO NOT use their content to inform your message.+#+# ---+# The following is the context for your task:+# ---+# <git-diff>+# ```+# {{ git_diff }}+# ```+# </git-diff>+#+# <git-info>+# <current-branch>{{ branch }}</current-branch>+# {% if recent_commits %}+# <previous-commit-message-titles>+# {% for commit in recent_commits %}+# <previous-commit-message-title>{{ commit }}</previous-commit-message-title>+# {% endfor %}+# </previous-commit-message-titles>+# {% endif %}+# </git-info>+# """+# <!-- DEFAULT_TEMPLATE_END -->+#+# Example alternative template with different style:+# template = """+# Generate a commit message for {{ repo | upper }}.+#+# Branch: {{ branch }}+# {%- if recent_commits %}+#+# Recent commit style ({{ recent_commits | length }} commits):+# {%- for commit in recent_commits %}+# {{ loop.index }}. {{ commit }}+# {%- endfor %}+# {%- endif %}+#+# Changes to commit:+# ```+# {{ git_diff }}+# ```+#+# Requirements:+# - Follow the style of recent commits above+# - First line under 50 chars+# - Focus on WHY, not HOW+# """++# Optional: Custom squash commit message template (inline) - Uses minijinja syntax+# Available variables: {{ git_diff }}, {{ branch }}, {{ recent_commits }}, {{ repo }}, {{ commits }}, {{ target_branch }}+# If not specified, uses the default template:+# <!-- DEFAULT_SQUASH_TEMPLATE_START -->+# squash-template = """+# Generate a commit message that combines these changes into one cohesive message. Output only the commit message without any explanation.+#+# Format+# - First line: <50 chars, present tense, describes WHAT and WHY (not HOW).+# - Blank line after first line.+# - Optional details with proper line breaks explaining context.+# - Match the style of the existing commits being squashed (e.g., if they use conventional commits, use conventional commits).+#+# Squashing commits from {{ branch }} to merge into {{ target_branch }}+#+# Commits being combined:+# {% for commit in commits %}+# - {{ commit }}+# {% endfor %}+#+# <git-diff>+# ```+# {{ git_diff }}+# ```+# </git-diff>+# """+# <!-- DEFAULT_SQUASH_TEMPLATE_END -->+#+# Example alternative template:+# squash-template = """+# Squashing {{ commits | length }} commit(s) from {{ branch }} to {{ target_branch }}.+#+# {% if commits | length > 1 -%}+# Commits being combined:+# {%- for c in commits %}+# {{ loop.index }}/{{ loop.length }}: {{ c }}+# {%- endfor %}+# {%- else -%}+# Single commit: {{ commits[0] }}+# {%- endif %}+#+# Generate one cohesive commit message that captures the overall change.+# Use conventional commit format (feat/fix/docs/refactor).+# """+```++### Project config++With `--project`, creates `.config/wt.toml` in the current repository:++```+# Worktrunk Project Configuration+# Copy to: <repo>/.config/wt.toml+#+# This file defines project-specific hooks that run automatically during+# worktree operations. It should be checked into git and shared across all+# developers working on the project.++# Available template variables (all hooks):+# {{ repo }} - Repository name (e.g., "my-project")+# {{ branch }} - Branch name (slashes replaced with dashes)+# {{ worktree }} - Absolute path to the worktree+# {{ repo_root }} - Absolute path to the repository root+#+# Merge-related hooks also support:+# {{ target }} - Target branch for the merge (e.g., "main")++# Post-Create Hook+# Runs SEQUENTIALLY and BLOCKS until complete+# The worktree switch won't complete until these finish+# Commands run one after another in the worktree directory+#+# Format options:+# 1. Single string:+# post-create = "npm install"+#+# 2. Named table (runs sequentially in declaration order):+# [post-create]+# install = "npm install --frozen-lockfile"+# build = "npm run build"++# Post-Start Hook+# Runs in BACKGROUND as detached processes (parallel)+# Use for: uv sync, npm install, bundle install, build, dev servers, file watchers,+# downloading assets too large for git (images, ML models, binaries), long-running tasks+# The worktree switch completes immediately, these run in parallel+# Output is logged to .git/wt-logs/{branch}-post-start-{name}.log+#+# Format options:+# 1. Single string:+# post-start = "npm run dev"+#+# 2. Named table (runs in parallel):+# [post-start]+# server = "npm run dev"+# watch = "npm run watch"++# Pre-Commit Hook+# Runs SEQUENTIALLY before committing changes during merge (blocking, fail-fast)+# All commands must exit with code 0 for commit to proceed+# Runs for both squash and no-squash merge modes+# Use for: formatters, linters, quick validation+#+# Single command:+# pre-commit = "cargo fmt -- --check"+#+# Multiple commands:+# [pre-commit]+# format = "cargo fmt -- --check"+# lint = "cargo clippy -- -D warnings"++# Pre-Merge Hook+# Runs SEQUENTIALLY before merging to target branch (blocking, fail-fast)+# All commands must exit with code 0 for merge to proceed+# Use for: tests, linters, build verification before merging+#+# Single command:+# pre-merge = "cargo test"+#+# Multiple commands:+# [pre-merge]+# test = "cargo test"+# build = "cargo build --release"++# Post-Merge Hook+# Runs SEQUENTIALLY in the main worktree after successful merge (blocking)+# Runs after push succeeds but before cleanup+# Use for: updating production builds, notifications, cleanup+#+# Single command:+# post-merge = "cargo install --path ."+#+# Multiple commands:+# [post-merge]+# install = "cargo install --path ."+# notify = "echo 'Merged!'"++# Example: Node.js Project+# [post-create]+# install = "npm ci"+#+# [post-start]+# server = "npm run dev"+#+# [pre-merge]+# lint = "npm run lint"+# test = "npm test"++# Example: Rust Project+# [post-create]+# build = "cargo build"+#+# [pre-merge]+# format = "cargo fmt -- --check"+# clippy = "cargo clippy -- -D warnings"+# test = "cargo test"+#+# post-merge = "cargo install --path ."++# Example: Python Project+# [post-create]+# venv = "python -m venv .venv"+# install = ".venv/bin/pip install -r requirements.txt"+#+# [pre-merge]+# format = ".venv/bin/black --check ."+# lint = ".venv/bin/ruff check ."+# test = ".venv/bin/pytest"+```++---++### Command reference++```+wt config create - Create configuration file+Usage: wt config create [OPTIONS]++Options:+ --project+ Create project config (.config/wt.toml) instead of user config++ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ -v, --verbose+ Show commands and debug info+```+++## wt config var++Variables are runtime values stored in git config, separate from+configuration files. Use `wt config show` to view file-based configuration.++### Available variables++- **default-branch**: The repository's default branch (read-only, cached)+- **marker**: Custom status marker for a branch (shown in `wt list`)++### Examples++Get the default branch:+```bash+wt config var get default-branch+```++Set a marker for current branch:+```bash+wt config var set marker "🚧 WIP"+```++Clear markers:+```bash+wt config var clear marker --all+```++---++### Command reference++```+wt config var - Get or set runtime variables (stored in git config)+Usage: wt config var [OPTIONS] <COMMAND>++Commands:+ get Get a variable value+ set Set a variable value+ clear Clear a variable value++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ -v, --verbose+ Show commands and debug info+```+---## Command referencediff --git a/src/cli.rs b/src/cli.rsindex c1136cd64..276f42ff8 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -942,6 +942,10 @@ WORKTRUNK_COMMIT_GENERATION__ARGS="test: automated commit" \| `WORKTRUNK_CONFIG_PATH` | Override user config file location (not a config key) || `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) || `CLICOLOR_FORCE` | Force colored output even when not a TTY |++<!-- subdoc: create -->++<!-- subdoc: var -->"#)]Config {diff --git a/src/main.rs b/src/main.rsindex 778a17851..36fad022e 100644--- a/src/main.rs+++ b/src/main.rs@@ -137,6 +137,78 @@ fn maybe_handle_help_with_pager() -> bool {}}+/// Get the help reference block for a command by invoking clap's help system.+///+/// Returns the usage/options/subcommands section without the after_long_help content.+fn get_help_reference(command_path: &[&str]) -> String {+ use clap::ColorChoice;+ use clap::error::ErrorKind;++ // Build args: ["wt", "config", "create", "--help"]+ let mut args: Vec<String> = vec!["wt".to_string()];+ args.extend(command_path.iter().map(|s| s.to_string()));+ args.push("--help".to_string());++ let mut cmd = cli::build_command();+ cmd = cmd.color(ColorChoice::Never);++ let help_block = if let Err(err) = cmd.try_get_matches_from_mut(args)+ && matches!(+ err.kind(),+ ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand+ ) {+ err.render()+ .to_string()+ .replace("```text\n", "```\n")+ .replace("```console\n", "```bash\n")+ } else {+ return String::new();+ };++ // Strip after_long_help if present (it appears at the end)+ // Find it by looking for the first ## heading after Options/Arguments+ if let Some(after_help_start) = find_after_help_start(&help_block) {+ help_block[..after_help_start].trim_end().to_string()+ } else {+ help_block+ }+}++/// Find where after_long_help starts in help output.+///+/// Clap outputs: usage, description, commands/options, Global Options, then after_long_help.+/// The after_long_help can start with a heading or plain text.+fn find_after_help_start(help: &str) -> Option<usize> {+ // After Global Options section, a blank line followed by non-indented text is after_long_help+ let mut past_global_options = false;+ let mut saw_blank_after_options = false;+ let mut blank_offset = None;+ let mut offset = 0;++ for line in help.lines() {+ if line.starts_with("Global Options:") {+ past_global_options = true;+ offset += line.len() + 1;+ continue;+ }++ if past_global_options {+ if line.is_empty() {+ saw_blank_after_options = true;+ blank_offset = Some(offset);+ } else if saw_blank_after_options && !line.starts_with(' ') {+ // Non-indented line after blank = start of after_long_help+ return blank_offset;+ } else if line.starts_with(' ') {+ // Still in indented options, reset blank tracking+ saw_blank_after_options = false;+ }+ }+ offset += line.len() + 1;+ }+ None+}+/// Generate a full documentation page for a command.////// Output format:@@ -161,7 +233,6 @@ fn maybe_handle_help_with_pager() -> bool {/// This is used to generate docs/content/merge.md etc from the source.fn handle_help_page(args: &[String]) {use clap::ColorChoice;- use clap::error::ErrorKind;let mut cmd = cli::build_command();cmd = cmd.color(ColorChoice::Never);@@ -189,57 +260,20 @@ fn handle_help_page(args: &[String]) {};// Get the after_long_help content- // Transform for web docs: console→bash, status colors, demo images+ // Transform for web docs: console→bash, status colors, demo images, subdocs+ let parent_name = format!("wt {}", subcommand);let after_help = sub.get_after_long_help().map(|s| {let text = s.to_string().replace("```console\n", "```bash\n");let text = expand_demo_placeholders(&text);+ let text = expand_subdoc_placeholders(&text, sub, &parent_name);colorize_ci_status_for_html(&text)}).unwrap_or_default();// Get the help reference block- let filtered_args: Vec<String> = args- .iter()- .map(|a| {- if a == "--help-page" {- "--help".to_string()- } else {- a.clone()- }- })- .collect();-- let mut cmd_for_help = cli::build_command();- cmd_for_help = cmd_for_help.color(ColorChoice::Never);-- let help_block = if let Err(err) = cmd_for_help.try_get_matches_from_mut(filtered_args)- && matches!(- err.kind(),- ErrorKind::DisplayHelp | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand- ) {- err.render()- .to_string()- .replace("```text\n", "```\n")- .replace("```console\n", "```bash\n")- } else {- String::new()- };-- // Split help_block into before and after the after_help section- // The help block includes the after_help at the end, we want just the reference part- let reference_block = if !after_help.is_empty() {- // Find where after_help starts in the help output and take everything before it- // The after_help starts after the last option block- if let Some(pos) = help_block.find(&after_help[..after_help.len().min(50)]) {- help_block[..pos].trim_end().to_string()- } else {- help_block.clone()- }- } else {- help_block- };+ let reference_block = get_help_reference(&[subcommand]);// Output the generated content (frontmatter is in skeleton files)// Uses region markers so sync can replace just this content@@ -277,6 +311,131 @@ fn colorize_ci_status_for_html(text: &str) -> String {.replace("`●` gray", "<span style='color:#888'>●</span> gray")}+/// Increase markdown heading levels by one (## -> ###, ### -> ####, etc.)+///+/// This makes subdoc headings children of the subdoc's main heading.+/// Only transforms actual markdown headings, not code block content.+fn increase_heading_levels(content: &str) -> String {+ let mut result = Vec::new();+ let mut in_code_block = false;++ for line in content.lines() {+ // Track code block boundaries (``` or ````+)+ if line.trim_start().starts_with("```") {+ in_code_block = !in_code_block;+ result.push(line.to_string());+ continue;+ }++ // Only transform headings outside code blocks+ if !in_code_block && line.starts_with('#') {+ result.push(format!("#{}", line));+ } else {+ result.push(line.to_string());+ }+ }++ let mut output = result.join("\n");+ // Preserve trailing newline if present (.lines() strips it)+ if content.ends_with('\n') {+ output.push('\n');+ }+ output+}++/// Expand subdoc placeholders for web docs.+///+/// Transforms `<!-- subdoc: subcommand -->` into an H2 section with the subcommand's help output.+/// For example, `<!-- subdoc: create -->` in `wt config` expands to:+///+/// ```markdown+/// ## wt config create+///+/// [help output for `wt config create`]+/// ```+///+/// This allows including subcommand documentation inline in the parent command's docs page.+fn expand_subdoc_placeholders(text: &str, parent_cmd: &clap::Command, parent_name: &str) -> String {+ const PREFIX: &str = "<!-- subdoc: ";+ const SUFFIX: &str = " -->";++ let mut result = text.to_string();+ while let Some(start) = result.find(PREFIX) {+ let after_prefix = start + PREFIX.len();+ if let Some(end_offset) = result[after_prefix..].find(SUFFIX) {+ let subcommand_name = result[after_prefix..after_prefix + end_offset].trim();+ let end = after_prefix + end_offset + SUFFIX.len();++ // Find the subcommand in the parent+ let replacement = if let Some(sub) = parent_cmd+ .get_subcommands()+ .find(|s| s.get_name() == subcommand_name)+ {+ format_subcommand_section(sub, parent_name, subcommand_name)+ } else {+ format!(+ "<!-- subdoc error: subcommand '{}' not found -->",+ subcommand_name+ )+ };++ result.replace_range(start..end, &replacement);+ } else {+ break;+ }+ }+ result+}++/// Format a subcommand as an H2 section for docs.+///+/// Includes the subcommand's `after_long_help` (conceptual docs) followed by+/// the command reference (usage, options).+fn format_subcommand_section(+ sub: &clap::Command,+ parent_name: &str,+ subcommand_name: &str,+) -> String {+ // parent_name is "wt config", subcommand_name is "create"+ // full_command is "wt config create"+ let full_command = format!("{} {}", parent_name, subcommand_name);++ // Get the after_long_help content (conceptual docs)+ // Increase heading levels since this will be nested under an H2+ let after_help = sub+ .get_after_long_help()+ .map(|s| {+ let text = s.to_string().replace("```console\n", "```bash\n");+ let text = increase_heading_levels(&text);+ colorize_ci_status_for_html(&text)+ })+ .unwrap_or_default();++ // Build command path from parent_name: "wt config" -> ["config", "create"]+ let command_path: Vec<&str> = parent_name+ .strip_prefix("wt ")+ .unwrap_or(parent_name)+ .split_whitespace()+ .chain(std::iter::once(subcommand_name))+ .collect();++ let reference_block = get_help_reference(&command_path);++ // Format the section+ let mut section = format!("## {}\n\n", full_command);++ if !after_help.is_empty() {+ section.push_str(after_help.trim());+ section.push_str("\n\n---\n\n");+ }++ section.push_str("### Command reference\n\n```\n");+ section.push_str(reference_block.trim());+ section.push_str("\n```\n");++ section+}+/// Expand demo GIF placeholders for web docs.////// Transforms `<!-- demo: filename.gif -->` into an HTML figure with the `demo` class.