Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
docs: leave trailing shell comments out of copied commands (#4091)
Maximilian Roos5dec42311060
diff --git a/docs/CLAUDE.md b/docs/CLAUDE.mdindex d3bc17e6d..88a49eeab 100644--- a/docs/CLAUDE.md+++ b/docs/CLAUDE.md@@ -232,12 +232,14 @@ Starlight and Expressive Code create the frame and copy button. The Worktrunkplugin highlights `console` commands as Bash, renders `$ ` as a prompt, andmakes blocks copy their commands rather than their output. A block with onecommand copies it with its comment lines and blank recipe separators; a block-with several gives each command its own copy button. Snapshot-backed output-gets its exact ANSI roles from the generated style manifest, while hand-written-output uses a conservative marker fallback. Generated Clap help fences carry-the `wt-command-reference` marker, which the plugin expands into semantic-command, option, value, and metadata roles. Committed Markdown must remain-useful without the plugin.+with several gives each command its own copy button. Copied shell commands+leave out trailing `#` comments, which zsh passes as arguments unless+`interactivecomments` is set. Snapshot-backed output gets its exact ANSI roles+from the generated style manifest, while hand-written output uses a+conservative marker fallback. Generated Clap help fences carry the+`wt-command-reference` marker, which the plugin expands into semantic command,+option, value, and metadata roles. Committed Markdown must remain useful+without the plugin.### Web-only post-processingdiff --git a/docs/src/plugins/worktrunk-terminal.mjs b/docs/src/plugins/worktrunk-terminal.mjsindex 4b898ff45..9521849ab 100644--- a/docs/src/plugins/worktrunk-terminal.mjs+++ b/docs/src/plugins/worktrunk-terminal.mjs@@ -175,6 +175,44 @@ export function shellCommandSegments(text) {return segments;}+/**+ * A `#` that begins an unquoted word starts a shell comment. Zsh passes one to+ * the command as arguments unless `interactivecomments` is set, so copied+ * commands leave trailing comments out. A line that is only a comment stays.+ * Heredocs, backticks, and `$'…'` strings aren't parsed; no example uses them.+ */+export function withoutTrailingShellComments(code) {+ let output = '';+ let quote;+ let wordStart = true;+ for (let index = 0; index < code.length; index += 1) {+ const char = code[index];+ if (quote) {+ output += char;+ if (char === quote) quote = undefined;+ else if (char === '\\' && quote === '"') output += code[++index] ?? '';+ wordStart = false;+ } else if (char === '\\') {+ output += char + (code[++index] ?? '');+ wordStart = false;+ } else if (char === "'" || char === '"') {+ output += char;+ quote = char;+ wordStart = false;+ } else if (char === '#' && wordStart) {+ const newline = code.indexOf('\n', index);+ const lineEnd = newline === -1 ? code.length : newline;+ const lineSoFar = output.slice(output.lastIndexOf('\n') + 1);+ output = lineSoFar.trim() === '' ? output + code.slice(index, lineEnd) : output.trimEnd();+ index = lineEnd - 1;+ } else {+ output += char;+ wordStart = /[\s;&|()<>]/u.test(char);+ }+ }+ return output;+}+function renderShellCommand(code) {code.children = shellCommandSegments(nodeText(code)).map(({ text: value, tone }) => tone? {@@ -558,7 +596,9 @@ export function pluginWorktrunkTerminal() {// each command line gets its own control in place of the block's.if (className === 'wt-command' && terminal.commandLines.size > 1) {renderData.lineAst.children ??= [];- renderData.lineAst.children.push(copyControl(text, 'wt-line-copy'));+ renderData.lineAst.children.push(+ copyControl(withoutTrailingShellComments(text), 'wt-line-copy'),+ );}if (className === 'wt-output') {const rendered = terminal.recordedByLine.has(lineIndex)@@ -575,7 +615,12 @@ export function pluginWorktrunkTerminal() {return;}const terminal = terminalBlocks.get(codeBlock);- if (!terminal) return;+ if (!terminal) {+ if (codeBlock.language === 'bash' || codeBlock.language === 'sh') {+ setCopyText(renderData.blockAst, withoutTrailingShellComments(codeBlock.code).replaceAll('\n', '\u007f'));+ }+ return;+ }if (terminal.commandLines.size > 1) {addClass(renderData.blockAst, 'wt-line-copies');removeCopyControl(renderData.blockAst);@@ -586,10 +631,10 @@ export function pluginWorktrunkTerminal() {return;}const copyText = [...codeBlock.getLines()]- .filter((_, lineIndex) => (- terminal.commandLines.has(lineIndex) || terminal.copyableLines.has(lineIndex)- ))- .map((line) => line.text)+ .flatMap((line, lineIndex) => {+ if (terminal.commandLines.has(lineIndex)) return [withoutTrailingShellComments(line.text)];+ return terminal.copyableLines.has(lineIndex) ? [line.text] : [];+ }).join('\u007f');setCopyText(renderData.blockAst, copyText);},diff --git a/docs/tests/built-site.test.mjs b/docs/tests/built-site.test.mjsindex 92a084f60..6271fc801 100644--- a/docs/tests/built-site.test.mjs+++ b/docs/tests/built-site.test.mjs@@ -9,6 +9,8 @@ import {syncTocCurrentToHash,} from '../src/components/toc-scroll.mjs';+import { withoutTrailingShellComments } from '../src/plugins/worktrunk-terminal.mjs';+const docsRoot = fileURLToPath(new URL('..', import.meta.url));const dist = path.join(docsRoot, 'dist');const publicRoutes = [@@ -388,7 +390,10 @@ test('command-bearing console blocks emit command-only copy payloads', async ())];const expected = lines.filter((line) => line[1] !== 'output')- .map((line) => renderedText(line[2]).replace(/\n$/u, ''));+ .map((line) => {+ const text = renderedText(line[2]).replace(/\n$/u, '');+ return line[1] === 'command' ? withoutTrailingShellComments(text) : text;+ });if (expected.length === 0) continue;commandBearingBlocks += 1;@@ -399,7 +404,7 @@ test('command-bearing console blocks emit command-only copy payloads', async ())?.[1];const commands = lines.filter((line) => line[1] === 'command')- .map((line) => renderedText(line[2]).replace(/\n$/u, ''));+ .map((line) => withoutTrailingShellComments(renderedText(line[2]).replace(/\n$/u, '')));const perLine = [...frame.matchAll(/<div class="copy wt-line-copy">[\s\S]*?<button\b[^>]*\bdata-code="([^"]*)"/g,)].map((line) => renderedText(line[1]));@@ -420,6 +425,22 @@ test('command-bearing console blocks emit command-only copy payloads', async ()assert.ok(perLineBlocks > 0, 'expected blocks listing several commands');});+test('shell copy payloads leave out trailing comments', async () => {+ let payloads = 0;+ for (const page of renderedPages) {+ const html = await readFile(page, 'utf8');+ for (const match of html.matchAll(/<figure class="frame[^"]*">([\s\S]*?)<\/figure>/g)) {+ if (!/<pre\b[^>]*\bdata-language="(?:bash|sh)"/.test(match[1])) continue;+ for (const button of match[1].matchAll(/<button\b[^>]*\bdata-code="([^"]*)"/g)) {+ payloads += 1;+ const code = renderedText(button[1]).replaceAll('\u007f', '\n');+ assert.equal(code, withoutTrailingShellComments(code), `${page} copies a trailing shell comment`);+ }+ }+ }+ assert.ok(payloads > 0, 'expected shell copy payloads');+});+test('generated command references expose no copy control', async () => {let references = 0;for (const page of renderedPages) {diff --git a/docs/tests/plugins.test.mjs b/docs/tests/plugins.test.mjsindex bf44a56be..d1e48f83e 100644--- a/docs/tests/plugins.test.mjs+++ b/docs/tests/plugins.test.mjs@@ -13,6 +13,7 @@ import {rehypeComparisonCommands,semanticOutputSegments,shellCommandSegments,+ withoutTrailingShellComments,} from '../src/plugins/worktrunk-terminal.mjs';function prepareCodeBlock(plugin, codeBlock) {@@ -365,6 +366,25 @@ test('shell command roles preserve syntax outside the styled grammar', () => {assert.equal(shellCommandSegments(source).map(({ text }) => text).join(''), source);});+test('copied shell commands leave out trailing comments', () => {+ assert.equal(withoutTrailingShellComments('wt switch - # Previous worktree'), 'wt switch -');+ assert.equal(withoutTrailingShellComments('wt list;# after an operator'), 'wt list;');+ assert.equal(withoutTrailingShellComments('echo a\\ #b'), 'echo a\\ #b');+ assert.equal(+ withoutTrailingShellComments(`git config k '{"a":"#b"}' "c # d" # Direct`),+ `git config k '{"a":"#b"}' "c # d"`,+ );+ assert.equal(withoutTrailingShellComments('echo $# ${#x} a#b \\#c'), 'echo $# ${#x} a#b \\#c');+ assert.equal(+ withoutTrailingShellComments('# Install\nbrew install wt # the CLI\n'),+ '# Install\nbrew install wt\n',+ );+ assert.equal(+ withoutTrailingShellComments("sh -c 'a\n# quoted' # comment"),+ "sh -c 'a\n# quoted'",+ );+});+test('console blocks give each of several commands its own copy control', () => {const lines = ['# Recent', '$ wt list', '', '# Failed', '$ wt list --full'].map((text) => ({text,@@ -428,7 +448,7 @@ test('console blocks wrap several commands but never captured output', () => {});test('console output and its blank lines stay out of copied commands', () => {- const lines = ['$ wt list', 'output', '', '# shell comment'].map((text) => ({+ const lines = ['$ wt list # recent', 'output', '', '# shell comment'].map((text) => ({text,editText(start, end, replacement) {this.text = this.text.slice(0, start) + replacement + this.text.slice(end);