Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/prd.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,13 @@ export function regenerateIndex(root = process.cwd()) {
? ["| # | Title | Status |", "|---|---|---|",
...prds.map((p) => `| [${p.id}](${p.file}) | ${p.title} | ${p.status} |`)].join("\n")
: "_No PRDs yet._";
// Use a function replacement so `$`-sequences in a PRD title (e.g. `$&`, `$1`,
// `$\`` ) are inserted verbatim instead of being read as String.replace special
// patterns, which would otherwise splice the match back in and corrupt the index.
const block = `${INDEX_START}\n${rows}\n${INDEX_END}`;
const next = body.replace(
new RegExp(`${INDEX_START}[\\s\\S]*${INDEX_END}`),
`${INDEX_START}\n${rows}\n${INDEX_END}`,
() => block,
);
if (next === body) return false;
fs.writeFileSync(readme, next);
Expand Down
28 changes: 27 additions & 1 deletion test/prd.test.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import assert from "node:assert/strict";
import test from "node:test";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

import { renderPrd } from "../src/prd.mjs";
import { createPrd, renderPrd } from "../src/prd.mjs";

test("renderPrd quotes titles so YAML metacharacters stay valid", () => {
const body = renderPrd({
Expand All @@ -13,3 +16,26 @@ test("renderPrd quotes titles so YAML metacharacters stay valid", () => {

assert.match(body, /^title: "Ship CLI: handle \\"quoted\\" flags"$/m);
});


test("regenerateIndex keeps the README intact when a title holds a String.replace pattern", () => {
// `$&`, `$\``, `$'`, `$$` are special in a String.replace *replacement string*.
// A PRD title carrying one must not splice the old index block back into itself.
const root = fs.mkdtempSync(path.join(os.tmpdir(), "moshcode-prd-"));
try {
createPrd("Add $& live support", root);
createPrd("Improve docs", root);

const readme = fs.readFileSync(path.join(root, "prd", "README.md"), "utf8");
const starts = (readme.match(/PRD-INDEX:START/g) || []).length;
const ends = (readme.match(/PRD-INDEX:END/g) || []).length;

assert.equal(starts, 1, "index start marker must appear exactly once");
assert.equal(ends, 1, "index end marker must appear exactly once");
// The literal title text survives; it is not expanded into the match.
assert.match(readme, /\$& live support/);
assert.match(readme, /Improve docs/);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
Loading