Skip to content

Instantly share code, notes, and snippets.

@kaydelaney
Created May 1, 2024 22:20
Show Gist options
  • Save kaydelaney/489bac318fe99febd7d0cf3e40b2071b to your computer and use it in GitHub Desktop.
Save kaydelaney/489bac318fe99febd7d0cf3e40b2071b to your computer and use it in GitHub Desktop.
Hacky codemod thing
const paths = [
// paths to ts/tsx/js/jsx files go here
];
function kebabToCamel(kebabString: string) {
return kebabString.replaceAll(/-(.)/g, (_, char) => char.toUpperCase());
}
const problemFiles = [];
for (const path of paths) {
try {
const text = await Deno.readTextFile(path);
const fixedText = text.replaceAll(/css`((?:.|\n)+?)`/gm, (match) => {
const cssString = match;
const propValues = cssString.split('\n').slice(1, -1);
let cssObjStr = `css({\n`;
for (const propValue of propValues) {
const [prop, value] = propValue.split(':');
const fixedProp = kebabToCamel(prop.trim());
cssObjStr += fixedProp + ': ';
let fixedValue = value.trim();
const match = fixedValue.match(/^(?<val>.+?);\s*(?:$|(?<comment>\/\/.*)$)/);
fixedValue = match?.groups?.val ?? '';
const comment = match?.groups?.comment ?? '';
// ${theme.blah} -> theme.blah
// not super robust but there probably won't be too many false positives
if (/^\${[^}]*?\}$/.test(fixedValue)) {
fixedValue = fixedValue.slice(2, -1);
} else if (fixedValue.includes('${')) {
fixedValue = `\`${fixedValue}\``;
} else if (Number.parseInt(fixedValue, 10).toString() !== fixedValue) {
fixedValue = `'${fixedValue}'`;
}
cssObjStr += fixedValue + `,${comment}\n`;
}
cssObjStr += '})';
return cssObjStr;
});
await Deno.writeTextFile(path, fixedText);
} catch (_err) {
problemFiles.push(path);
}
console.log(`Processed ${paths.length - problemFiles.length}/${paths.length} files`);
console.log(`Could not process the following files:\n${problemFiles.join('\n')}`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment