|
| 1 | +import { writeFile } from 'node:fs/promises' |
| 2 | +import { bold } from 'picocolors' |
| 3 | +import prompts from 'prompts' |
| 4 | +import { TRANSFORM_OPTIONS } from '../config' |
| 5 | +import { getAllFiles, getContent } from '../utils/file' |
| 6 | + |
| 7 | +export function onCancel() { |
| 8 | + process.exit(1) |
| 9 | +} |
| 10 | + |
| 11 | +// biome-ignore lint/suspicious/noExplicitAny: 'Any' is used because options can be anything. |
| 12 | +export async function transform(codemodName: string, source: string, options: any): Promise<void> { |
| 13 | + let codemodSelected = codemodName |
| 14 | + let sourceSelected = source |
| 15 | + |
| 16 | + const { dry } = options |
| 17 | + |
| 18 | + let existCodemod = TRANSFORM_OPTIONS.find(({ value }) => value === codemodSelected) |
| 19 | + |
| 20 | + if (!codemodSelected || (codemodSelected && !existCodemod)) { |
| 21 | + const res = await prompts( |
| 22 | + { |
| 23 | + type: 'select', |
| 24 | + name: 'transformer', |
| 25 | + message: 'Which codemod would you like to apply?', |
| 26 | + choices: TRANSFORM_OPTIONS.map(({ description, value, version }) => { |
| 27 | + return { |
| 28 | + title: `(${bold(`v${version}`)}) ${value}`, |
| 29 | + description, |
| 30 | + value, |
| 31 | + } |
| 32 | + }), |
| 33 | + }, |
| 34 | + { onCancel }, |
| 35 | + ) |
| 36 | + |
| 37 | + codemodSelected = res.transformer |
| 38 | + existCodemod = TRANSFORM_OPTIONS.find(({ value }) => value === codemodSelected) |
| 39 | + } |
| 40 | + |
| 41 | + if (!sourceSelected) { |
| 42 | + const res = await prompts( |
| 43 | + { |
| 44 | + type: 'text', |
| 45 | + name: 'path', |
| 46 | + message: 'Which files or directories should the codemods be applied to?', |
| 47 | + initial: '.', |
| 48 | + }, |
| 49 | + { onCancel }, |
| 50 | + ) |
| 51 | + |
| 52 | + sourceSelected = res.path |
| 53 | + } |
| 54 | + |
| 55 | + const files = await getAllFiles(sourceSelected) |
| 56 | + |
| 57 | + for (const file of files) { |
| 58 | + const content = await getContent(file) |
| 59 | + |
| 60 | + if (existCodemod) { |
| 61 | + const newContent = existCodemod.codemod({ path: file.toString(), source: content }, options) |
| 62 | + |
| 63 | + if (!dry) { |
| 64 | + await writeFile(file.toString(), newContent) |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments