import type { ElementNode, Node } from "comark"; import { lines, pair, props, MAX_CELLS, type Data, type DiffRow, type Issue } from "./read.ts"; import { isGenerated, languageOf, readUnified, type FileStatus } from "./unified.ts"; import { childrenOf, isElement } from "../../../shared/nodes.ts"; import { text } from "../../../shared/text.ts"; /** A changed line, or the `@@` line that starts a hunk. */ export type PullRow = | DiffRow | { kind: "hunk"; old: number; new: number; oldLines: number; newLines: number; context: string }; export interface PullFile { path: string; from?: string; status: FileStatus; binary: boolean; /** A lockfile, a build, or a minified file: its diff starts closed. */ generated: boolean; /** The file's fragment suffix within its pull. */ id: string; added: number; removed: number; rows: PullRow[]; /** Its code block's `class` and `style`, which carry Shiki's theme. */ code: { class?: string; style?: string }; } export interface PullScope { title?: string; /** What the scope's author wrote beside its diff, rendered above its files. */ summary: Node[]; files: PullFile[]; } export interface Pull { title?: string; href?: string; open: boolean; scopes: PullScope[]; files: number; added: number; removed: number; } /** The word a file fence carries its hunks in, so the renderer can put each line back in its hunk. */ const META = "cd-pull"; type Encoded = { path: string; from?: string; status: FileStatus; binary: boolean; hunks: { old: number; new: number; context: string; kinds: string }[]; }; // `path|from|status|binary|old,new,kinds,context;…`, each text part URI-encoded so it holds no `|`, `,`, `;`, or `"`. const encode = (file: Encoded) => [ encodeURIComponent(file.path), encodeURIComponent(file.from ?? ""), file.status, file.binary ? "1" : "", file.hunks .map((hunk) => `${hunk.old},${hunk.new},${hunk.kinds},${encodeURIComponent(hunk.context)}`) .join(";"), ].join("|"); const STATUSES = new Map( (["added", "deleted", "renamed", "modified"] as const).map((status) => [status, status]), ); const ENCODED = /^([^|]+)\|([^|]*)\|(\w+)\|(1?)\|((?:\d+,\d+,[sda]*,[^,;|]*)(?:;\d+,\d+,[sda]*,[^,;|]*)*|)$/; function decodeText(source: string): Encoded | undefined { const match = ENCODED.exec(source); const status = match && STATUSES.get(match[3]!); if (!match || !status) return; try { return { path: decodeURIComponent(match[1]!), from: match[2] ? decodeURIComponent(match[2]) : undefined, status, binary: match[4] === "1", hunks: match[5] ? match[5].split(";").map((part) => { const [old, next, kinds, context] = part.split(","); return { old: Number(old), new: Number(next), kinds: kinds!, context: decodeURIComponent(context!), }; }) : [], }; } catch { // A hand-written word with a broken escape isn't one `splitFences` wrote. return undefined; } } type Token = { type: string; tag: string; info: string; content: string; nesting: number }; /** * Turns each ```diff fence inside a `::pull` into one fence per file, in that file's language with git's signs taken * off, so Shiki highlights it like the file itself. Runs before any plugin's `post`. */ export function splitFences(tokens: Token[]) { let depth = 0; for (let at = 0; at < tokens.length; at++) { const token = tokens[at]!; if (token.type === "mdc_block_open" && token.tag === "pull") depth++; else if (token.type === "mdc_block_close" && token.tag === "pull") depth--; if (!depth || token.type !== "fence" || !/^(?:diff|patch)(?:\s|$)/i.test(token.info.trim())) continue; const files = readUnified(token.content); if (!files.length) continue; const fences = files.map((file) => { // SAFETY: a copy of a markdown-it token, made from its own prototype, is a token with the same fields. return Object.assign(Object.create(Object.getPrototypeOf(token)) as Token, token, { info: `${languageOf(file.path)} ${META}="${encode(file)}"`, content: file.code.join("\n") + "\n", }); }); tokens.splice(at, 1, ...fences); at += fences.length - 1; } } function decode(pre: ElementNode) { const match = new RegExp(`(?:^|\\s)${META}="([^"]*)"`).exec(text(pre[1].meta)); return match ? decodeText(match[1]!) : undefined; } // A code block that isn't a diff's file is reported and left out, rather than shown as the scope's summary. const isCode = (node: Node) => isElement(node) && node[0] === "pre"; const fileOf = (node: Node) => isElement(node) && node[0] === "pre" && decode(node) !== undefined ? node : undefined; const isFile = (node: Node) => fileOf(node) !== undefined; function readFile(pre: ElementNode, budget: { cells: number }, index: number): PullFile { // SAFETY: `fileOf` only passes a block `decode` reads. const encoded = decode(pre)!; const code = lines(pre); const rows: PullRow[] = []; let at = 0; let added = 0; let removed = 0; for (const { old, new: next, context, kinds } of encoded.hunks) { rows.push({ kind: "hunk", old, new: next, oldLines: kinds.replaceAll("a", "").length, newLines: kinds.replaceAll("d", "").length, context, }); let before = old; let after = next; let dels: DiffRow[] = []; let adds: DiffRow[] = []; const flush = () => { for (let k = 0; k < Math.min(dels.length, adds.length); k++) pair(dels[k]!, adds[k]!, budget); // One push per row: spreading a lockfile's thousands of lines passes more arguments than the engine allows. for (const row of [dels, adds].flat()) rows.push(row); dels = []; adds = []; }; for (const kind of kinds) { // Comark drops a fence's last line when it's empty, so a missing line is a blank one. const nodes = code[at++] ?? []; if (kind === "d") { dels.push({ kind: "del", old: before++, nodes, highlight: false }); removed++; } else if (kind === "a") { adds.push({ kind: "add", new: after++, nodes, highlight: false }); added++; } else { flush(); rows.push({ kind: "same", old: before++, new: after++, nodes, highlight: false }); } } flush(); } return { path: encoded.path, from: encoded.from, status: encoded.status, binary: encoded.binary, generated: isGenerated(encoded.path), id: `file${index}`, added, removed, rows, code: { class: text(pre[1].class) || undefined, style: text(pre[1].style) || undefined }, }; } /** Reads a `::pull` node: its scopes, each with its summary and the files its diff changes. */ export function readPull(node: ElementNode, data: Data): Pull { const attrs = props(node, data); const budget = { cells: MAX_CELLS }; const scopes: PullScope[] = []; let nextFile = 0; let loose: PullScope | undefined; let file: ElementNode | undefined; for (const child of childrenOf(node)) { if (isElement(child) && child[0] === "scope") { loose = undefined; const content = childrenOf(child); scopes.push({ title: text(props(child, data).title) || undefined, summary: content.filter((each) => !isCode(each) && (isElement(each) || text(each))), files: content .map(fileOf) .filter((pre) => pre !== undefined) .map((pre) => readFile(pre, budget, ++nextFile)), }); } else if ((file = fileOf(child))) { if (!loose) scopes.push((loose = { summary: [], files: [] })); loose.files.push(readFile(file, budget, ++nextFile)); } else if (!isCode(child) && (isElement(child) || text(child))) { if (!loose) scopes.push((loose = { summary: [], files: [] })); loose.summary.push(child); } } const files = scopes.flatMap((scope) => scope.files); const open = attrs.open; return { title: text(attrs.title) || undefined, href: /^https?:\/\//i.test(text(attrs.href)) ? text(attrs.href) : undefined, open: open === true || open === "" || open === "true", scopes, files: files.length, added: files.reduce((sum, file) => sum + file.added, 0), removed: files.reduce((sum, file) => sum + file.removed, 0), }; } const PULL_PROPS = ["title", "href", "open"]; const SCOPE_PROPS = ["title"]; const NATIVE = /^(?:id|class|style|data-.+|aria-.+)$/i; function unknown(node: ElementNode, valid: string[], block: string, issues: Issue[]) { for (const key of Object.keys(node[1])) { const name = key.replace(/^:/, ""); if (name === "$" || NATIVE.test(name) || valid.includes(name)) continue; issues.push({ rule: "comark/diff/pull-unknown-prop", message: `${block}: \`${name}\` isn't a valid prop. Valid props: ${valid.join(", ")}.`, }); } } /** Every problem in a document's pulls and scopes. */ export function checkPulls(nodes: Node[], issues: Issue[]) { let pulls = 0; let scopes = 0; const checkFences = (nodes: Node[], block: string) => { for (const pre of nodes) if (isElement(pre) && pre[0] === "pre" && !isFile(pre)) issues.push({ rule: "comark/diff/pull-unreadable-diff", message: `${block}: a ${text(pre[1].language) ? `\`\`\`${text(pre[1].language)}` : "code"} block isn't a git diff it can read. Paste \`git diff\` output, with its \`diff --git\` and \`@@\` lines, into a \`\`\`diff fence.`, }); }; const walk = (nodes: Node[], inside = false, parent?: string) => { for (const node of nodes) { if (!isElement(node)) continue; const tag = node[0]; const children = childrenOf(node); if (tag === "pull") { const block = `\`::pull\` ${++pulls}`; unknown(node, PULL_PROPS, block, issues); checkFences(children, block); if ( !children.some( (child) => fileOf(child) || (isElement(child) && child[0] === "scope" && childrenOf(child).some(fileOf)), ) ) issues.push({ rule: "comark/diff/pull-missing-diff", message: `${block} has no changes to show. Paste the output of \`git diff\` into a \`\`\`diff fence inside it.`, }); } else if (tag === "scope") { const block = `\`:::scope\` ${++scopes}`; if (!inside) issues.push({ rule: "comark/diff/scope-outside-pull", message: `${block} sits outside a \`::pull\`, so nothing draws it. Put it inside the \`::pull\` whose changes it groups.`, }); if (parent === "pull") { unknown(node, SCOPE_PROPS, block, issues); if (!text(node[1].title) && !node[1][":title"]) issues.push({ rule: "comark/diff/scope-missing-title", message: `${block} has no title, so the reader can't tell what its files do together. Name it, like \`:::scope{title="Retry failed uploads"}\`.`, }); checkFences(children, block); } } walk(children, inside || tag === "pull", tag); } }; walk(nodes); return issues; }