|
| 1 | +/* eslint-env node */ |
| 2 | +// eslint-disable console |
| 3 | +import { promises } from "fs"; |
| 4 | +import path from "path"; |
| 5 | +import os from "os"; |
| 6 | +import pQueue from "p-queue"; |
| 7 | + |
| 8 | +const CONCURRENCY = Math.max(1, os.cpus().length - 1); |
| 9 | + |
| 10 | +const { default: PQueue } = pQueue; |
| 11 | + |
| 12 | +import ignored from "./ignore.js"; |
| 13 | + |
| 14 | +const [, ignoredDirectories] = ignored; |
| 15 | + |
| 16 | +const { |
| 17 | + readFile: readFileAsync, |
| 18 | + writeFile: writeFileAsync, |
| 19 | + readdir: readDirectoryAsync |
| 20 | +} = promises; |
| 21 | + |
| 22 | +const [, , cwd = process.cwd()] = process.argv; |
| 23 | +const root = cwd; |
| 24 | + |
| 25 | +const main = async cwd => { |
| 26 | + console.log(`Normalizing files in ${cwd}...`); |
| 27 | + |
| 28 | + const entries = await readDirectoryAsync(cwd, { withFileTypes: true }); |
| 29 | + |
| 30 | + const files = entries.filter(x => x.isFile()).map(x => x.name); |
| 31 | + |
| 32 | + const directories = entries |
| 33 | + .filter(x => x.isDirectory()) |
| 34 | + .map(x => x.name) |
| 35 | + .filter(x => !ignoredDirectories.includes(x)); |
| 36 | + |
| 37 | + for (const directory of directories) { |
| 38 | + await main(path.join(cwd, directory)); |
| 39 | + } |
| 40 | + |
| 41 | + const processFile = async file => { |
| 42 | + const filePath = path.join(cwd, file); |
| 43 | + const relativeFilePath = path.relative(root, filePath); |
| 44 | + |
| 45 | + try { |
| 46 | + console.log(`Normalizing ${relativeFilePath}...`); |
| 47 | + |
| 48 | + const contents = await readFileAsync(filePath, "utf-8"); |
| 49 | + |
| 50 | + const normalized = contents |
| 51 | + .split("\n") |
| 52 | + .map(x => x.trimEnd()) |
| 53 | + .join("\n"); |
| 54 | + |
| 55 | + await writeFileAsync(filePath, normalized, "utf-8"); |
| 56 | + } catch (error) { |
| 57 | + console.error(error); |
| 58 | + |
| 59 | + process.exit(1); |
| 60 | + } |
| 61 | + }; |
| 62 | + |
| 63 | + const queue = new PQueue({ concurrency: CONCURRENCY }); |
| 64 | + |
| 65 | + for (const file of files) { |
| 66 | + queue.add(() => processFile(file)); |
| 67 | + } |
| 68 | + |
| 69 | + await queue.onIdle(); |
| 70 | +}; |
| 71 | + |
| 72 | +main(cwd); |
0 commit comments