Files
ims/scripts/modernist-codemod.mjs
T

56 lines
2.0 KiB
JavaScript

import { readdirSync, readFileSync, writeFileSync, statSync } from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const CLASS_ATTR =
/className=(?:"[^"]*"|'[^']*'|\{"[^"]*"\}|\{'[^']*'\}|\{`(?:[^`\\]|\\.)*`\})/g
const ROUNDED =
/(?<![\w:-])(?:[\w-]+:)*rounded(?:-(?:t|b|l|r|tl|tr|bl|br|s|e))?(?:-(?:xs|sm|md|lg|xl|2xl|3xl|4xl|none))?(?![\w-])/g
function transformClassAttr(attr) {
let out = attr
out = out.replace(ROUNDED, '')
out = out.replace(/(?<![\w-])bg-white(?![\w-])/g, 'bg-surface')
out = out.replace(/(?<![\w-])border-gray-(?:100|200|300)(?![\w-])/g, 'border-divider')
out = out.replace(/(?<![\w-])divide-gray-(?:100|200|300)(?![\w-])/g, 'divide-divider')
out = out.replace(/(?<![\w-])shadow-(?:xl|2xl)(?![\w-])/g, 'shadow-lg')
out = out.replace(/(["'])([^"'`$]*)\1/g, (_, q, body) => q + body.trim().replace(/ {2,}/g, ' ') + q)
out = out.replace(/^(className=\{`)\s+/, '$1').replace(/\s+(`\})$/, '$1')
out = out.replace(/ {2,}/g, ' ')
return out
}
export function transformSource(src) {
const next = src.replace(CLASS_ATTR, transformClassAttr)
return next.replace(/ className=(?:""|''|\{""\}|\{''\}|\{``\})/g, '')
}
function walk(dir, files = []) {
for (const name of readdirSync(dir)) {
const full = path.join(dir, name)
if (statSync(full).isDirectory()) walk(full, files)
else if (full.endsWith('.tsx')) files.push(full)
}
return files
}
function main() {
const dry = process.argv.includes('--dry')
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
let changed = 0
for (const dir of ['app', 'components']) {
for (const file of walk(path.join(root, dir))) {
const before = readFileSync(file, 'utf8')
const after = transformSource(before)
if (after !== before) {
changed++
if (!dry) writeFileSync(file, after)
}
}
}
console.log(`${dry ? 'would change' : 'changed'} ${changed} files`)
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main()