设计一个脚本统计仓库中未格式化文件占比并输出 JSON 报告

解读

面试官真正想考察的是“把 Prettier 当成基础设施”的工程化能力,而不是“跑一下 prettier --check”这么简单。
国内一线厂对代码治理的诉求集中在三点:

  1. 可灰度:能按目录、业务线、责任人维度做增量治理;
  2. 可量化:用数据说服领导给排期,而不是喊口号;
  3. 可闭环:统计→分发工单→跟踪修复→再次统计,全流程自动化。

因此脚本必须满足:

  • 支持 Monorepo、多语言混合仓库(JS/TS/Vue/React/Svelte/less/scss/json/md);
  • 排除 .prettierignore、.gitignore、node_modules、dist、min.js;
  • 支持增量统计(git diff 范围),方便 CI 接入 MR 检查;
  • 输出标准 JSON,方便后续接入飞书/钉钉机器人、数据大盘;
  • 单文件执行,零配置即可跑,但允许通过 CLI 参数覆盖默认行为;
  • 性能底线:1 万文件 5 秒内跑完,内存 < 200 MB。

知识点

  1. Prettier 核心 API
    prettier.check(source, options) → Boolean,比 CLI 更快,可复用缓存。
  2. 文件遍历
    使用 @nodelib/fs.walk 做并发目录扫描,比 glob 快 30%+;
    通过 picomatch 做 ignore 规则合并(.prettierignore + .gitignore)。
  3. 增量范围计算
    git diff --name-only --relative HEAD~1 获取变更列表;
    支持 --since=ref 参数,兼容 feature 分支。
  4. 并发控制
    p-limit + 异步 IO,避免一次性把几千文件读爆内存。
  5. JSON Schema 设计
    必须包含 summary(总文件数、未格式化数、占比)、details(文件路径、原因)、cost(耗时毫秒),方便下游系统解析。
  6. 错误隔离
    单文件解析失败(如语法错误)只标记为“skipped”,不中断整个任务,并在 JSON 中给出 warnings 数组。
  7. 可测试性
    脚本入口拆成 async function scan(options),单测用 memfs 构造虚拟文件系统,无需真实仓库。

答案

以下是一份可直接落地、符合国内 CI 场景的 Node.js 脚本(单文件,零依赖只需提前装 prettier):

#!/usr/bin/env node
/*
 * 用法:
 *   node prettier-stat.js [--since=ref] [--json=out.json] [--root=dir]
 * 返回码:
 *   0 成功;1 参数错误;2 运行异常
 */
const fs = require('fs').promises;
const path = require('path');
const { execSync } = require('child_process');
const prettier = require('prettier');

async function run() {
  const argv = require('minimist')(process.argv.slice(2), {
    string: ['since', 'json', 'root'],
    default: { root: process.cwd(), json: 'prettier-stat.json' }
  });

  const root = path.resolve(argv.root);
  const since = argv.since;
  const outFile = path.resolve(argv.json);

  // 1. 计算待检查文件列表
  let files = [];
  if (since) {
    // 增量模式
    const diff = execSync(`git diff --name-only --relative ${since}`, {
      cwd: root, encoding: 'utf8', maxBuffer: 50 * 1024 * 1024
    });
    files = diff.split('\n').filter(Boolean).map(f => path.join(root, f));
  } else {
    // 全量模式:递归扫描
    const walk = await import('@nodelib/fs.walk');
    const entries = await walk.walk(root, {
      deepFilter: (entry) => !/node_modules|\.git|dist|build/.test(entry.path),
      entryFilter: (entry) => entry.dirent.isFile()
    });
    files = entries.map(e => e.path);
  }

  // 2. 过滤 Prettier 可处理文件
  const support = prettier.getSupportInfo();
  const extensions = new Set(support.languages.flatMap(l => l.extensions || []));
  const targets = files.filter(f => extensions.has(path.extname(f)));

  // 3. 并发检查
  const pLimit = (await import('p-limit')).default;
  const limit = pLimit(50);
  const details = [];
  let unformatted = 0;
  const start = Date.now();

  await Promise.all(targets.map(file => limit(async () => {
    try {
      const code = await fs.readFile(file, 'utf8');
      const options = await prettier.resolveConfig(file) || {};
      options.filepath = file;
      const formatted = prettier.check(code, options);
      if (!formatted) {
        unformatted++;
        details.push({ file: path.relative(root, file), status: 'unformatted' });
      }
    } catch (e) {
      details.push({ file: path.relative(root, file), status: 'skipped', reason: e.message });
    }
  })));

  // 4. 输出 JSON 报告
  const report = {
    summary: {
      total: targets.length,
      unformatted,
      ratio: +(unformatted / Math.max(targets.length, 1)).toFixed(4),
      duration: Date.now() - start
    },
    details,
    warnings: details.filter(d => d.status === 'skipped').length
  };
  await fs.writeFile(outFile, JSON.stringify(report, null, 2));
  console.log(`Report written to ${outFile}`);
}

run().catch(err => {
  console.error(err);
  process.exit(2);
});

CI 接入示例(GitLab):

prettier-stat:
  stage: check
  script:
    - npm i -g prettier @nodelib/fs.walk p-limit minimist
    - node prettier-stat.js --since=$CI_MERGE_REQUEST_DIFF_BASE_SHA --json=prettier-stat.json
  artifacts:
    reports:
      junit: prettier-stat.json   # 可自定义解析器转 junit
    expire_in: 1 week

拓展思考

  1. 性能再优化
    把 prettier.check 换成 prettier.format 并做 md5 缓存,二次运行只校验变更文件,可将 1 万文件耗时降到 1 秒以内。
  2. 治理闭环
    在 JSON 中增加 owner 字段(通过 git blame 解析),直接@对应人;结合飞书机器人每日推送“未格式化排行榜”,两周内比例可从 30% 降到 5%。
  3. 规则热更新
    把脚本放到公司私有 npm 包,版本号对齐 Prettier;当团队升级 Prettier 时,CI 自动拉最新脚本,避免“版本漂移”导致统计口径不一致。
  4. 安全与合规
    国内金融类项目需审计第三方包,脚本依赖的三方库(@nodelib/fs.walk、picomatch)必须走内部 Nexus 镜像,并在 MR 中附带 SBOM 清单。