async function fixImport(
file: string,
line: number,
char: number,
broken: string
) {
const fixed = broken + ".ts";
// open the file and replace 'broken' with 'fixed'
console.log("cwd", Deno.cwd());
if (Deno.cwd() === import.meta.dirname) {
console.log("cwd is the same as the script directory");
}
const relative = file.replace(Deno.cwd(), ".");
const decoder = new TextDecoder();
const bytes = await Deno.readFile(file);
const content = decoder.decode(bytes);
const lines = content.split("\n");
// replace the content at the line and char position with the fixed import
const targetLine = lines[line - 1];
const fixedLine =
targetLine.slice(0, char) + fixed + targetLine.slice(char + broken.length);
lines[line - 1] = fixedLine;
const updated = lines.join("\n");
Deno.writeTextFileSync(file, updated);
console.log(`🔧 fixed import for ${broken}`);
}
if (import.meta.main) {
// run deno check on and capture the output
const cmd = new Deno.Command(Deno.execPath(), {
args: ["check", "./datalayer/mod.ts"],
});
const decoder = new TextDecoder();
const fixes: string[] = [];
while (true) {
const { stderr } = await cmd.output();
const error = decoder.decode(stderr).replaceAll("\n", "");
const regex =
/(?:.*)Module not found "file:\/\/(?<broken>[^"]+)". Maybe add a '\.ts'.*file:\/\/(?<file>[^:]+):(?<line>[^:]+):(?<char>[^:]+)/;
const match = error.match(regex);
if (match && match.groups) {
const { file, broken, line, char } = match.groups;
console.log(
`🔍 found broken import "${broken}" in "${file}" (${line}:${char})`
);
await fixImport(file, Number(line), Number(char), broken);
fixes.push(broken);
} else {
break;
}
}
console.log(`🚀 fixed ${fixes.length} imports`);
}