commover
Version:
Batch remove unused @ts-expect-error directive comment lines, especially helpful when using with ts-migrate.
85 lines (80 loc) • 2.65 kB
JavaScript
// src/index.ts
import "zx/globals";
import { program } from "commander";
// src/utils.ts
import "zx/globals";
function groupErrors(logText) {
return logText.split("\n").reduce((res, text) => {
const [, errorType] = text.match(/(TS\d+)/) || [];
if (errorType) {
const [relPath, message] = text.split(
new RegExp(`:\\s+error ${errorType}:\\s+`)
);
const index = relPath.lastIndexOf("(");
const filePath = relPath.slice(0, index);
try {
const [line, col] = relPath.slice(index).split(",").map((v) => Number.parseInt(v.match(/\w+/)[0]));
res[filePath] = [
...res[filePath] ?? [],
{ type: errorType, message, line, col }
];
} catch (e) {
console.log(e);
}
}
return res;
}, {});
}
// package.json
var name = "commover";
var version = "1.0.0";
var description = "Batch remove unused @ts-expect-error directive comment lines, especially helpful when using with ts-migrate.";
// src/index.ts
var commentLineReg = [
/** // @ts-expect-error → Starts with // and possible spaces */
/^\s*\/\//,
/** {/* @ts-expect-error → Starts with {/ and possible spaces */
/^\s*\{\s*\/\*.*\*\/\s*}/
];
program.name(name).description(description).version(version).argument("<path>", "Path to the ts compile log.").action((input) => {
try {
const errorGroup = groupErrors(fs.readFileSync(input, "utf8"));
const unhandled = {};
for (const [filePath, errors] of Object.entries(errorGroup)) {
const fileLines = fs.readFileSync(filePath, "utf8").split("\n");
for (const error of errors.filter((v) => v.type === "TS2578").toSorted((a, b) => b.line - a.line)) {
const lineIndex = error.line - 1;
if (commentLineReg.some((v) => v.test(fileLines[lineIndex]))) {
fileLines.splice(lineIndex, 1);
console.log(
`${chalk.blue("Removed line")}: ${filePath}:${error.line}`
);
} else {
unhandled[filePath] = [...unhandled[filePath] ?? [], error];
}
}
fs.writeFileSync(filePath, fileLines.join("\n"));
}
const arr = [];
for (const [filePath, errors] of Object.entries(unhandled)) {
arr.push(
...errors.map(
(v) => `${filePath}:${v.line} ${chalk.red(v.type)} ${v.message} `
)
);
}
if (arr.length) {
console.log(
"\n",
arr.join("\n"),
chalk.blue.bold(
"\n\nThese lines are not a pure comment line, please manually remove it."
)
);
}
} catch (e) {
console.log(e.message);
}
});
program.parse();