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

如何仅对GitHub PR中的文件运行Pylint代码检查

解决方案

要在Windows环境的GitHub Actions中,让Pylint仅检查Pull Request中的变更Python文件,需修改Workflow的两个关键部分:

1. 完整拉取仓库历史

默认的actions/checkout@v2仅拉取当前分支的最新提交,无法对比PR的基准分支。需添加fetch-depth: 0获取完整仓库历史:

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

2. 替换Pylint执行命令

在Windows环境下使用PowerShell脚本,根据事件类型判断执行逻辑:PR事件仅检查变更文件,非PR事件保持检查所有文件。修改后的Lint步骤如下:

- name: Lint with Pylint
  run: |
    if ($env:GITHUB_EVENT_NAME -eq 'pull_request') {
      # 获取PR中变更的Python文件(过滤添加/修改/重命名等类型文件)
      $changedFiles = git diff --name-only --diff-filter=ACMRT origin/${{ github.base_ref }}...origin/${{ github.head_ref }} | Where-Object { $_ -like '*.py' }
      if ($changedFiles) {
        pylint $changedFiles
      } else {
        Write-Host "No Python files changed in this PR."
      }
    } else {
      # 非PR事件(如push、手动触发)检查所有Python文件
      pylint (git ls-files '*.py')
    }
  shell: pwsh

命令说明

  • git diff --name-only --diff-filter=ACMRT:仅输出**添加(A)、复制(C)、修改(M)、重命名(R)、类型变更(T)**的文件路径,排除已删除文件(无需检查)。
  • Where-Object { $_ -like '*.py' }:过滤出仅Python格式的文件。
  • shell: pwsh:指定使用PowerShell执行脚本,确保Windows环境下语法兼容。

完整修改后的Workflow文件

name: Python Linting
on:
  push:
    branches: [master]
  pull_request:
  workflow_dispatch:
jobs:
  build:
    runs-on: windows-latest
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install pylint
      - name: Lint with Pylint
        run: |
          if ($env:GITHUB_EVENT_NAME -eq 'pull_request') {
            $changedFiles = git diff --name-only --diff-filter=ACMRT origin/${{ github.base_ref }}...origin/${{ github.head_ref }} | Where-Object { $_ -like '*.py' }
            if ($changedFiles) {
              pylint $changedFiles
            } else {
              Write-Host "No Python files changed in this PR."
            }
          } else {
            pylint (git ls-files '*.py')
          }
        shell: pwsh

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:17:59