运行 仅当上一步有 运行 时才执行 GitHub 操作步骤

Running a GitHub Actions step only if previous step has run

我已经在 GitHub 操作中为 运行 我的测试设置了一个工作流,并创建了一个测试覆盖率的工件。我的 YAML 文件的精简版本如下所示:

name: Build

on: [pull_request]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      # Other steps here

      - name: Build app
      - name: Run tests
      - name: Create artifact of test coverage

      # Other steps here

问题是测试失败时不会创建工件。

我从 docs 中找出了关于 if: always() 的条件,但是当我的 Build app 步骤失败时,这也会导致此步骤变为 运行。我不希望发生这种情况,因为在那种情况下没有什么可存档的。

如果上一步有运行(成功或失败),我怎么才能只运行这一步?

尝试检查 success()failure().

name: Build

on: [pull_request]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      # Other steps here

      - name: Build app
      - name: Run tests
      - name: Create artifact of test coverage
        if: success() || failure()

      # Other steps here

或者,创建退出代码的步骤输出,您可以在后面的步骤中检查。例如:

      - name: Build app
        id: build
        run: |
          <build command>
          echo ::set-output name=exit_code::$?

      - name: Run tests

      - name: Create artifact of test coverage
        if: steps.build.outputs.exit_code == 0

可能更好的选择是 <step>.outcome<step>.conclusion

https://docs.github.com/en/actions/learn-github-actions/contexts#steps-context

steps.<step id>.conclusion. The result of a completed step after continue-on-error is applied. Possible values are success, failure, cancelled, or skipped. When a continue-on-error step fails, the outcome is failure, but the final conclusion is success.

steps.<step id>.outcome The result of a completed step before continue-on-error is applied. Possible values are success, failure, cancelled, or skipped. When a continue-on-error step fails, the outcome is failure, but the final conclusion is success.

  - name: Build app
    id: build
    run: |
      <build command>

  - name: Run tests

  - name: Create artifact of test coverage
    if: steps.build.outcome == 'success'