Skip to content

Instantly share code, notes, and snippets.

@jomifepe
Last active October 23, 2024 13:52
Show Gist options
  • Save jomifepe/e071415f6059f3703baa68458d5027f6 to your computer and use it in GitHub Desktop.
Save jomifepe/e071415f6059f3703baa68458d5027f6 to your computer and use it in GitHub Desktop.
Converts interfaces to types
import { parseArgs } from "https://deno.land/[email protected]/cli/parse_args.ts";
import { join } from "https://deno.land/[email protected]/path/mod.ts";
const { debug } = parseArgs(Deno.args, { boolean: ["debug"], default: { "debug": false } });
const interfaceRegex = /interface\s+(\w+)(\s+extends\s+([\w, ]+))?\s*{([^}]*)}/g;
let convertedFiles = 0
function isIncludedDir(filePath: string) {
return ["configs", "packages", "scripts"].find((dir) => filePath.startsWith(Deno.realPathSync(dir)))
}
function convertInterfaceToType(content: string) {
const newContent = content.replace(interfaceRegex, (_, name, __, extendedTypes, body) => {
let result = `type ${name} = `;
if (extendedTypes) result += `${extendedTypes.trim()} & `;
result += `{\n${body.trim()}\n}`;
return result;
});
return newContent;
}
function transformFile(filePath: string) {
const content = Deno.readTextFileSync(filePath);
const convertedContent = convertInterfaceToType(content);
Deno.writeTextFileSync(filePath, convertedContent);
convertedFiles++
if (debug) console.log(`%cFile converted: ${filePath}`, "color: green");
}
function transform(dir = Deno.cwd()) {
const files = Deno.readDirSync(dir);
let printedDebugLogs = false
for (const file of files) {
const path = join(dir, file.name);
if (file.isFile) {
if (path.endsWith(".ts") || path.endsWith(".tsx")) {
if (debug) {
console.log(`%cChecking file ${path}`, "color: blue")
printedDebugLogs = true
}
const lines = Deno.readTextFileSync(path).split("\n");
for (let lineNum = 0; lineNum < lines.length; lineNum++) {
if (!lines[lineNum].match(/interface\s([A-Za-z_][A-Za-z0-9_])*\s*{/)) continue;
transformFile(path)
}
}
} else if (file.isDirectory && isIncludedDir(path)) {
transform(path);
}
}
if (printedDebugLogs) console.log();
};
function changes() {
if (convertedFiles === 0) {
console.log('%cNo files converted', "color: red");
} else {
console.log(`%cConverted ${convertedFiles} files`, "color: green");
}
if (debug) console.log();
}
function prettier() {
if (debug) console.log('%cRunning prettier...', "font-weight: bold");
new Deno.Command('yarn', {
args: ['prettier-write'],
...(debug ? { stdout: 'inherit', stderr: 'inherit'} : {})
}).outputSync();
if (debug) console.log();
}
function tsc() {
if (debug) console.log('%cRunning tsc...', "font-weight: bold");
new Deno.Command('yarn', {
args: ['tsc'],
...(debug ? { stdout: 'inherit', stderr: 'inherit'} : {})
}).outputSync();
if (debug) console.log();
}
transform();
changes()
prettier();
tsc();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment