diff --git a/src/article-api/lib/graphql-helpers.ts b/src/article-api/lib/graphql-helpers.ts index 6db482d7ff06..2799514f1028 100644 --- a/src/article-api/lib/graphql-helpers.ts +++ b/src/article-api/lib/graphql-helpers.ts @@ -1,6 +1,5 @@ import type { Context, Page } from '@/types' import { renderContent } from '@/content-render/index' -import matter from '@gr2m/gray-matter' /** * Extract manual content from page markdown @@ -15,14 +14,7 @@ export async function extractManualContent(page: Page, context: Context): Promis if (markerIndex <= 0) return '' - const { content } = matter(page.markdown) - const manualContentMarkerIndex = content.indexOf( - '', - ) - - if (manualContentMarkerIndex <= 0) return '' - - const rawManualContent = content.substring(0, manualContentMarkerIndex).trim() + const rawManualContent = page.markdown.substring(0, markerIndex).trim() if (!rawManualContent) return '' return await renderContent(rawManualContent, { diff --git a/src/article-api/transformers/audit-logs-transformer.ts b/src/article-api/transformers/audit-logs-transformer.ts index 4d04976aeb3d..5125e65b62ed 100644 --- a/src/article-api/transformers/audit-logs-transformer.ts +++ b/src/article-api/transformers/audit-logs-transformer.ts @@ -3,7 +3,6 @@ import type { PageTransformer } from './types' import type { CategorizedEvents } from '@/audit-logs/types' import { renderContent } from '@/content-render/index' import { loadTemplate } from '@/article-api/lib/load-template' -import matter from '@gr2m/gray-matter' /** * Transformer for Audit Logs pages @@ -46,18 +45,12 @@ export class AuditLogsTransformer implements PageTransformer { '', ) if (markerIndex > 0) { - const { content } = matter(page.markdown) - const manualContentMarkerIndex = content.indexOf( - '', - ) - if (manualContentMarkerIndex > 0) { - const rawManualContent = content.substring(0, manualContentMarkerIndex).trim() - if (rawManualContent) { - manualContent = await renderContent(rawManualContent, { - ...context, - markdownRequested: true, - }) - } + const rawManualContent = page.markdown.substring(0, markerIndex).trim() + if (rawManualContent) { + manualContent = await renderContent(rawManualContent, { + ...context, + markdownRequested: true, + }) } } } diff --git a/src/article-api/transformers/github-apps-transformer.ts b/src/article-api/transformers/github-apps-transformer.ts index 72cecd46999b..6e6f7aa46bcf 100644 --- a/src/article-api/transformers/github-apps-transformer.ts +++ b/src/article-api/transformers/github-apps-transformer.ts @@ -2,7 +2,6 @@ import type { Context, Page } from '@/types' import type { PageTransformer } from './types' import { renderContent } from '@/content-render/index' import { loadTemplate } from '@/article-api/lib/load-template' -import matter from '@gr2m/gray-matter' const DEBUG = process.env.RUNNER_DEBUG === '1' || process.env.DEBUG === '1' @@ -131,7 +130,7 @@ export class GithubAppsTransformer implements PageTransformer { // Prepare manual content let manualContent = '' if (page.markdown) { - const { content } = matter(page.markdown) + const content = page.markdown // GitHub Apps pages don't have the automated marker, so we render all markdown content if (content.trim()) { manualContent = await renderContent(content, { diff --git a/src/article-api/transformers/rest-transformer.ts b/src/article-api/transformers/rest-transformer.ts index 2b9e328e2dd6..5eb75625e658 100644 --- a/src/article-api/transformers/rest-transformer.ts +++ b/src/article-api/transformers/rest-transformer.ts @@ -6,7 +6,6 @@ import { engine } from '@/content-render/liquid/engine' import { apiTransformerTags } from '@/article-api/liquid-renderers' import { loadTemplate } from '@/article-api/lib/load-template' import { summarizeSchema } from '@/article-api/lib/summarize-schema' -import matter from '@gr2m/gray-matter' import { fastTextOnly } from '@/content-render/unified/text-only' import GithubSlugger from 'github-slugger' @@ -86,18 +85,12 @@ export class RestTransformer implements PageTransformer { '', ) if (markerIndex > 0) { - const { content } = matter(page.markdown) - const manualContentMarkerIndex = content.indexOf( - '', - ) - if (manualContentMarkerIndex > 0) { - const rawManualContent = content.substring(0, manualContentMarkerIndex).trim() - if (rawManualContent) { - manualContent = await renderContent(rawManualContent, { - ...context, - markdownRequested: true, - }) - } + const rawManualContent = page.markdown.substring(0, markerIndex).trim() + if (rawManualContent) { + manualContent = await renderContent(rawManualContent, { + ...context, + markdownRequested: true, + }) } } } diff --git a/src/article-api/transformers/webhooks-transformer.ts b/src/article-api/transformers/webhooks-transformer.ts index ba2a4c623bd5..674fdfcec97f 100644 --- a/src/article-api/transformers/webhooks-transformer.ts +++ b/src/article-api/transformers/webhooks-transformer.ts @@ -3,7 +3,6 @@ import type { PageTransformer } from './types' import { renderContent } from '@/content-render/index' import { fastTextOnly } from '@/content-render/unified/text-only' import { loadTemplate } from '@/article-api/lib/load-template' -import matter from '@gr2m/gray-matter' /** * Transformer for Webhooks pages. @@ -32,7 +31,7 @@ export class WebhooksTransformer implements PageTransformer { // Prepare manual content let manualContent = '' if (page.markdown) { - const { content } = matter(page.markdown) + const content = page.markdown const markerIndex = content.indexOf( '', ) diff --git a/src/content-linter/lib/helpers/utils.ts b/src/content-linter/lib/helpers/utils.ts index 3e4d478542e1..1863b46e4b44 100644 --- a/src/content-linter/lib/helpers/utils.ts +++ b/src/content-linter/lib/helpers/utils.ts @@ -1,7 +1,7 @@ import { addError, filterTokens } from 'markdownlint-rule-helpers' -import matter from '@gr2m/gray-matter' import type { RuleParams, RuleErrorCallback, MarkdownToken } from '@/content-linter/types' +import { parseYamlFrontmatter } from '@/frame/lib/parse-yaml-frontmatter' // Adds an error object with details conditionally via the onError callback export function addFixErrorDetail( @@ -147,10 +147,10 @@ export const docsDomains = ['docs.github.com', 'help.github.com', 'developer.git // Returns frontmatter as a Record with unknown values since YAML can contain various types export function getFrontmatter(lines: string[]): Record | null { const fmString = lines.join('\n') - const { data } = matter(fmString) + const { data } = parseYamlFrontmatter(fmString) // If there is no frontmatter or the frontmatter contains - // no keys, matter will return an empty object. - if (Object.keys(data).length === 0) return null + // no keys, the parser will return an empty object. + if (data == null || Object.keys(data).length === 0) return null return data } diff --git a/src/content-render/scripts/move-by-content-type.ts b/src/content-render/scripts/move-by-content-type.ts index c64ef0ed27fc..dc4eaf4440e3 100644 --- a/src/content-render/scripts/move-by-content-type.ts +++ b/src/content-render/scripts/move-by-content-type.ts @@ -4,6 +4,7 @@ */ import { program } from 'commander' +import { constants } from 'fs' import fs from 'fs/promises' import path from 'path' import chalk from 'chalk' @@ -25,6 +26,32 @@ const contentTypeToDir = (contentType: string): string => { } const validContentTypeDirs = new Set(CONTENT_TYPES.map(contentTypeToDir)) +const contentRoot = path.resolve('content') + +// The move helper also updates links in other products. Check the entire tree +// before any migration writes, including when the user selects only one file. +async function checkContentTree() { + if (!(await fs.lstat(contentRoot)).isDirectory()) { + throw new Error('Expected content to be a directory, not a symbolic link') + } + const entries = await fs.readdir(contentRoot, { recursive: true, withFileTypes: true }) + const link = entries.find((entry) => entry.isSymbolicLink()) + if (link) { + throw new Error(`Symbolic links are not supported: ${path.join(link.parentPath, link.name)}`) + } +} + +function resolveContentPath(input: string): string { + const absolutePath = path.resolve(input) + const relative = path.relative(contentRoot, absolutePath) + if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) { + throw new Error(`Expected a path inside content: ${input}`) + } + return absolutePath +} + +// Rewrites should neither create a missing index nor follow a replacement link. +const indexWriteFlags = constants.O_WRONLY | constants.O_TRUNC | (constants.O_NOFOLLOW ?? 0) // Helper: Should we skip this index.md file from processing? function shouldSkipIndexFile(filePath: string): boolean { @@ -80,18 +107,41 @@ interface FileMove { contentType: string } +// Only remove directories. A skipped or unselected file must survive cleanup. +async function removeEmptyDirectoryTree(dir: string): Promise { + for (const entry of await fs.readdir(dir, { withFileTypes: true })) { + if (entry.isDirectory()) await removeEmptyDirectoryTree(path.join(dir, entry.name)) + } + + try { + await fs.rmdir(dir) + return true + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOTEMPTY') return false + throw error + } +} + program .name('content-type-based-move') .description('Reorganize content files into subdirectories based on their contentType property') .argument('[paths...]', 'Content paths to process') .action(async (paths: string[]) => { + const inputPaths = paths.map(resolveContentPath) + // Run in a checkout without concurrent writers; Node's path-based + // operations and the child scripts cannot pin directory ancestors. + await checkContentTree() + // ==================== // 1. GATHER FILES // ==================== const filesToProcess: string[] = [] - if (paths?.length > 0) { - for (const p of paths) { + const requestedProducts = new Set() + if (inputPaths.length > 0) { + for (const p of inputPaths) { const stats = await fs.stat(p) + const [product, child] = path.relative(contentRoot, p).split(path.sep) + if (product && (stats.isDirectory() || child)) requestedProducts.add(product) if (stats.isDirectory()) { filesToProcess.push(...(await walkFiles(p, ['.md']))) } else if (p.endsWith('.md')) { @@ -99,7 +149,7 @@ program } } } else { - filesToProcess.push(...(await walkFiles(path.join(process.cwd(), 'content'), ['.md']))) + filesToProcess.push(...(await walkFiles(contentRoot, ['.md']))) } console.log(chalk.white(`Processing ${filesToProcess.length} files...\n`)) @@ -127,7 +177,8 @@ program // Read and validate contentType const fileContent = await fs.readFile(filePath, 'utf-8') - const { data } = readFrontmatter(fileContent) + const { data, errors } = readFrontmatter(fileContent) + if (!data && errors.length) throw new Error(errors[0].reason) if (!data?.contentType) { skipped.push({ file: relativePath, reason: 'No contentType property found' }) @@ -155,7 +206,7 @@ program } // Get product directory - if (contentIndex === -1 || contentIndex + 1 >= parts.length) { + if (contentIndex === -1 || contentIndex + 2 >= parts.length) { console.log( chalk.yellow(`⚠ Skipping ${relativePath}: Cannot determine product directory`), ) @@ -215,24 +266,12 @@ program console.log(chalk.white('Ensuring standard content-type directories exist...\n')) // Add standard content-type directories for each affected product - if (paths?.length > 0) { - for (const p of paths) { - const fullPath = path.resolve(process.cwd(), p) - const relativePath = path.relative(process.cwd(), fullPath) - const parts = relativePath.split(path.sep) - const contentIndex = parts.indexOf('content') - - if (contentIndex !== -1 && contentIndex + 1 < parts.length) { - const productName = parts[contentIndex + 1] - - for (const ct of CONTENT_TYPES.filter((t) => t !== 'rai' && t !== 'landing')) { - targetDirs.add(path.join('content', productName, contentTypeToDir(ct))) - } - - if (productsWithRai.has(productName)) { - targetDirs.add(path.join('content', productName, 'responsible-use')) - } - } + for (const productName of requestedProducts) { + for (const ct of CONTENT_TYPES.filter((t) => t !== 'rai' && t !== 'landing')) { + targetDirs.add(path.join('content', productName, contentTypeToDir(ct))) + } + if (productsWithRai.has(productName)) { + targetDirs.add(path.join('content', productName, 'responsible-use')) } } @@ -288,7 +327,7 @@ contentType: ${placeholderContentType} ` await fs.mkdir(absoluteDirPath, { recursive: true }) - await fs.writeFile(indexPath, content, 'utf-8') + await fs.writeFile(indexPath, content, { flag: 'wx' }) newPlaceholders.push(indexPath) console.log(chalk.green(`✓ Created ${dirPath}/index.md`)) @@ -368,15 +407,14 @@ contentType: ${placeholderContentType} await fs.mkdir(file.targetDir, { recursive: true }) const content = await fs.readFile(file.filePath, 'utf-8') - const { data, content: body } = readFrontmatter(content) + const { data, content: body, errors } = readFrontmatter(content) + if (!data && errors.length) throw new Error(errors[0].reason) // Clear children array because paths will be invalid in the new content-type directory structure if (data?.children) data.children = [] - await fs.writeFile( - file.targetPath, - readFrontmatter.stringify(body || '', data || {}), - 'utf-8', - ) + await fs.writeFile(file.targetPath, readFrontmatter.stringify(body || '', data || {}), { + flag: 'wx', + }) indexFilesToDeleteLater.push(file.filePath) moved.push({ @@ -410,6 +448,7 @@ contentType: ${placeholderContentType} ['run', 'move-content', '--', relativeFilePath, relativeTargetPath, '--no-git'], { cwd: process.cwd(), + env: { ...process.env, ROOT: '.' }, stdio: 'inherit', }, ) @@ -473,6 +512,7 @@ contentType: ${placeholderContentType} for (const productDir of productDirs) { const productName = path.basename(productDir) + const retainedDirs = new Set() try { const entries = await fs.readdir(productDir, { withFileTypes: true }) @@ -482,7 +522,15 @@ contentType: ${placeholderContentType} const oldDirPath = path.join(productDir, entry.name) try { - await fs.rm(oldDirPath, { recursive: true, force: true }) + if (!(await removeEmptyDirectoryTree(oldDirPath))) { + retainedDirs.add(entry.name) + console.log( + chalk.yellow( + `⚠ Keeping ${path.relative(process.cwd(), oldDirPath)}: files remain`, + ), + ) + continue + } console.log( chalk.gray(`✓ Deleted old directory: ${path.relative(process.cwd(), oldDirPath)}`), ) @@ -490,6 +538,7 @@ contentType: ${placeholderContentType} if (!deletedByProduct.has(productName)) deletedByProduct.set(productName, []) deletedByProduct.get(productName)!.push(`/${productName}/${entry.name}`) } catch (error) { + retainedDirs.add(entry.name) console.log(chalk.yellow(`⚠ Could not delete ${oldDirPath}: ${error}`)) } } @@ -516,6 +565,13 @@ contentType: ${placeholderContentType} } if (newChildren.length > 0) { + if (Array.isArray(data.children)) { + for (const child of data.children) { + if (typeof child === 'string' && retainedDirs.has(child.split('/')[1])) { + newChildren.push(child) + } + } + } data.children = newChildren updated = true } @@ -535,7 +591,9 @@ contentType: ${placeholderContentType} } if (updated) { - await fs.writeFile(productIndexPath, readFrontmatter.stringify(body, data), 'utf-8') + await fs.writeFile(productIndexPath, readFrontmatter.stringify(body, data), { + flag: indexWriteFlags, + }) const changes = [] if (newChildren.length > 0) changes.push(`${newChildren.length} children`) if (deletedPaths.length > 0) changes.push(`${deletedPaths.length} redirects`) @@ -576,7 +634,9 @@ contentType: ${placeholderContentType} if (subdirs.length > 0) { data.children = subdirs - await fs.writeFile(indexPath, readFrontmatter.stringify(body, data), 'utf-8') + await fs.writeFile(indexPath, readFrontmatter.stringify(body, data), { + flag: indexWriteFlags, + }) console.log( chalk.green( `✓ Added children to ${path.relative(process.cwd(), indexPath)} (${subdirs.length} subdirectories)`, @@ -599,7 +659,9 @@ contentType: ${placeholderContentType} if (JSON.stringify(sorted) !== JSON.stringify(data.children)) { data.children = sorted - await fs.writeFile(indexPath, readFrontmatter.stringify(body, data), 'utf-8') + await fs.writeFile(indexPath, readFrontmatter.stringify(body, data), { + flag: indexWriteFlags, + }) console.log( chalk.green(`✓ Sorted children in ${path.relative(process.cwd(), indexPath)}`), ) @@ -639,4 +701,9 @@ contentType: ${placeholderContentType} } }) -program.parse() +try { + await program.parseAsync() +} catch (error) { + console.error(chalk.red(error instanceof Error ? error.message : String(error))) + process.exitCode = 1 +} diff --git a/src/content-render/tests/move-by-content-type.ts b/src/content-render/tests/move-by-content-type.ts new file mode 100644 index 000000000000..0341c7da9db0 --- /dev/null +++ b/src/content-render/tests/move-by-content-type.ts @@ -0,0 +1,124 @@ +import { spawnSync } from 'node:child_process' +import fs from 'node:fs' +import { createRequire } from 'node:module' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, expect, test } from 'vitest' + +import readFrontmatter from '@/frame/lib/read-frontmatter' + +const repo = fileURLToPath(new URL('../../../', import.meta.url)) +const tsx = createRequire(import.meta.url).resolve('tsx/cli') +const script = path.join(repo, 'src/content-render/scripts/move-by-content-type.ts') +const tsconfig = path.join(repo, 'tsconfig.json') +const markdown = "---\ntitle: Example\nversions:\n fpt: '*'\n" +let cwd: string + +function write(file: string, content = `${markdown}---\n`) { + const dest = path.join(cwd, file) + fs.mkdirSync(path.dirname(dest), { recursive: true }) + fs.writeFileSync(dest, content) +} + +function run(...args: string[]) { + return spawnSync(process.execPath, [tsx, '--tsconfig', tsconfig, script, ...args], { + cwd, + env: { ...process.env, ROOT: cwd }, + encoding: 'utf8', + timeout: 15_000, + }) +} + +beforeEach(() => { + cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'move-by-content-type-')) + // The frontmatter module loads these files relative to the current directory. + for (const file of ['src/ghes-releases/lib/enterprise-dates.json', 'src/rest/lib/config.json']) { + write(file, fs.readFileSync(path.join(repo, file), 'utf8')) + } + fs.mkdirSync(path.join(cwd, 'data/features'), { recursive: true }) +}) + +afterEach(() => { + fs.rmSync(cwd, { recursive: true, force: true }) +}) + +test.each([ + 'content', + 'content/product', + 'content/product/index.md', + 'content/product/how-tos', + 'content/product/concepts/index.md', + 'content/another-product/nested/article.md', +])('rejects a symbolic link at %s before migration', (link) => { + const dest = path.join(cwd, link) + fs.mkdirSync(path.dirname(dest), { recursive: true }) + const directoryLink = !link.endsWith('.md') + // A dangling file link must be rejected too. + const target = path.join(cwd, directoryLink ? 'outside' : 'missing.md') + if (directoryLink) fs.mkdirSync(target) + fs.symlinkSync(target, dest, directoryLink ? 'junction' : 'file') + + const result = run('content/product') + expect(result.status).toBe(1) + expect(result.stderr).toMatch(/symbolic link/i) + expect(result.stdout).not.toContain('Processing') + if (directoryLink) expect(fs.readdirSync(target)).toEqual([]) + else expect(fs.existsSync(target)).toBe(false) +}) + +test('rejects inputs in a sibling directory whose name starts with content', () => { + write('content/index.md') + write('content-sibling/content/product/article.md') + + const result = run('content-sibling/content/product/article.md') + expect(result.status).toBe(1) + expect(result.stderr).toContain('Expected a path inside content') + expect(fs.readdirSync(path.join(cwd, 'content'))).toEqual(['index.md']) +}) + +test('updates metadata and cleans up legacy directories in a regular content tree', () => { + write('content/product/index.md', `${markdown}children:\n - /legacy\n---\n`) + write('content/product/concepts/article.md', `${markdown}contentType: concepts\n---\n`) + write('content/product/concepts/index.md', `${markdown}children:\n - /z\n - /about-a\n---\n`) + write('content/product/legacy/index.md', `${markdown}contentType: how-tos\n---\n`) + for (const type of ['get-started', 'how-tos', 'reference', 'tutorials']) { + write(`content/product/${type}/index.md`) + } + + const result = run('content/product') + expect(result.status, result.stderr).toBe(0) + expect(fs.existsSync(path.join(cwd, 'content/product/legacy'))).toBe(false) + const product = fs.readFileSync(path.join(cwd, 'content/product/index.md'), 'utf8') + expect(product).toContain(' - /concepts') + expect(product).toContain('redirect_from:\n - /product/legacy') + const concepts = fs.readFileSync(path.join(cwd, 'content/product/concepts/index.md'), 'utf8') + expect(concepts).toContain('children:\n - /about-a\n - /z') + expect(fs.existsSync(path.join(cwd, 'content/product/how-tos/legacy/index.md'))).toBe(true) +}) + +test('migration cleanup keeps rejected sources and removes fully migrated directory trees', () => { + const rejected = '---js\n{"title":"Rejected"}\n---\nBody\n' + const article = '---\ntitle: Migrate me\ncontentType: how-tos\n---\nArticle body\n' + const read = (file: string) => fs.readFileSync(path.join(cwd, 'content/demo', file), 'utf8') + + write('content/demo/index.md', '---\ntitle: Demo\nchildren: [/mixed, /complete]\n---\n') + for (const dir of ['get-started', 'concepts', 'how-tos', 'reference', 'tutorials']) { + write(`content/demo/${dir}/index.md`, '---\ntitle: Destination\n---\n') + } + write('content/demo/mixed/nested/rejected.md', rejected) + write('content/demo/mixed/index.md', article) + write('content/demo/complete/nested/index.md', article) + + const result = run('content/demo') + expect(result.status, result.stderr).toBe(0) + expect(result.stderr).toContain('expected a plain YAML frontmatter opening fence') + expect(read('mixed/nested/rejected.md')).toBe(rejected) + expect(read('how-tos/mixed/index.md')).toContain('Article body') + expect(read('how-tos/complete/nested/index.md')).toContain('Article body') + expect(() => read('complete')).toThrow(/ENOENT/) + expect(readFrontmatter(read('index.md')).data).toMatchObject({ + children: ['/get-started', '/concepts', '/how-tos', '/reference', '/tutorials', '/mixed'], + redirect_from: ['/demo/complete'], + }) +}, 20_000) diff --git a/src/data-directory/README.md b/src/data-directory/README.md index b57bb3388f01..393cedf62288 100644 --- a/src/data-directory/README.md +++ b/src/data-directory/README.md @@ -54,7 +54,13 @@ Purpose-built utilities, schemas, and workflows that power our Liquid `{% data % ## Data conventions and consumers - File locations: Everything under `data/` (English and localized mirrors). Reusables/variables/ui are read via dotted paths (`reusables.foo.bar`, `variables.product.prodname_ghe_server`, `ui.pages.home`). -- Markdown in data: Frontmatter is stripped by `gray-matter`; content is trimmed. + + + + +- Reusable Markdown in `get-data.ts`: The shared frontmatter parser reads plain YAML fences and accepts explicit YAML or JSON labels for reusables. It strips frontmatter once and trims trailing whitespace from the body. + + - Downstream consumers: - Liquid tags: `content-render/liquid/data.ts`, `indented-data-reference.ts` - Content linter: `content-linter/lib/linting-rules/liquid-data-tags.ts`, `frontmatter-intro-links.ts` diff --git a/src/data-directory/lib/data-directory.ts b/src/data-directory/lib/data-directory.ts index 58c9a655691f..7fc382a1468e 100644 --- a/src/data-directory/lib/data-directory.ts +++ b/src/data-directory/lib/data-directory.ts @@ -5,7 +5,7 @@ import walk from 'walk-sync' import yaml from 'js-yaml' import { isRegExp, setWith } from 'lodash-es' import filenameToKey from './filename-to-key' -import matter from '@gr2m/gray-matter' +import { parseYamlFrontmatter } from '@/frame/lib/parse-yaml-frontmatter' interface DataDirectoryOptions { preprocess?: (content: string) => string @@ -78,10 +78,10 @@ export default function dataDirectory( break case '.md': case '.markdown': - // Use `matter` to drop frontmatter, since localized reusable Markdown files + // Drop frontmatter, since localized reusable Markdown files // can potentially have frontmatter, but we want to prevent the frontmatter // from being rendered. - setWith(data, key, matter(processedContent).content, Object) + setWith(data, key, parseYamlFrontmatter(processedContent).content, Object) break } } diff --git a/src/data-directory/lib/get-data.ts b/src/data-directory/lib/get-data.ts index 94185c05bd55..bb6c2258f371 100644 --- a/src/data-directory/lib/get-data.ts +++ b/src/data-directory/lib/get-data.ts @@ -2,19 +2,15 @@ import fs from 'fs' import path from 'path' import yaml from 'js-yaml' -import matter from '@gr2m/gray-matter' import { merge, get } from 'lodash-es' +import { parseYamlFrontmatter } from '@/frame/lib/parse-yaml-frontmatter' import languages from '@/languages/lib/languages-server' import { correctTranslatedContentStrings } from '@/languages/lib/correct-translation-content' import { createLogger } from '@/observability/logger' const logger = createLogger(import.meta.url) -interface YAMLException extends Error { - mark?: any -} - interface FileSystemError extends Error { code?: string } @@ -124,20 +120,16 @@ export const getDataByLanguage = memoize((dottedPath: string, langCode: string): } return value } catch (error) { - if (error instanceof Error && (error as YAMLException).mark && error.message) { - // It's a yaml.load() generated error! - // Remember, the file that we read might have been a .yml or a .md - // file. If it was a .md file, with corrupt front-matter that too - // would have caused a YAMLException + if (error instanceof yaml.YAMLException) { + // Fall back when YAML data or Markdown frontmatter in a translation is invalid. if (langCode !== 'en') { if (DEBUG_JIT_DATA_READS) { - logger.warn('Unable to parse Yaml in translation', { langCode, dottedPath, error }) + logger.warn('Unable to parse data in translation', { langCode, dottedPath, error }) } // Give it one more chance, but use English this time return getDataByDir(dottedPath, languages.en.dir) } - // Always throw English Yaml reading errors. Staff writers - // need to know early and explicitly that they are corrupt. + // Surface invalid English data so writers can fix it. throw error } @@ -190,13 +182,13 @@ function getDataByDir( if (allData && key) { const value = allData[key] if (value) { - let content = matter(value).content + let content = parseYamlFrontmatter(value).content if (dir !== englishRoot) { let englishContent = content try { const englishData = getYamlContent(englishRoot, fullPath.join(path.sep), englishRoot) if (englishData?.[key]) { - englishContent = matter(englishData[key]).content + englishContent = parseYamlFrontmatter(englishData[key]).content } } catch (error) { if ((error as FileSystemError).code !== 'ENOENT') { @@ -220,8 +212,7 @@ function getDataByDir( const nakedname = split.pop()! fullPath.push(...split) fullPath.push(`${nakedname}.md`) - const markdown = getMarkdownContent(dir, fullPath.join(path.sep), englishRoot) - let { content } = matter(markdown) + let content = getMarkdownContent(dir, fullPath.join(path.sep), englishRoot) if (dir !== englishRoot) { // If we're reading a translation, we need to replace the possible // corruptions. For example `[AUTOTITLE"을](/foo/bar)`. @@ -340,7 +331,10 @@ const getMarkdownContent = memoize( } const fileContent = getFileContent(root, relPath, englishRoot) - return matter(fileContent).content.trimEnd() + return parseYamlFrontmatter(fileContent, { + allowFormatLabels: true, + filename: relPath, + }).content.trimEnd() }, ) diff --git a/src/data-directory/tests/get-data.ts b/src/data-directory/tests/get-data.ts index 976529411602..c49abdbf3dad 100644 --- a/src/data-directory/tests/get-data.ts +++ b/src/data-directory/tests/get-data.ts @@ -1,6 +1,7 @@ import fs from 'fs' import path from 'path' +import { YAMLException } from 'js-yaml' import { afterAll, beforeAll, describe, expect, test } from 'vitest' import languages from '@/languages/lib/languages-server' @@ -234,6 +235,10 @@ describe('get-data on corrupt translations', () => { }, reusables: { cool: VALID_ENGLISH_MARKDOWN, + unsupported: '\uFEFF--- Js \r\n---\r\nEnglish body', + body: '---json\n{"title":"Example"}\n---\n---\n\nReusable body\n', + labeledYaml: '---YML\r\ntitle: Example\r\n---\r\nReusable body\r\n', + invalidJson: '---json\ntitle: Example\n---\nReusable body\n', }, }, }) @@ -252,6 +257,7 @@ describe('get-data on corrupt translations', () => { }, reusables: { cool: VALID_JAPANESE_MARKDOWN, + body: '---javascript\n---\nTranslated body', }, }, }, @@ -295,6 +301,28 @@ describe('get-data on corrupt translations', () => { expect(result).toBe('*English* /Markdown/') } }) + + test('rejects an unsupported reusable frontmatter language after a BOM', () => { + expect(() => getDataByLanguage('reusables.unsupported', 'en')).toThrow( + 'Unsupported Markdown frontmatter language "Js"', + ) + }) + + test('preserves a Markdown rule at the start of the body after frontmatter', () => { + expect(getDataByLanguage('reusables.body', 'en')).toBe('---\n\nReusable body') + }) + + test('accepts a YAML alias on reusable frontmatter', () => { + expect(getDataByLanguage('reusables.labeledYaml', 'en')).toBe('Reusable body') + }) + + test('requires valid JSON when reusable frontmatter is labeled json', () => { + expect(() => getDataByLanguage('reusables.invalidJson', 'en')).toThrow(YAMLException) + }) + + test('falls back to English when a reusable translation selects an unsupported language', () => { + expect(getDataByLanguage('reusables.body', 'ja')).toBe('---\n\nReusable body') + }) }) describe('get-data applies corrections to translated variables', () => { diff --git a/src/frame/lib/parse-yaml-frontmatter.ts b/src/frame/lib/parse-yaml-frontmatter.ts new file mode 100644 index 000000000000..405162b31d40 --- /dev/null +++ b/src/frame/lib/parse-yaml-frontmatter.ts @@ -0,0 +1,54 @@ +import { load, YAMLException } from 'js-yaml' + +// Keep the existing frontmatter data type for callers with different schemas. +// The frame reader validates the parsed YAML values separately. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type FrontmatterData = Record + +export function parseYamlFrontmatter( + markdown: string, + { allowFormatLabels = false, filename }: { allowFormatLabels?: boolean; filename?: string } = {}, +): { + content: string + data: FrontmatterData +} { + const input = markdown.replace(/^\uFEFF/, '') + if (!input.startsWith('---') || input.startsWith('----')) { + return { content: input, data: {} } + } + + const openingFence = allowFormatLabels ? /^---([^\r\n]*)\r?\n/ : /^---([ \t]*)\r?\n/ + const opening = openingFence.exec(input) + if (!opening) throw new YAMLException('expected a plain YAML frontmatter opening fence') + + const label = opening[1].trim() + if (label) { + // Reusables support only these labels. Never look up a user-supplied parser. + if (label !== 'json' && !/^ya?ml$/i.test(label)) { + throw new YAMLException( + `Unsupported Markdown frontmatter language "${label}"${filename ? ` in ${filename}` : ''}`, + ) + } + } + + const rest = input.slice(opening[0].length) + const closing = /(?:^|\r?\n)---[ \t]*(?:\r?\n|$)/.exec(rest) + if (!closing) throw new YAMLException('missing YAML frontmatter closing fence') + + const yaml = rest.slice(0, closing.index) + const content = rest.slice(closing.index + closing[0].length) + if (label === 'json' && yaml.trim()) { + try { + return { content, data: JSON.parse(yaml) } + } catch (error) { + if (!(error instanceof SyntaxError)) throw error + throw new YAMLException(error.message) + } + } + // Preserve the empty object for whitespace and comments while letting schema + // validation see explicit non-object YAML values. + const data = yaml.replace(/^\s*#[^\n]*/gm, '').trim() + ? (load(yaml, { filename }) as FrontmatterData) + : {} + return { content, data } +} diff --git a/src/frame/lib/read-frontmatter.ts b/src/frame/lib/read-frontmatter.ts index ceb62c683102..496d5754a826 100644 --- a/src/frame/lib/read-frontmatter.ts +++ b/src/frame/lib/read-frontmatter.ts @@ -1,6 +1,7 @@ -import matter from '@gr2m/gray-matter' import type { SchemaObject, ErrorObject } from 'ajv' +import { dump, type DumpOptions } from 'js-yaml' +import { parseYamlFrontmatter } from '@/frame/lib/parse-yaml-frontmatter' import { validateJson } from '@/tests/lib/validate-json-schema' interface ReadFrontmatterOptions { @@ -23,7 +24,7 @@ function readFrontmatter(markdown: string, opts: ReadFrontmatterOptions = {}) { let data try { - ;({ content, data } = matter(markdown)) + ;({ content, data } = parseYamlFrontmatter(markdown)) } catch (e: unknown) { const defaultReason = 'invalid frontmatter entry' @@ -96,10 +97,12 @@ function readFrontmatter(markdown: string, opts: ReadFrontmatterOptions = {}) { return { content, data, errors } } -// Expose gray-matter's underlying stringify method for joining a parsed -// frontmatter object and a markdown string back into a unified string -// -// stringify('some string', {some: 'frontmatter'}) -readFrontmatter.stringify = matter.stringify +// Merge existing YAML frontmatter when a tooling caller supplies a full document. +readFrontmatter.stringify = (markdown: string, data: object, options?: DumpOptions) => { + const parsed = parseYamlFrontmatter(markdown) + const yaml = dump({ ...parsed.data, ...data }, options).trim() + const frontmatter = yaml === '{}' ? '' : `---\n${yaml}\n---\n` + return frontmatter + (parsed.content.endsWith('\n') ? parsed.content : `${parsed.content}\n`) +} export default readFrontmatter diff --git a/src/frame/tests/read-frontmatter.ts b/src/frame/tests/read-frontmatter.ts index 67217d45c81e..b177bcb0150c 100644 --- a/src/frame/tests/read-frontmatter.ts +++ b/src/frame/tests/read-frontmatter.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from 'vitest' import parse from '@/frame/lib/read-frontmatter' import { schema as frontmatterSchema } from '@/frame/lib/frontmatter' +import { getFrontmatter } from '@/content-linter/lib/helpers/utils' const filepath = 'path/to/file.md' const fixture1 = `--- @@ -28,9 +29,44 @@ describe('frontmatter', () => { expect(errors.length).toBe(0) }) + test('preserves Markdown after plain YAML with a BOM, CRLF, and fence whitespace', () => { + const markdown = '\uFEFF--- \r\ntitle: Example\r\n---\t\r\n\r\n---\r\nBody' + expect(parse(markdown)).toEqual({ + data: { title: 'Example' }, + content: '\r\n---\r\nBody', + errors: [], + }) + expect(getFrontmatter(markdown.split('\r\n'))).toEqual({ title: 'Example' }) + }) + + test.each(['javascript', 'js', ' JAVASCRIPT ', ' Js ', ' JS ', 'json', 'yaml', 'yml'])( + 'rejects a frontmatter fence labeled %j in both readers and the writer', + (label) => { + const markdown = `\uFEFF---${label}\r\n---\r\nBody` + const reason = 'expected a plain YAML frontmatter opening fence' + expect(parse(markdown, { filepath })).toEqual({ + errors: [{ filepath, message: 'YML parsing error!', reason }], + }) + expect(() => getFrontmatter(markdown.split('\r\n'))).toThrow(reason) + expect(() => parse.stringify(markdown, { title: 'Example' })).toThrow(reason) + }, + ) + + test('reports a missing closing fence', () => { + expect(parse('---\ntitle: Example').errors[0].reason).toBe( + 'missing YAML frontmatter closing fence', + ) + }) + describe('frontmatter.stringify', () => { - test('is exported', () => { - expect(typeof parse.stringify).toBe('function') + test('merges existing YAML frontmatter and keeps the Markdown body', () => { + const markdown = '---\ntitle: Original\nshortTitle: Short\n---\nBody' + const output = parse.stringify(markdown, { title: 'Updated' }) + expect(parse(output)).toEqual({ + content: 'Body\n', + data: { title: 'Updated', shortTitle: 'Short' }, + errors: [], + }) }) }) diff --git a/src/versions/scripts/update-versioning-in-files.ts b/src/versions/scripts/update-versioning-in-files.ts index 1edcfcc5e319..565f597b4739 100755 --- a/src/versions/scripts/update-versioning-in-files.ts +++ b/src/versions/scripts/update-versioning-in-files.ts @@ -56,7 +56,6 @@ for (const file of contentFiles) { } } - // @ts-expect-error lineWidth is a valid js-yaml option not included in gray-matter's type definitions fs.writeFileSync(file, frontmatter.stringify(newContent, data || {}, { lineWidth: 10000 })) } diff --git a/src/workflows/fm-utils.ts b/src/workflows/fm-utils.ts index fd0bac660613..926a6b289e71 100644 --- a/src/workflows/fm-utils.ts +++ b/src/workflows/fm-utils.ts @@ -1,5 +1,5 @@ import { readFileSync } from 'fs' -import matter from '@gr2m/gray-matter' +import { parseYamlFrontmatter } from '@/frame/lib/parse-yaml-frontmatter' // Filters out files from a list of filePaths // that have a contentType property in their frontmatter @@ -7,8 +7,8 @@ import matter from '@gr2m/gray-matter' export function checkContentType(filePaths: string[], contentType: string) { const unallowedChangedFiles = [] for (const filePath of filePaths) { - const { data } = matter(readFileSync(filePath, 'utf8')) - if (data.contentType === contentType) { + const { data } = parseYamlFrontmatter(readFileSync(filePath, 'utf8')) + if (data?.contentType === contentType) { unallowedChangedFiles.push(filePath) } } diff --git a/src/workflows/fr-add-docs-reviewers-requests.ts b/src/workflows/fr-add-docs-reviewers-requests.ts index 079831d4e474..8961edc68e7b 100644 --- a/src/workflows/fr-add-docs-reviewers-requests.ts +++ b/src/workflows/fr-add-docs-reviewers-requests.ts @@ -228,7 +228,7 @@ async function run() { // Populate fields for the new project items // (Using for...of instead of forEach since the function uses await) for (const [index, itemID] of newItemIDs.entries()) { - const updateProjectV2ItemMutation = generateUpdateProjectV2ItemFieldMutation({ + const { mutation, variables } = generateUpdateProjectV2ItemFieldMutation({ item: itemID, author: newItemAuthors[index], turnaround: 2, @@ -239,7 +239,8 @@ async function run() { : hubberTypeID console.log(`Populating fields for item: ${itemID} with author ${newItemAuthors[index]}`) - await graphql(updateProjectV2ItemMutation, { + await graphql(mutation, { + ...variables, project: projectID, statusID, statusValueID: readyForReviewID, diff --git a/src/workflows/projects.ts b/src/workflows/projects.ts index 88c24b987539..927de857e6ba 100644 --- a/src/workflows/projects.ts +++ b/src/workflows/projects.ts @@ -253,106 +253,61 @@ export function generateUpdateProjectV2ItemFieldMutation({ const datePosted = new Date() const dueDate = calculateDueDate(datePosted, turnaround) - // Build the mutation to update a single project field - // Specify literal=true to indicate that the value should be used as a string, not a variable - function generateMutationToUpdateField({ - item: itemId, - fieldID, - value, - fieldType, - literal = false, - }: { - item: string - fieldID: string - value: string - fieldType: string - literal?: boolean - }) { - const parsedValue = literal ? `${fieldType}: "${value}"` : `${fieldType}: ${value}` - - // Strip all non-alphanumeric out of the item ID when creating the mutation ID to avoid a GraphQL parsing error - // (statistically, this should still give us a unique mutation ID) + // Only fixed field names and variable references belong in the mutation document. + function generateMutationToUpdateField(fieldID: string, fieldType: string, value: string) { return ` - set_${fieldID.slice(1)}_item_${itemId.replaceAll( - /[^a-z0-9]/g, - '', - )}: updateProjectV2ItemFieldValue(input: { + set_${fieldID}: updateProjectV2ItemFieldValue(input: { projectId: $project - itemId: "${itemId}" - fieldId: ${fieldID} - value: { ${parsedValue} } + itemId: $item + fieldId: $${fieldID} + value: { ${fieldType}: $${value} } }) { - projectV2Item { - id + projectV2Item { + id + } } - } ` } const mutation = ` mutation( $project: ID! + $item: ID! $statusID: ID! $statusValueID: String! $datePostedID: ID! + $datePosted: Date! $reviewDueDateID: ID! + $reviewDueDate: Date! $contributorTypeID: ID! $contributorType: String! $sizeTypeID: ID! $sizeType: String! $featureID: ID! + $feature: String! $authorID: ID! + $author: String! ) { - ${generateMutationToUpdateField({ - item, - fieldID: '$statusID', - value: '$statusValueID', - fieldType: 'singleSelectOptionId', - })} - ${generateMutationToUpdateField({ - item, - fieldID: '$datePostedID', - value: formatDateForProject(datePosted), - fieldType: 'date', - literal: true, - })} - ${generateMutationToUpdateField({ - item, - fieldID: '$reviewDueDateID', - value: formatDateForProject(dueDate), - fieldType: 'date', - literal: true, - })} - ${generateMutationToUpdateField({ - item, - fieldID: '$contributorTypeID', - value: '$contributorType', - fieldType: 'singleSelectOptionId', - })} - ${generateMutationToUpdateField({ - item, - fieldID: '$sizeTypeID', - value: '$sizeType', - fieldType: 'singleSelectOptionId', - })} - ${generateMutationToUpdateField({ - item, - fieldID: '$featureID', - value: feature, - fieldType: 'text', - literal: true, - })} - ${generateMutationToUpdateField({ - item, - fieldID: '$authorID', - value: author, - fieldType: 'text', - literal: true, - })} - } - ` + ${generateMutationToUpdateField('statusID', 'singleSelectOptionId', 'statusValueID')} + ${generateMutationToUpdateField('datePostedID', 'date', 'datePosted')} + ${generateMutationToUpdateField('reviewDueDateID', 'date', 'reviewDueDate')} + ${generateMutationToUpdateField('contributorTypeID', 'singleSelectOptionId', 'contributorType')} + ${generateMutationToUpdateField('sizeTypeID', 'singleSelectOptionId', 'sizeType')} + ${generateMutationToUpdateField('featureID', 'text', 'feature')} + ${generateMutationToUpdateField('authorID', 'text', 'author')} + } + ` - return mutation + return { + mutation, + variables: { + item, + datePosted: formatDateForProject(datePosted), + reviewDueDate: formatDateForProject(dueDate), + feature, + author, + }, + } } // Guess the affected docs sets based on the files that the PR changed diff --git a/src/workflows/ready-for-docs-review.ts b/src/workflows/ready-for-docs-review.ts index 06757373302a..af9d10ac2656 100644 --- a/src/workflows/ready-for-docs-review.ts +++ b/src/workflows/ready-for-docs-review.ts @@ -236,7 +236,7 @@ async function run() { ) // Generate a mutation to populate fields for the new project item - const updateProjectV2ItemMutation = generateUpdateProjectV2ItemFieldMutation({ + const { mutation, variables } = generateUpdateProjectV2ItemFieldMutation({ item: newItemID, author: authorFieldValue, turnaround, @@ -261,7 +261,8 @@ async function run() { console.log(`Populating fields for item: ${newItemID}`) - await graphql(updateProjectV2ItemMutation, { + await graphql(mutation, { + ...variables, project: projectID, statusID, statusValueID: readyForReviewID, diff --git a/src/workflows/tests/projects.ts b/src/workflows/tests/projects.ts new file mode 100644 index 000000000000..f749a4b0af40 --- /dev/null +++ b/src/workflows/tests/projects.ts @@ -0,0 +1,76 @@ +import { readFileSync } from 'node:fs' + +import { graphql } from '@octokit/graphql' +import { buildSchema, parse, validate } from 'graphql' +import { afterEach, expect, test, vi } from 'vitest' + +import { generateUpdateProjectV2ItemFieldMutation, getFeature } from '../projects' + +afterEach(() => { + vi.unstubAllEnvs() +}) + +test('sends filename-derived Feature text separately from the ProjectV2 mutation', async () => { + vi.stubEnv('REPO', 'github/docs') + const directory = 'example "quoted" \\ directory' + const feature = getFeature({ + item: { + __typename: 'PullRequest', + files: { + nodes: [{ path: `content/${directory}/article.md`, additions: 1, deletions: 0 }], + }, + }, + }) + const item = 'project-item' + const author = 'Copilot + contributor' + const { mutation, variables } = generateUpdateProjectV2ItemFieldMutation({ + item, + author, + feature, + }) + const ordinary = generateUpdateProjectV2ItemFieldMutation({ + item: 'another-item', + author: 'contributor', + }) + expect(mutation).toBe(ordinary.mutation) + expect(ordinary.variables.feature).toBe('') + + const schema = buildSchema( + readFileSync(new URL('../../graphql/data/fpt/schema.docs.graphql', import.meta.url), 'utf8'), + ) + expect(validate(schema, parse(mutation))).toEqual([]) + + const projectVariables = { + project: 'project-id', + statusID: 'status-id', + statusValueID: 'ready', + datePostedID: 'date-posted-id', + reviewDueDateID: 'review-due-date-id', + contributorTypeID: 'contributor-type-id', + contributorType: 'open-source', + sizeTypeID: 'size-id', + sizeType: 'small', + featureID: 'feature-id', + authorID: 'author-id', + } + const fetch = vi.fn().mockResolvedValue( + new Response(JSON.stringify({ data: {} }), { + headers: { 'content-type': 'application/json' }, + }), + ) + await graphql(mutation, { ...variables, ...projectVariables, request: { fetch } }) + + expect(fetch).toHaveBeenCalledTimes(1) + const requestBody = JSON.parse(fetch.mock.calls[0][1]?.body as string) + expect(requestBody).toEqual({ + query: mutation, + variables: { + ...projectVariables, + item, + feature: directory, + author, + datePosted: expect.any(String), + reviewDueDate: expect.any(String), + }, + }) +})