You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将GitHub Actions中yarn audit的运行结果添加到PR评论中

将Yarn Audit结果添加到PR评论的实现方案

以下是具体的GitHub Actions配置步骤,直接替换或添加到你的Workflow文件中即可:

1. 基础Workflow触发配置

确保Workflow只在PR创建或更新时触发,在Workflow文件开头添加:

on:
  pull_request:
    types: [opened, synchronize]

2. 完整Job配置

jobs:
  audit-comment:
    runs-on: ubuntu-latest
    steps:
      - name: 拉取代码
        uses: actions/checkout@v4

      - name: 配置Node.js环境
        uses: actions/setup-node@v4
        with:
          node-version: '20' # 根据你的项目Node版本调整
          cache: 'yarn'

      - name: 安装依赖
        run: yarn install --frozen-lockfile

      - name: 执行Yarn Audit并保存结果
        run: yarn audit > yarn-audit-results.txt 2>&1 || true
        # 2>&1 捕获所有输出(包括错误信息);|| true 避免因检测到漏洞导致步骤失败

      - name: 将Audit结果添加到PR评论
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const auditResults = fs.readFileSync('./yarn-audit-results.txt', 'utf8');
            // 判断是否检测到漏洞,避免无意义的冗余评论
            const hasVulnerabilities = auditResults.includes('found') && auditResults.includes('vulnerability');
            if (hasVulnerabilities) {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: `### 🚨 Yarn Audit 检测结果\n\`\`\`text\n${auditResults}\`\`\``
              });
            } else {
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: '✅ Yarn Audit 未检测到漏洞'
              });
            }

关键说明

  • 权限说明:默认的GITHUB_TOKEN已经拥有创建PR评论的权限,无需额外配置。
  • 结果过滤:示例中加入了漏洞判断逻辑,只有检测到漏洞时才输出详细结果,无漏洞时输出提示,避免冗余评论。
  • 输出截断:如果Audit结果过长超出GitHub评论字符限制,可以在yarn audit命令后添加--level high只检测高危漏洞,或者用head -n 100截断输出(如yarn audit | head -n 100 > yarn-audit-results.txt 2>&1 || true)。
  • 错误处理:|| true确保即使Audit返回非0状态码(检测到漏洞),后续步骤仍能执行;如果希望检测到漏洞时Workflow失败,可以移除|| true,并调整评论逻辑。

内容的提问来源于stack exchange,提问作者smooth97

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:31:35