如何在每次推送提交时在 GitHub 工作流中运行 commitlint

Que*_*n3r 8 git push pull-request github-actions conventional-commits

我有一个 Github 存储库,在本地安装了commitlint 和 husky,并希望在验证拉取请求时设置一个在每次推送提交时运行 commitlint 的工作流。在主分支上,较旧的提交不遵循传统的提交规则。

我根据此评论创建了一个单独的分支

https://github.com/conventional-changelog/commitlint/issues/586#issuecomment-657226800

我从这个工作流程开始

name: Run commitlint on pull request

on: pull_request

jobs:
  run-commitlint-on-pull-request:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Setup Node
        uses: actions/setup-node@v2
        with:
          node-version: 14.x

      - name: Install dependencies
        run: npm install

      - name: Validate all commits from PR
        run: npx commitlint --from HEAD~${{ github.event.pull_request.commits }} --to HEAD --verbose
Run Code Online (Sandbox Code Playgroud)

我按照传统的提交规则又做了两次提交并开始了拉取请求

  • 我预计工作流不会运行,因为我还不存在于主分支上。
    • 实际上它运行
  • 我期望工作流程只检查 PR 提交
    • 工作流失败,因为它开始验证主分支中的每个提交。而且因为我知道较旧的提交不遵守规则,所以这永远不会通过。

我想到的第一个解决方案是重新设置所有内容并重命名每个提交以遵循规则,但这需要付出巨大的努力。

我不确定我是否必须在这里改进这条线

npx commitlint --from HEAD~${{ github.event.pull_request.commits }} --to HEAD --verbose

仅检查来自 PR 的提交(不幸的是,我不知道需要在那里修复什么)。

您有任何想法或重新定位和重命名唯一的解决方案吗?

Mat*_*att 5

解决方案

直接的解决方案是将commitlint--to--from参数与SHA-1 值一起使用,而不是分支名称或相对引用。一方面,这可靠地解决了工作树中未知修订或路径的问题。另一方面,只会检查 PR 范围内的提交。作为旁注:GitHub 对正在检出的临时合并使用相同的引用 (SHA-1)。

我们需要基础-SHA 以及头部-SHA。在 GitHub 操作中,这些值在github-context 中事件的拉取请求对象中可用。

因此,您可以使用以下经过测试并按预期工作的行:

npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
Run Code Online (Sandbox Code Playgroud)

演示

这是GitHub 上POC 存储库,其中包含 3 个测试用例(拉取请求)。

完整的工作流程

name: Run Commitlint on PR

on:
  pull_request:

jobs:

  run-commitlint-on-pr:
    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Setup Node
        uses: actions/setup-node@v2
        with:
          node-version: 14.x

      - name: Install dependencies
        run: npm install

      - name: Validate all commits from PR
        run: npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
Run Code Online (Sandbox Code Playgroud)