Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add docs-to-README section sync for DRY content management
Maximilian Roosa5783220ccad
diff --git a/README.md b/README.mdindex 587a860b5..064b47f9b 100644--- a/README.md+++ b/README.md@@ -19,6 +19,8 @@ Worktrunk is a CLI for git worktree management, designed for parallel AI agent w> ## π Full documentation at [worktrunk.dev](https://worktrunk.dev) π+<!-- β οΈ AUTO-GENERATED-SECTION from docs/content/why-worktrunk.md#context-git-worktrees..what-worktrunk-adds β edit source to update -->+## Context: git worktreesAI agents like Claude and Codex can increasingly handle longer tasks without supervision, and it's very practical to run several in parallel. But on a single file tree they step on each other's uncommitted changes.@@ -33,12 +35,12 @@ Worktrunk makes worktrees easy to use β branch-based navigation, unified statu**Core commands:**-| Task | Worktrunk | Plain git |-|------|-----------|-----------|-| Switch worktrees | `wt switch feature` | `cd ../repo.feature` |+| Task | Worktrunk | Plain git |+| --------------------- | -------------------------------- | ----------------------------------------------------------------------------- |+| Switch worktrees | `wt switch feature` | `cd ../repo.feature` || Create + start Claude | `wt switch -c -x claude feature` | `git worktree add -b feature ../repo.feature && cd ../repo.feature && claude` |-| Clean up | `wt remove` | `cd ../repo && git worktree remove ../repo.feature && git branch -d feature` |-| List with status | `wt list` | `git worktree list` (paths only) |+| Clean up | `wt remove` | `cd ../repo && git worktree remove ../repo.feature && git branch -d feature` |+| List with status | `wt list` | `git worktree list` (paths only) |**Workflow automation:**@@ -46,6 +48,8 @@ Worktrunk makes worktrees easy to use β branch-based navigation, unified statu- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** β generate commit messages from diffs via [llm](https://llm.datasette.io/)- **[Merge workflow](https://worktrunk.dev/merge/)** β squash, rebase, merge, clean up in one command+<!-- END AUTO-GENERATED-SECTION -->+## Core commands in practiceCreate a worktree for a new task:@@ -97,6 +101,8 @@ $ wt remove<!-- END AUTO-GENERATED -->+<!-- β οΈ AUTO-GENERATED-SECTION from docs/content/why-worktrunk.md#install..further-reading β edit source to update -->+## Install**Homebrew (macOS & Linux):**@@ -122,8 +128,11 @@ $ wt config shell install## Further reading-- **[Worktrunk documentation](https://worktrunk.dev)** β full docs, examples, and command reference- [Claude Code: Best practices for agentic coding](https://www.anthropic.com/engineering/claude-code-best-practices) β Anthropic's official guide, including the worktree pattern- [Shipping faster with Claude Code and Git Worktrees](https://incident.io/blog/shipping-faster-with-claude-code-and-git-worktrees) β incident.io's workflow for parallel agents- [Git worktree pattern discussion](https://github.com/anthropics/claude-code/issues/1052) β Community discussion in the Claude Code repo- [git-worktree documentation](https://git-scm.com/docs/git-worktree) β Official git reference++<!-- END AUTO-GENERATED-SECTION -->++> ## π Full documentation at [worktrunk.dev](https://worktrunk.dev) πdiff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rsindex 61e673e98..9d424c9e6 100644--- a/tests/integration_tests/readme_sync.rs+++ b/tests/integration_tests/readme_sync.rs@@ -88,6 +88,21 @@ static RUST_RAW_STRING_PATTERN: LazyLock<Regex> = LazyLock::new(|| {.unwrap()});+/// Regex to find README section markers (synced from docs)+/// Format: <!-- β οΈ AUTO-GENERATED-SECTION from path#start..end β edit source to update -->+/// The anchor can be a single section (e.g., #install) or a range (e.g., #install..further-reading)+static SECTION_MARKER_PATTERN: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(+ r"(?s)<!-- β οΈ AUTO-GENERATED-SECTION from ([^\s]+)#([^\s]+) β edit source to update -->\n+(.*?)\n*<!-- END AUTO-GENERATED-SECTION -->",+ )+ .unwrap()+});++/// Regex to convert Zola internal links to full URLs+/// Matches: [text](@/page.md) or [text](@/page.md#anchor)+static ZOLA_LINK_PATTERN: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(@/([^)#]+)\.md(#[^)]*)?\)").unwrap());+// =============================================================================// Unified Template Infrastructure// =============================================================================@@ -655,6 +670,160 @@ fn extract_templates(content: &str) -> std::collections::HashMap<String, String>.collect()}+// =============================================================================+// Docs-to-README Section Sync+// =============================================================================++/// Extract sections from markdown content by anchor range+///+/// If `anchor` contains `..`, extracts from start anchor through end anchor (inclusive).+/// Otherwise extracts a single section.+fn extract_section_by_anchor(content: &str, anchor: &str) -> Option<String> {+ let (start_anchor, end_anchor) = if let Some((start, end)) = anchor.split_once("..") {+ (start, Some(end))+ } else {+ (anchor, None)+ };++ let lines: Vec<&str> = content.lines().collect();++ // Find the start heading+ let start_idx = lines.iter().position(|line| {+ line.strip_prefix("## ")+ .or_else(|| line.strip_prefix("### "))+ .is_some_and(|text| heading_to_anchor(text) == start_anchor)+ })?;++ // Find the end: either after end_anchor section, or next same-level heading+ let end_idx = if let Some(end_anchor) = end_anchor {+ // Find where end_anchor's section ends+ let end_heading_idx = lines.iter().skip(start_idx + 1).position(|line| {+ line.strip_prefix("## ")+ .or_else(|| line.strip_prefix("### "))+ .is_some_and(|text| heading_to_anchor(text) == end_anchor)+ })? + start_idx+ + 1;++ // Find the next ## heading after end_anchor (or EOF)+ lines+ .iter()+ .skip(end_heading_idx + 1)+ .position(|line| line.starts_with("## "))+ .map(|i| i + end_heading_idx + 1)+ .unwrap_or(lines.len())+ } else {+ // Single section: find next ## heading+ lines+ .iter()+ .skip(start_idx + 1)+ .position(|line| line.starts_with("## "))+ .map(|i| i + start_idx + 1)+ .unwrap_or(lines.len())+ };++ let section = lines[start_idx..end_idx].join("\n").trim().to_string();+ Some(section)+}++/// Convert heading text to anchor format (lowercase, spaces to hyphens)+fn heading_to_anchor(heading: &str) -> String {+ heading+ .to_lowercase()+ .chars()+ .map(|c| if c.is_alphanumeric() { c } else { '-' })+ .collect::<String>()+ .split('-')+ .filter(|s| !s.is_empty())+ .collect::<Vec<_>>()+ .join("-")+}++/// Transform Zola-flavored markdown to GitHub-flavored markdown+///+/// Converts:+/// - `[text](@/page.md)` β `[text](https://worktrunk.dev/page/)`+/// - `[text](@/page.md#anchor)` β `[text](https://worktrunk.dev/page/#anchor)`+fn transform_zola_to_github(content: &str) -> String {+ ZOLA_LINK_PATTERN+ .replace_all(content, |caps: ®ex::Captures| {+ let text = caps.get(1).unwrap().as_str();+ let page = caps.get(2).unwrap().as_str();+ let anchor = caps.get(3).map_or("", |m| m.as_str());+ format!("[{text}](https://worktrunk.dev/{page}/{anchor})")+ })+ .into_owned()+}++/// Get section content from docs file, transformed for README+///+/// Extracts section(s) by anchor (supports ranges like `start..end`),+/// and transforms Zola links to GitHub URLs.+fn get_docs_section_for_readme(docs_path: &Path, anchor: &str) -> Result<String, String> {+ let content = fs::read_to_string(docs_path)+ .map_err(|e| format!("Failed to read {}: {}", docs_path.display(), e))?;++ let section = extract_section_by_anchor(&content, anchor)+ .ok_or_else(|| format!("Section '{}' not found in {}", anchor, docs_path.display()))?;++ // Transform Zola links to GitHub URLs+ Ok(transform_zola_to_github(§ion))+}++/// Sync section markers in README from docs source files+///+/// Finds markers like:+/// `<!-- β οΈ AUTO-GENERATED-SECTION from docs/content/why-worktrunk.md#section-anchor β edit source to update -->`+///+/// And replaces the content with the transformed section from the docs file.+fn sync_readme_sections(+ readme_content: &str,+ project_root: &Path,+) -> Result<(String, usize), Vec<String>> {+ let mut result = readme_content.to_string();+ let mut errors = Vec::new();+ let mut updated = 0;++ // Collect all matches first (to avoid borrowing issues)+ let matches: Vec<_> = SECTION_MARKER_PATTERN+ .captures_iter(readme_content)+ .map(|cap| {+ let full_match = cap.get(0).unwrap();+ let path = cap.get(1).unwrap().as_str().to_string();+ let anchor = cap.get(2).unwrap().as_str().to_string();+ let current = trim_lines(cap.get(3).unwrap().as_str());+ (full_match.start(), full_match.end(), path, anchor, current)+ })+ .collect();++ // Process in reverse order to preserve positions+ for (start, end, path, anchor, current) in matches.into_iter().rev() {+ let docs_path = project_root.join(&path);++ let expected = match get_docs_section_for_readme(&docs_path, &anchor) {+ Ok(content) => trim_lines(&content),+ Err(e) => {+ errors.push(format!("β {}#{}: {}", path, anchor, e));+ continue;+ }+ };++ if current != expected {+ let replacement = format!(+ "<!-- β οΈ AUTO-GENERATED-SECTION from {}#{} β edit source to update -->\n\n{}\n\n<!-- END AUTO-GENERATED-SECTION -->",+ path, anchor, expected+ );+ result.replace_range(start..end, &replacement);+ updated += 1;+ }+ }++ if errors.is_empty() {+ Ok((result, updated))+ } else {+ Err(errors)+ }+}+#[test]fn test_config_example_templates_are_in_sync() {let project_root = Path::new(env!("CARGO_MANIFEST_DIR"));@@ -796,6 +965,16 @@ fn test_readme_examples_are_in_sync() {Err(errs) => errors.extend(errs),}+ // Update section markers (synced from docs)+ match sync_readme_sections(&updated_content, project_root) {+ Ok((new_content, updated_count)) => {+ updated_content = new_content;+ total_updated += updated_count;+ checked += updated_count.max(1); // Count at least 1 if we have section markers+ }+ Err(errs) => errors.extend(errs),+ }+if checked == 0 {panic!("No README markers found in README.md");}