|
| 1 | +import { execFileSync } from "child_process"; |
| 2 | +import fs from "fs"; |
| 3 | + |
| 4 | +function formatAll() { |
| 5 | + console.log("Formatting all files..."); |
| 6 | + execFileSync("npm", ["run", "pretty:fix"], { stdio: "inherit" }); |
| 7 | + execFileSync("npm", ["run", "lint:fix"], { stdio: "inherit" }); |
| 8 | +} |
| 9 | + |
| 10 | +function runInBatches(command, args, files, batchSize = 100) { |
| 11 | + for (let i = 0; i < files.length; i += batchSize) { |
| 12 | + const batch = files.slice(i, i + batchSize); |
| 13 | + execFileSync("npx", [command, ...args, ...batch], { stdio: "inherit" }); |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +function runPrettier(files) { |
| 18 | + try { |
| 19 | + console.log(`Running prettier on ${files.length} file(s)`); |
| 20 | + runInBatches("prettier", ["--write", "--ignore-unknown"], files); |
| 21 | + } catch (e) { |
| 22 | + console.error("Prettier formatting failed"); |
| 23 | + process.exit(1); |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +function runEslint(files) { |
| 28 | + const jsTsFiles = files.filter((f) => /\.(js|mjs|jsx|ts|tsx)$/.test(f)); |
| 29 | + if (jsTsFiles.length === 0) |
| 30 | + return; |
| 31 | + try { |
| 32 | + console.log(`Running eslint on ${jsTsFiles.length} file(s)`); |
| 33 | + runInBatches("eslint", ["--fix"], jsTsFiles); |
| 34 | + } catch (e) { |
| 35 | + console.error("ESLint formatting failed"); |
| 36 | + process.exit(1); |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +function getChangedFiles() { |
| 41 | + const diffOut = execFileSync("git", ["diff", "--name-only", "--diff-filter=ACMR", "@{upstream}"], { encoding: "utf8" }); |
| 42 | + const files = diffOut |
| 43 | + .split("\n") |
| 44 | + .map((f) => f.trim()) |
| 45 | + .filter((f) => f.length > 0 && fs.existsSync(f)); |
| 46 | + return [...new Set(files)]; |
| 47 | +} |
| 48 | + |
| 49 | +const isAll = process.argv.includes("--all"); |
| 50 | + |
| 51 | +if (isAll) { |
| 52 | + formatAll(); |
| 53 | + process.exit(0); |
| 54 | +} |
| 55 | + |
| 56 | +let changedFiles = []; |
| 57 | +try { |
| 58 | + changedFiles = getChangedFiles(); |
| 59 | +} catch (e) { |
| 60 | + console.error("Failed to get changed files from git. Falling back to formatting all files."); |
| 61 | + formatAll(); |
| 62 | + process.exit(0); |
| 63 | +} |
| 64 | + |
| 65 | +if (changedFiles.length === 0) { |
| 66 | + console.log("No files changed compared to upstream."); |
| 67 | + process.exit(0); |
| 68 | +} |
| 69 | +console.log(`Formatting ${changedFiles.length} changed files compared to upstream`); |
| 70 | + |
| 71 | +runPrettier(changedFiles); |
| 72 | +runEslint(changedFiles); |
0 commit comments