Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Docs: Add terminal shortcode with ANSI to HTML conversion
Maximilian Roos63879dcae782
diff --git a/Cargo.lock b/Cargo.lockindex 000e0fcb0..0b27940a8 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -53,6 +53,16 @@ dependencies = ["ansitok",]+[[package]]+name = "ansi-to-html"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12e283a4fc285735ef99577e81a125f738429516161ac33977e466d0d8d40764"+dependencies = [+ "regex",+ "thiserror 1.0.69",+]+[[package]]name = "ansitok"version = "0.3.0"@@ -2926,6 +2936,7 @@ name = "worktrunk"version = "0.1.10"dependencies = ["ansi-str",+ "ansi-to-html","anstream","anstyle","anyhow",diff --git a/Cargo.toml b/Cargo.tomlindex ae129f38a..eaa1b59f3 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -90,6 +90,7 @@ criterion = "0.8"portable-pty = "0.9"regex = "1.12"vt100 = "0.16"+ansi-to-html = "0.2.2"[[bench]]name = "completion"diff --git a/docs/content/configuration.md b/docs/content/configuration.mdindex 4b2bbf757..15a92633c 100644--- a/docs/content/configuration.md+++ b/docs/content/configuration.md@@ -45,17 +45,21 @@ Create `.config/wt.toml` in your repository:### Hook execution-```bash-$ wt switch --create feature-x-🔄 Running post-create install:- uv sync+<!-- ⚠️ AUTO-GENERATED-HTML from tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap — edit source to update -->++{% terminal() %}+<span class="prompt">$</span> wt switch --create feature-x+🔄 <span style='color:var(--cyan,#0aa)'>Running post-create <b>install</b>:</span>+<span style='background:var(--bright-white,#fff)'> </span> <span style='opacity:0.67'><span style='color:var(--blue,#00a)'>uv</span></span><span style='opacity:0.67'> sync</span>Resolved 24 packages in 145msInstalled 24 packages in 1.2s-✅ Created new worktree for feature-x from main at ../repo.feature-x-🔄 Running post-start dev:- uv run dev-```+✅ <span style='color:var(--green,#0a0)'>Created new worktree for <b>feature-x</b> from <b>main</b> at <b>../repo.feature-x</b></span>+🔄 <span style='color:var(--cyan,#0aa)'>Running post-start <b>dev</b>:</span>+<span style='background:var(--bright-white,#fff)'> </span> <span style='opacity:0.67'><span style='color:var(--blue,#00a)'>uv</span></span><span style='opacity:0.67'> run dev</span>+{% end %}++<!-- END AUTO-GENERATED -->**Security**: Project commands require approval on first run. Approvals are saved to user config. Use `--force` to bypass prompts or `--no-verify` to skip hooks entirely.diff --git a/docs/content/quickstart.md b/docs/content/quickstart.mdindex 3a6af86de..7aa8c2706 100644--- a/docs/content/quickstart.md+++ b/docs/content/quickstart.md@@ -21,31 +21,43 @@ $ wt config shell install## Create a worktree-```bash-$ wt switch --create fix-auth-✅ Created new worktree for fix-auth from main at ../repo.fix-auth-```+<!-- ⚠️ AUTO-GENERATED-HTML from tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_simple_switch.snap — edit source to update -->++{% terminal() %}+<span class="prompt">$</span> wt switch --create fix-auth+✅ <span style='color:var(--green,#0a0)'>Created new worktree for <b>fix-auth</b> from <b>main</b> at <b>../repo.fix-auth</b></span>+{% end %}++<!-- END AUTO-GENERATED -->This creates `../repo.fix-auth` on branch `fix-auth`.## Switch between worktrees-```bash-$ wt switch feature-api-✅ Switched to worktree for feature-api at ../repo.feature-api-```+<!-- ⚠️ AUTO-GENERATED-HTML from tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_switch_back.snap — edit source to update -->++{% terminal() %}+<span class="prompt">$</span> wt switch feature-api+✅ <span style='color:var(--green,#0a0)'>Switched to worktree for <b>feature-api</b> at <b>../repo.feature-api</b></span>+{% end %}++<!-- END AUTO-GENERATED -->## List worktrees-```bash-$ wt list- Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message-@ feature-api + ↑⇡ +36 -11 ↑4 ./repo.feature-api ⇡3 b1554967 30m Add API tests-^ main ^⇣ ./repo ⇣1 b834638e 1d Initial commit-+ fix-auth _ ./repo.fix-auth b834638e 1d Initial commit+<!-- ⚠️ AUTO-GENERATED-HTML from tests/snapshots/integration__integration_tests__list__readme_example_simple_list.snap — edit source to update -->-⚪ Showing 3 worktrees, 1 with changes, 1 ahead-```+{% terminal() %}+<span class="prompt">$</span> wt list+ <b>Branch</b> <b>Status</b> <b>HEAD±</b> <b>main↕</b> <b>Path</b> <b>Remote⇅</b> <b>Commit</b> <b>Age</b> <b>Message</b>+@ <b>feature-api</b> <span style='color:var(--cyan,#0aa)'>+</span> <span style='opacity:0.67'>↑</span><span style='opacity:0.67'>⇡</span> <span style='color:var(--green,#0a0)'>+36</span> <span style='color:var(--red,#a00)'>-11</span> <span style='color:var(--green,#0a0)'>↑4</span> <b>./repo.feature-api</b> <span style='color:var(--green,#0a0)'>⇡3</span> <span style='opacity:0.67'>b1554967</span> <span style='opacity:0.67'>30m</span> <span style='opacity:0.67'>Add API tests</span>+^ main <span style='opacity:0.67'>^</span><span style='opacity:0.67'>⇣</span> ./repo <span style='opacity:0.67'><span style='color:var(--red,#a00)'>⇣1</span></span> <span style='opacity:0.67'>b834638e</span> <span style='opacity:0.67'>1d</span> <span style='opacity:0.67'>Initial commit</span>++ <span style='opacity:0.67'>fix-auth</span> <span style='opacity:0.67'>_</span> <span style='opacity:0.67'>./repo.fix-auth</span> <span style='opacity:0.67'>b834638e</span> <span style='opacity:0.67'>1d</span> <span style='opacity:0.67'>Initial commit</span>++⚪ <span style='opacity:0.67'>Showing 3 worktrees, 1 with changes, 1 ahead</span>+{% end %}++<!-- END AUTO-GENERATED -->Add `--full` for CI status and conflicts. Add `--branches` to include all branches.@@ -53,10 +65,14 @@ Add `--full` for CI status and conflicts. Add `--branches` to include all branchWhen you're done with a worktree (e.g., after merging via CI):-```bash-$ wt remove-🔄 Removing feature-api worktree & branch in background (already in main)-```+<!-- ⚠️ AUTO-GENERATED-HTML from tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_remove.snap — edit source to update -->++{% terminal() %}+<span class="prompt">$</span> wt remove+🔄 <span style='color:var(--cyan,#0aa)'>Removing <b>feature-api</b> worktree & branch in background (already in main)</span>+{% end %}++<!-- END AUTO-GENERATED -->Worktrunk checks if your changes are already on main before deleting the branch.diff --git a/docs/sass/custom.scss b/docs/sass/custom.scssindex 93c056d3a..b89f41644 100644--- a/docs/sass/custom.scss+++ b/docs/sass/custom.scss@@ -1,6 +1,28 @@// Custom styles for Worktrunk docs// Only add what the theme doesn't provide; prefer theme defaults+// Terminal output styling (ANSI colors via inline styles from ansi-to-html crate)+.terminal {+ background-color: #ffffff;+ border: 1px solid #e0e0e0;+ border-radius: 6px;+ padding: 1rem;+ overflow-x: auto;+ margin: 1rem 0;+ font-family: 'SF Mono', 'Menlo', 'Monaco', 'Consolas', monospace;+ font-size: 0.875rem;+ line-height: 1.5;++ code {+ background-color: transparent;+ color: #323232;+ padding: 0;+ }++ // Prompt styling (manually added, not from ANSI conversion)+ .prompt { color: #666666; }+}+// Code block enhancements (theme handles colors via CSS vars).content pre {border: 1px solid #e0e0e0;diff --git a/docs/templates/shortcodes/terminal.html b/docs/templates/shortcodes/terminal.htmlnew file mode 100644index 000000000..467960ef1--- /dev/null+++ b/docs/templates/shortcodes/terminal.html@@ -0,0 +1 @@+<pre class="terminal"><code>{{ body | safe }}</code></pre>diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rsindex 583821bca..98dbc53cb 100644--- a/tests/integration_tests/readme_sync.rs+++ b/tests/integration_tests/readme_sync.rs@@ -6,6 +6,7 @@//!//! Run with: `cargo test --test integration readme_sync`+use ansi_to_html::convert as ansi_to_html;use regex::Regex;use std::fs;use std::path::Path;@@ -34,6 +35,15 @@ static ANSI_ESCAPE_REGEX: LazyLock<Regex> =/// Regex to strip literal bracket notation (as stored in snapshots)static ANSI_LITERAL_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[[0-9;]*m").unwrap());+/// Regex to find docs snapshot markers (HTML output)+/// Format: <!-- ⚠️ AUTO-GENERATED-HTML from path.snap — edit source to update -->+static DOCS_SNAPSHOT_MARKER_PATTERN: LazyLock<Regex> = LazyLock::new(|| {+ Regex::new(+ r"(?s)<!-- ⚠️ AUTO-GENERATED-HTML from ([^\s]+\.snap) — edit source to update -->\n+\{% terminal\(\) %\}\n(.*?)\{% end %\}\n+<!-- END AUTO-GENERATED -->",+ )+ .unwrap()+});+/// Regex for HASH placeholder (used by shell_wrapper tests)static HASH_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[HASH\]").unwrap());@@ -75,6 +85,16 @@ fn strip_ansi(text: &str) -> String {ANSI_LITERAL_REGEX.replace_all(&text, "").to_string()}+/// Convert literal bracket notation [32m to actual escape sequences \x1b[32m+fn literal_to_escape(text: &str) -> String {+ ANSI_LITERAL_REGEX+ .replace_all(text, |caps: ®ex::Captures| {+ let code = caps.get(0).unwrap().as_str();+ format!("\x1b{code}")+ })+ .to_string()+}+/// Check if a line is gutter-formatted content (has the white background ANSI code)fn is_gutter_line(line: &str) -> bool {line.starts_with("[107m") || line.starts_with("\x1b[107m")@@ -254,6 +274,74 @@ fn normalize_for_readme(content: &str) -> String {trim_lines(&content)}+/// Parse snapshot content for docs (with ANSI to HTML conversion)+fn parse_snapshot_content_for_docs(content: &str) -> Result<String, String> {+ let content = content.to_string();++ // Remove YAML front matter+ let content = if content.starts_with("---") {+ let parts: Vec<&str> = content.splitn(3, "---").collect();+ if parts.len() >= 3 {+ parts[2].trim().to_string()+ } else {+ content+ }+ } else {+ content+ };++ // Handle insta_cmd format with stdout/stderr sections+ let content = if content.contains("----- stdout -----") {+ // For docs, we only use stderr (that's where user messages go)+ if let Some(start) = content.find("----- stderr -----\n") {+ let after_header = &content[start + "----- stderr -----\n".len()..];+ if let Some(end) = after_header.find("----- ") {+ after_header[..end].trim_end().to_string()+ } else {+ after_header.trim_end().to_string()+ }+ } else {+ content+ }+ } else {+ content+ };++ // Replace placeholders before ANSI conversion+ let content = HASH_REGEX.replace_all(&content, "a1b2c3d");+ let content = TMPDIR_BRANCH_REGEX.replace_all(&content, "../repo.$1");+ let content = TMPDIR_MAIN_REGEX.replace_all(&content, "../repo$1");+ let content = REPO_REGEX.replace_all(&content, "../repo");++ // Convert literal bracket notation [32m to escape sequences for the library+ let content = literal_to_escape(&content);++ // Convert ANSI to HTML using the ansi-to-html library+ let html = ansi_to_html(&content).map_err(|e| format!("ANSI conversion failed: {e}"))?;++ // The ansi-to-html library leaves bare ESC characters (\x1b) in the output+ // when processing our snapshot format. This happens because:+ // 1. Snapshots use literal bracket notation like [32m (not real escape sequences)+ // 2. We convert these to \x1b[32m before passing to ansi-to-html+ // 3. The library wraps content in HTML tags but keeps bare \x1b chars+ // Strip them all since they've already been converted to HTML styling.+ let html = html.replace('\x1b', "");++ // Clean up empty tags generated by reset codes+ let html = html.replace("<b></b>", "");+ // Remove empty spans (e.g., <span style='opacity:0.67'></span>)+ let empty_span_regex = Regex::new(r"<span[^>]*></span>").unwrap();+ let html = empty_span_regex.replace_all(&html, "").to_string();++ Ok(html)+}++/// Normalize snapshot output for docs display (just trim - placeholders already replaced)+fn normalize_for_docs(content: &str) -> String {+ // Placeholders are replaced in parse_snapshot_content_for_docs before ANSI conversion+ trim_lines(content)+}+/// Get help output for a command////// Expected format: `wt <subcommand> --help-md`@@ -585,6 +673,56 @@ fn test_readme_examples_are_in_sync() {}}+/// Update a docs section with HTML output (terminal shortcode wrapper)+fn update_docs_section(+ content: &str,+ pattern: &Regex,+ get_replacement: impl Fn(&str, &str) -> Result<String, String>,+) -> Result<(String, usize, usize), Vec<String>> {+ let mut result = content.to_string();+ let mut errors = Vec::new();+ let mut updated = 0;++ // Collect all matches first+ let matches: Vec<_> = pattern+ .captures_iter(content)+ .map(|cap| {+ let full_match = cap.get(0).unwrap();+ let id = cap.get(1).unwrap().as_str().to_string();+ let current = trim_lines(cap.get(2).unwrap().as_str());+ (full_match.start(), full_match.end(), id, current)+ })+ .collect();++ let total = matches.len();++ // Process in reverse order to preserve positions+ for (start, end, id, current) in matches.into_iter().rev() {+ let expected = match get_replacement(&id, ¤t) {+ Ok(content) => content,+ Err(e) => {+ errors.push(format!("❌ {}: {}", id, e));+ continue;+ }+ };++ if current != expected {+ let replacement = format!(+ "<!-- ⚠️ AUTO-GENERATED-HTML from {} — edit source to update -->\n\n{{% terminal() %}}\n{}\n{{% end %}}\n\n<!-- END AUTO-GENERATED -->",+ id, expected+ );+ result.replace_range(start..end, &replacement);+ updated += 1;+ }+ }++ if errors.is_empty() {+ Ok((result, updated, total))+ } else {+ Err(errors)+ }+}+#[test]fn test_docs_commands_are_in_sync() {let project_root = Path::new(env!("CARGO_MANIFEST_DIR"));@@ -602,3 +740,104 @@ fn test_docs_commands_are_in_sync() {}}}++/// Sync docs snapshot markers in a single file (with ANSI to HTML conversion)+fn sync_docs_snapshots(doc_path: &Path, project_root: &Path) -> Result<usize, Vec<String>> {+ if !doc_path.exists() {+ return Ok(0);+ }++ let content = fs::read_to_string(doc_path)+ .map_err(|e| vec![format!("Failed to read {}: {}", doc_path.display(), e)])?;++ let project_root_for_snapshots = project_root.to_path_buf();+ match update_docs_section(+ &content,+ &DOCS_SNAPSHOT_MARKER_PATTERN,+ |snap_path, current_content| {+ // Extract existing command line from docs if present+ let existing_command = current_content+ .lines()+ .find(|line| line.contains("class=\"prompt\""))+ .map(|line| {+ // Convert HTML command back to plain text for matching+ // <span class="prompt">$</span> wt switch ... -> $ wt switch ...+ let plain = strip_html_tags(line);+ plain.trim().to_string()+ });++ let full_path = project_root_for_snapshots.join(snap_path);+ let raw = fs::read_to_string(&full_path)+ .map_err(|e| format!("Failed to read {}: {}", full_path.display(), e))?;+ let html_content = parse_snapshot_content_for_docs(&raw)?;+ let normalized = normalize_for_docs(&html_content);++ // Prepend command line with prompt styling if present+ Ok(match existing_command {+ Some(cmd) if cmd.starts_with("$ ") => {+ let cmd_text = cmd.strip_prefix("$ ").unwrap();+ format!(+ "<span class=\"prompt\">$</span> {}\n{}",+ cmd_text, normalized+ )+ }+ _ => normalized,+ })+ },+ ) {+ Ok((new_content, updated_count, _total_count)) => {+ if updated_count > 0 {+ fs::write(doc_path, &new_content).unwrap();+ println!(+ "✅ Updated {} sections in {}",+ updated_count,+ doc_path.display()+ );+ }+ Ok(updated_count)+ }+ Err(errs) => Err(errs),+ }+}++#[test]+fn test_docs_quickstart_examples_are_in_sync() {+ let project_root = Path::new(env!("CARGO_MANIFEST_DIR"));++ // Process all docs files with AUTO-GENERATED-HTML markers+ let doc_files = [+ "docs/content/quickstart.md",+ "docs/content/configuration.md",+ ];++ let mut all_errors = Vec::new();++ for doc_file in doc_files {+ let doc_path = project_root.join(doc_file);+ if let Err(errors) = sync_docs_snapshots(&doc_path, project_root) {+ all_errors.extend(errors);+ }+ }++ if !all_errors.is_empty() {+ panic!(+ "Docs examples are out of sync:\n\n{}\n",+ all_errors.join("\n")+ );+ }+}++/// Strip HTML tags from a string (simple implementation for command extraction)+fn strip_html_tags(s: &str) -> String {+ let mut result = String::new();+ let mut in_tag = false;+ for c in s.chars() {+ match c {+ '<' => in_tag = true,+ '>' => in_tag = false,+ _ if !in_tag => result.push(c),+ _ => {}+ }+ }+ result+}