|
| 1 | +/* eslint-disable @typescript-eslint/default-param-last */ |
| 2 | +import os from 'node:os'; |
| 3 | +import { join } from 'node:path'; |
| 4 | + |
| 5 | +import { program } from 'commander'; |
| 6 | +import { promises as fs } from 'fs'; |
| 7 | +import pLimit from 'p-limit'; |
| 8 | +import picocolors from 'picocolors'; |
| 9 | +import slash from 'slash'; |
| 10 | + |
| 11 | +import { configToCsfFactory } from '../../code/lib/cli-storybook/src/codemod/helpers/config-to-csf-factory'; |
| 12 | +import { storyToCsfFactory } from '../../code/lib/cli-storybook/src/codemod/helpers/story-to-csf-factory'; |
| 13 | +import { SNIPPETS_DIRECTORY } from '../utils/constants'; |
| 14 | + |
| 15 | +const logger = console; |
| 16 | + |
| 17 | +export const maxConcurrentTasks = Math.max(1, os.cpus().length - 1); |
| 18 | + |
| 19 | +type SnippetInfo = { |
| 20 | + path: string; |
| 21 | + source: string; |
| 22 | + attributes: { |
| 23 | + filename?: string; |
| 24 | + language?: string; |
| 25 | + renderer?: string; |
| 26 | + tabTitle?: string; |
| 27 | + highlightSyntax?: string; |
| 28 | + [key: string]: string; |
| 29 | + }; |
| 30 | +}; |
| 31 | + |
| 32 | +type Codemod = { |
| 33 | + check: (snippetInfo: SnippetInfo) => boolean; |
| 34 | + transform: (snippetInfo: SnippetInfo) => string | Promise<string>; |
| 35 | +}; |
| 36 | + |
| 37 | +export async function runSnippetCodemod({ |
| 38 | + glob, |
| 39 | + check, |
| 40 | + transform, |
| 41 | + dryRun = false, |
| 42 | +}: { |
| 43 | + glob: string; |
| 44 | + check: Codemod['check']; |
| 45 | + transform: Codemod['transform']; |
| 46 | + dryRun?: boolean; |
| 47 | +}) { |
| 48 | + let modifiedCount = 0; |
| 49 | + let unmodifiedCount = 0; |
| 50 | + let errorCount = 0; |
| 51 | + let skippedCount = 0; |
| 52 | + |
| 53 | + try { |
| 54 | + // Dynamically import these packages because they are pure ESM modules |
| 55 | + // eslint-disable-next-line depend/ban-dependencies |
| 56 | + const { globby } = await import('globby'); |
| 57 | + |
| 58 | + const files = await globby(slash(glob), { |
| 59 | + followSymbolicLinks: true, |
| 60 | + ignore: ['node_modules/**', 'dist/**', 'storybook-static/**', 'build/**'], |
| 61 | + }); |
| 62 | + |
| 63 | + if (!files.length) { |
| 64 | + logger.error(`No files found for pattern ${glob}`); |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + const limit = pLimit(10); |
| 69 | + |
| 70 | + await Promise.all( |
| 71 | + files.map((file) => |
| 72 | + limit(async () => { |
| 73 | + try { |
| 74 | + const source = await fs.readFile(file, 'utf-8'); |
| 75 | + const snippets = extractSnippets(source); |
| 76 | + if (snippets.length === 0) { |
| 77 | + unmodifiedCount++; |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + const targetSnippet = snippets.find(check); |
| 82 | + if (!targetSnippet) { |
| 83 | + skippedCount++; |
| 84 | + logger.log('Skipping file', file); |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + const counterpartSnippets = snippets.filter((snippet) => { |
| 89 | + return ( |
| 90 | + snippet !== targetSnippet && |
| 91 | + snippet.attributes.renderer === targetSnippet.attributes.renderer && |
| 92 | + snippet.attributes.language !== targetSnippet.attributes.language |
| 93 | + ); |
| 94 | + }); |
| 95 | + |
| 96 | + const getSource = (snippet: SnippetInfo) => |
| 97 | + `\n\`\`\`${formatAttributes(snippet.attributes)}\n${snippet.source}\n\`\`\`\n`; |
| 98 | + |
| 99 | + try { |
| 100 | + let appendedContent = ''; |
| 101 | + if (counterpartSnippets.length > 0) { |
| 102 | + appendedContent += |
| 103 | + '\n<!-- js & ts-4-9 (when applicable) still needed while providing both CSF 3 & 4 -->\n'; |
| 104 | + } |
| 105 | + |
| 106 | + for (const snippet of [targetSnippet, ...counterpartSnippets]) { |
| 107 | + const newSnippet = { ...snippet }; |
| 108 | + newSnippet.attributes.tabTitle = 'CSF 4 (experimental)'; |
| 109 | + appendedContent += getSource({ |
| 110 | + ...newSnippet, |
| 111 | + attributes: { |
| 112 | + ...newSnippet.attributes, |
| 113 | + renderer: 'react', |
| 114 | + tabTitle: 'CSF 4 (experimental)', |
| 115 | + }, |
| 116 | + source: await transform(newSnippet), |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + const updatedSource = source + appendedContent; |
| 121 | + |
| 122 | + if (!dryRun) { |
| 123 | + await fs.writeFile(file, updatedSource, 'utf-8'); |
| 124 | + } else { |
| 125 | + logger.log( |
| 126 | + `Dry run: would have modified ${picocolors.yellow(file)} with \n` + |
| 127 | + picocolors.green(appendedContent) |
| 128 | + ); |
| 129 | + } |
| 130 | + |
| 131 | + modifiedCount++; |
| 132 | + } catch (transformError) { |
| 133 | + logger.error(`Error transforming snippet in file ${file}:`, transformError); |
| 134 | + errorCount++; |
| 135 | + } |
| 136 | + } catch (fileError) { |
| 137 | + logger.error(`Error processing file ${file}:`, fileError); |
| 138 | + errorCount++; |
| 139 | + } |
| 140 | + }) |
| 141 | + ) |
| 142 | + ); |
| 143 | + } catch (error) { |
| 144 | + logger.error('Error applying snippet transform:', error); |
| 145 | + errorCount++; |
| 146 | + } |
| 147 | + |
| 148 | + logger.log( |
| 149 | + `Summary: ${picocolors.green(`${modifiedCount} files modified`)}, ${picocolors.yellow(`${unmodifiedCount} files unmodified`)}, ${picocolors.gray(`${skippedCount} skipped`)}, ${picocolors.red(`${errorCount} errors`)}` |
| 150 | + ); |
| 151 | +} |
| 152 | + |
| 153 | +export function extractSnippets(source: string): SnippetInfo[] { |
| 154 | + const snippetRegex = |
| 155 | + /```(?<highlightSyntax>[a-zA-Z0-9]+)?(?<attributes>[^\n]*)\n(?<content>[\s\S]*?)```/g; |
| 156 | + const snippets: SnippetInfo[] = []; |
| 157 | + let match; |
| 158 | + |
| 159 | + while ((match = snippetRegex.exec(source)) !== null) { |
| 160 | + const { highlightSyntax, attributes, content } = match.groups || {}; |
| 161 | + const snippetAttributes = parseAttributes(attributes || ''); |
| 162 | + if (highlightSyntax) { |
| 163 | + snippetAttributes.highlightSyntax = highlightSyntax.trim(); |
| 164 | + } |
| 165 | + |
| 166 | + snippets.push({ |
| 167 | + path: snippetAttributes.filename || '', |
| 168 | + source: content.trim(), |
| 169 | + attributes: snippetAttributes, |
| 170 | + }); |
| 171 | + } |
| 172 | + |
| 173 | + return snippets; |
| 174 | +} |
| 175 | + |
| 176 | +export function parseAttributes(attributes: string): Record<string, string> { |
| 177 | + const attributeRegex = /([a-zA-Z0-9.-]+)="([^"]+)"/g; |
| 178 | + const result: Record<string, string> = {}; |
| 179 | + let match; |
| 180 | + |
| 181 | + while ((match = attributeRegex.exec(attributes)) !== null) { |
| 182 | + result[match[1]] = match[2]; |
| 183 | + } |
| 184 | + |
| 185 | + return result; |
| 186 | +} |
| 187 | + |
| 188 | +function formatAttributes(attributes: Record<string, string>): string { |
| 189 | + const formatted = Object.entries(attributes) |
| 190 | + .filter(([key]) => key !== 'highlightSyntax') |
| 191 | + .map(([key, value]) => `${key}="${value}"`) |
| 192 | + .join(' '); |
| 193 | + return `${attributes.highlightSyntax || 'js'} ${formatted}`; |
| 194 | +} |
| 195 | + |
| 196 | +const codemods: Record<string, Codemod> = { |
| 197 | + 'csf-factory-story': { |
| 198 | + check: (snippetInfo: SnippetInfo) => { |
| 199 | + return ( |
| 200 | + snippetInfo.path.includes('.stories') && |
| 201 | + snippetInfo.attributes.tabTitle !== 'CSF 4 (experimental)' && |
| 202 | + snippetInfo.attributes.language === 'ts' && |
| 203 | + (snippetInfo.attributes.renderer === 'react' || |
| 204 | + snippetInfo.attributes.renderer === 'common') |
| 205 | + ); |
| 206 | + }, |
| 207 | + transform: storyToCsfFactory, |
| 208 | + }, |
| 209 | + 'csf-factory-config': { |
| 210 | + check: (snippetInfo: SnippetInfo) => { |
| 211 | + return ( |
| 212 | + snippetInfo.attributes.tabTitle !== 'CSF 4 (experimental)' && |
| 213 | + (snippetInfo.path.includes('preview') || snippetInfo.path.includes('main')) |
| 214 | + ); |
| 215 | + }, |
| 216 | + transform: (snippetInfo: SnippetInfo) => { |
| 217 | + const configType = snippetInfo.path.includes('preview') ? 'preview' : 'main'; |
| 218 | + return configToCsfFactory(snippetInfo, { |
| 219 | + configType, |
| 220 | + frameworkPackage: '@storybook/your-framework', |
| 221 | + }); |
| 222 | + }, |
| 223 | + }, |
| 224 | +}; |
| 225 | + |
| 226 | +program |
| 227 | + .name('command') |
| 228 | + .description('A minimal CLI for demonstration') |
| 229 | + .argument('<id>', 'ID to process') |
| 230 | + .requiredOption('--glob <pattern>', 'Glob pattern to match') |
| 231 | + .option('--dry-run', 'Run without making actual changes', false) |
| 232 | + .action(async (id, { glob, dryRun }) => { |
| 233 | + const codemod = codemods[id as keyof typeof codemods]; |
| 234 | + if (!codemod) { |
| 235 | + logger.error(`Unknown codemod "${id}"`); |
| 236 | + logger.log( |
| 237 | + `\n\nAvailable codemods: ${Object.keys(codemods) |
| 238 | + .map((c) => `\n- ${c}`) |
| 239 | + .join('')}` |
| 240 | + ); |
| 241 | + process.exit(1); |
| 242 | + } |
| 243 | + |
| 244 | + await runSnippetCodemod({ |
| 245 | + glob: join(SNIPPETS_DIRECTORY, glob), |
| 246 | + dryRun, |
| 247 | + ...codemod, |
| 248 | + }); |
| 249 | + }); |
| 250 | + |
| 251 | +// Parse and validate arguments |
| 252 | +program.parse(process.argv); |
0 commit comments