diff --git a/src/content-render/scripts/move-by-content-type.ts b/src/content-render/scripts/move-by-content-type.ts index c64ef0ed27fc..0e5dc89cbaed 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 { @@ -85,13 +112,21 @@ program .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 +134,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`)) @@ -155,7 +190,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 +250,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 +311,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`)) @@ -372,11 +395,9 @@ contentType: ${placeholderContentType} // 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 +431,7 @@ contentType: ${placeholderContentType} ['run', 'move-content', '--', relativeFilePath, relativeTargetPath, '--no-git'], { cwd: process.cwd(), + env: { ...process.env, ROOT: '.' }, stdio: 'inherit', }, ) @@ -535,7 +557,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 +600,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 +625,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 +667,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..de9cc2a54ca4 --- /dev/null +++ b/src/content-render/tests/move-by-content-type.ts @@ -0,0 +1,96 @@ +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' + +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) +})