如何将bash命令的输出放入GitHub Actions的yaml消息中

43次阅读
没有评论

问题描述

在GitHub Actions中有一个工作流程,目的是从一个coverage.txt文件中读取代码覆盖率,并将覆盖率作为评论打印出来。用户在获取文件的输出(使用bash命令awk '/^Lines/ { print $2 }' < coverage.txt)后,想将其插入到消息中,而消息目前只是一个简单的问候语。用户在尝试使用一些YAML变量的代码后遇到了问题,不知道是否有更好的方法。用户还考虑是否可以直接将文件的内容转储到消息中。

解决方案

请注意以下操作注意版本差异及修改前做好备份。

方案1

您可以使用GitHub Actions的run步骤来运行bash命令,并将其输出存储在一个变量中。然后,您可以在消息中使用该变量来显示代码覆盖率。
以下是一个示例工作流程的代码:

name: Report Code Coverage
on:
  pull_request:
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 12.x
        uses: actions/setup-node@v1
        with:
          node-version: 12.x
      - name: Install dependencies
        run: npm ci
      - name: Run tests
        run: npm run test:coverage
      - name: Get code coverage
        id: coverage
        run: |
          coverage=$(awk '/^Lines/ { print $2 }' < coverage.txt)
          echo "::set-output name=coverage::$coverage"
      - uses: mshick/add-pr-comment@v1
        with:
          message: |
            **Code Coverage: ${{ steps.coverage.outputs.coverage }}**
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          repo-token-user-login: 'github-actions[bot]'
          allow-repeats: false

在上面的示例中,我们添加了一个名为Get code coverage的步骤,该步骤运行了您的bash命令,并将输出存储在一个名为coverage的变量中。然后,我们使用::set-output语法将该变量的值设置为一个输出,以便在后续步骤中使用。最后,在消息中使用${{ steps.coverage.outputs.coverage }}来显示代码覆盖率。

方案2

如果您只是想将文件的内容转储到消息中,而不需要对其进行处理,您可以使用cat命令将文件的内容读取到一个变量中,并在消息中使用该变量来显示文件的内容。
以下是一个示例工作流程的代码:

name: Report Code Coverage
on:
  pull_request:
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 12.x
        uses: actions/setup-node@v1
        with:
          node-version: 12.x
      - name: Install dependencies
        run: npm ci
      - name: Run tests
        run: npm run test:coverage
      - name: Get file content
        id: file
        run: |
          content=$(cat coverage.txt)
          echo "::set-output name=content::$content"
      - uses: mshick/add-pr-comment@v1
        with:
          message: |
            **File Content: ${{ steps.file.outputs.content }}**
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          repo-token-user-login: 'github-actions[bot]'
          allow-repeats: false

在上面的示例中,我们添加了一个名为Get file content的步骤,该步骤使用cat命令将文件的内容读取到一个名为content的变量中。然后,我们使用::set-output语法将该变量的值设置为一个输出,以便在后续步骤中使用。最后,在消息中使用${{ steps.file.outputs.content }}来显示文件的内容。

正文完