如何自动创建 PR 评论报告?

解读

在国内前端团队的日常协作中,Pull Request(PR) 是代码合并前的最后一道质量闸门。面试官问“如何自动创建 PR 评论报告”,并不是让你背诵 GitHub API 文档,而是考察你能否用 Gulp 流式构建 的思路,把“代码 diff → 质量检测 → 报告生成 → 评论推送”整条链路自动化,并兼顾国内网络环境(GitHub 偶发超时、企业 GitLab 私有化、钉钉/飞书 Webhook 加速通知)与研发规范(Commit 规范、MR 模板、Code Owner 强制评审)。回答时要体现“代码优于配置”的 Gulp 理念,用少量 Node 代码把零散工具串成可维护的管道,而不是写一堆散乱的 Shell。

知识点

  1. Gulp 的 Vinyl 虚拟文件系统:把 Git diff、ESLint 报告、构建日志都抽象成 Vinyl 对象,才能统一走 .pipe()。
  2. 国内 Git 托管适配:GitHub 需 Personal Access Token(经典 Token 2024 后仍可用);GitLab 私有版常用 Project Access Token 或 CI_JOB_TOKEN;Gitee 企业版要走 企业微信机器人 + 密码机 绕开外网限制。
  3. PR 事件触发源:
    • GitHub Actions / GitLab CI 的 pull_request 事件最稳;
    • 若团队强制本地提 PR,可在 husky + lint-staged 后追加 gulp pr:report,把报告通过 钉钉群机器人 Markdown 消息 发出,实现“本地跑,评论到远端”。
  4. 报告内容合规:国内大厂审计要求脱敏,不能把源码片段直接贴评论;需用 Base64 混淆 + 行号映射 或 仅统计级指标(错误数、重复率、性能评分)。
  5. Gulp 4 的 series/parallel:把 git-diff → eslint → unit → markdown → post-comment 拆成 3 个并行子任务,保证 30s 内完成,避免 GitHub Actions 计费超时。

答案

下面给出一条可直接落地到国内 GitLab 私有实例的 Gulp 任务骨架,兼顾 GitHub 平滑迁移。核心思路:用 simple-git 读 diff,eslint 流式检查,got 发 HTTP 请求,全程 Vinyl 管道,代码优于配置。

// gulpfile.esm.js
import { src, dest, series, parallel } from 'gulp';
import { Transform } from 'stream';
import { ESLint } from 'eslint';
import git from 'simple-git';
import got from 'got';
import { createHash } from 'crypto';

const TOKEN = process.env.GITLAB_TOKEN || process.env.GITHUB_TOKEN;
const PROJECT_ID = process.env.CI_PROJECT_ID || process.env.GITHUB_REPOSITORY;
const MR_IID = process.env.CI_MERGE_REQUEST_IID || context.issue.number;

// 1. 生成 diff Vinyl 流
function loadDiff() {
  return new Transform({
    objectMode: true,
    transform(chunk, enc, cb) {
      git().diff(['--name-only', 'origin/main...HEAD'], (err, data) => {
        if (err) return cb(err);
        const files = data.split('\n').filter(Boolean);
        files.forEach(f => this.push({ path: f, contents: Buffer.from('') }));
        cb();
      });
    }
  });
}

// 2. ESLint 流式检查
function eslintStream() {
  const eslint = new ESLint();
  return new Transform({
    objectMode: true,
    async transform(file, enc, cb) {
      if (!file.path.endsWith('.js')) return cb(null, file);
      const results = await eslint.lintFiles([file.path]);
      file.eslint = results[0].errorCount + results[0].warningCount;
      cb(null, file);
    }
  });
}

// 3. 聚合报告并推送评论
function publishReport() {
  return new Transform({
    objectMode: true,
    transform(file, enc, cb) {
      const total = file.eslint || 0;
      const body = `## 构建报告(自动)
- **ESLint 问题数**:${total}
- **Commit 哈希**:${createHash('md5').update(process.env.CI_COMMIT_SHA).digest('hex').slice(0, 8)}
- **生成时间**:${new Date().toLocaleString('zh-CN')}
> 由 Gulp 流式任务自动投递,无需人工粘贴。`;
      const api = process.env.GITLAB_TOKEN
        ? `${process.env.CI_API_V4_URL}/projects/${PROJECT_ID}/merge_requests/${MR_IID}/notes`
        : `https://api.github.com/repos/${PROJECT_ID}/issues/${MR_IID}/comments`;
      got.post(api, {
        headers: {
          'PRIVATE-TOKEN': process.env.GITLAB_TOKEN,
          'Authorization': process.env.GITHUB_TOKEN ? `token ${process.env.GITHUB_TOKEN}` : ''
        },
        json: { body }
      }).then(() => cb()).catch(cb);
    }
  });
}

// 4. 组合任务
export const prReport = series(
  () => src('.').pipe(loadDiff()).pipe(eslintStream()).pipe(publishReport())
);

使用方式

  1. 在 .gitlab-ci.yml 里加:
    pr_report:
      stage: test
      only: [merge_requests]
      script: npx gulp prReport
    
  2. 若团队用 GitHub,把 GITHUB_TOKEN 塞到 Secrets,任务名改成 pull_request 触发即可。
  3. 国内加速:把 got 换成 axios 并配 HTTPS_PROXY 走公司 Nexus 代理,解决 api.github.com 丢包问题。

拓展思考

  1. 增量性能报告:在 Gulp 管道里再插一个 webpack-bundle-analyzer 的 JSON 输出,对比上次主分支的 stats.json,用 gzip-size 算增量,把“新增 3.2 kB gzip”自动贴在 PR,性能预算超标即 @CodeOwner,这套方案已在阿里内部脚手架 def-gulp 落地。
  2. 国内移动端适配:很多团队用 Gitee 企业版,但 Gitee PR 接口无官方评论字段,可曲线救国:Gulp 任务把报告推送到 钉钉群机器人,@对应 Commit 作者,实现“评论即通知”,合规又及时。
  3. 可视化回归:把 BackstopJS 截图 diff 结果上传到 阿里云 OSS + 私有 CDN,Gulp 管道拿到访问 URL 后,用 Markdown 图片语法贴进 PR,UI 变更一目了然,面试官听到“Gulp 管图片、OSS 做加速”会立刻加分。