|
| 1 | +const { promises: fs } = require("fs"); |
| 2 | +const { EOL } = require("node:os"); |
| 3 | +const path = require("path"); |
| 4 | + |
| 5 | +const filePath = "./src/converters/lintConfigs/rules/ruleConverters.ts"; |
| 6 | + |
| 7 | +module.exports.rewriteConvertersMap = async ({ args, tslintPascalCase }) => { |
| 8 | + const lines = (await fs.readFile(filePath)).toString().split(/\r\n|\r|\n/); |
| 9 | + |
| 10 | + /** |
| 11 | + * Inserts a new line alphabetically into the file lines. |
| 12 | + * |
| 13 | + * @param {string} insertion Line to be added. |
| 14 | + * @param {number} start Starting point to begin comparing at. |
| 15 | + * @param {number} end Last line to compare at, and add just after as a fallback. |
| 16 | + * @param {(line: string) => string} [mapLine] Transforms lines to be sorted. |
| 17 | + * @remarks In theory this could use binary search, but... why bother? |
| 18 | + */ |
| 19 | + const insertAlphabetically = (insertion, start, end, mapLine = (line) => line) => { |
| 20 | + const sorter = mapLine(insertion); |
| 21 | + |
| 22 | + for (let i = start; i < lines.length; i += 1) { |
| 23 | + if (mapLine(lines[i]) > sorter) { |
| 24 | + lines.splice(i, 0, insertion); |
| 25 | + return; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + lines.splice(end, 0, insertion); |
| 30 | + }; |
| 31 | + |
| 32 | + insertAlphabetically( |
| 33 | + `import { convert${tslintPascalCase} } from "./ruleConverters/${args.tslint}";`, |
| 34 | + 0, |
| 35 | + lines.indexOf(""), |
| 36 | + (line) => line.split(" from ")[1], |
| 37 | + ); |
| 38 | + |
| 39 | + insertAlphabetically( |
| 40 | + ` ["${args.tslint}", convert${tslintPascalCase}],`, |
| 41 | + lines.indexOf("export const ruleConverters = new Map([") + 1, |
| 42 | + lines.indexOf("]);"), |
| 43 | + ); |
| 44 | + |
| 45 | + await fs.writeFile(filePath, lines.join(EOL)); |
| 46 | +}; |
0 commit comments