如何在每次推送提交时在 GitHub 工作流中运行 commitlint 解决方案演示完整的工作流程

问题描述

我有一个 Github 存储库,在本地安装了 commitlint and 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

我按照常规提交规则又进行了两次提交并开始了拉取请求

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

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

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

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

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

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

解决方法

git rev-list 被认为是因为拉取请求 (PR) 的提交似乎无效。不需要循环。

这个 issue 提示检查 PR 分支,这似乎比获取 PR 提交更简单。从问题来看,似乎不需要在默认分支上进行测试。

- uses: actions/checkout@v2
        with:
          fetch-depth: 0
          ref: ${{ github.event.pull_request.base.sha }}

lint 指令是:

npx commitlint --from ${{ github.event.pull_request.base.sha }} --verbose

pull-request payload 的文档 不立即提供提交列表。

,

解决方案

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

我们需要 base-SHA 以及 head-SHA。在 GitHub 操作中,这些值在 github 上下文中事件的拉取请求对象中可用。

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

npx commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose

演示

这是一个带有 3 个测试用例(拉取请求)的 POC repository on GitHub

完整的工作流程

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