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

如何在GitHub Action中仅获取PR最新提交的变更文件?

如何在GitHub Action中仅获取PR最新提交的变更文件

调整现有tj-actions/changed-files配置解决问题

默认情况下,该Action在PR触发时会对比PR目标分支与源分支的全量差异,要获取仅最新提交的变更文件,需修改配置指定对比范围:

on: pull_request 
jobs:
  get-latest-changes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0  # 拉取完整提交历史,确保能访问到上一次提交
          ref: ${{ github.event.pull_request.head.ref }}  # 切换到PR源分支

      - name: 获取最新提交的变更文件
        uses: tj-actions/changed-files@v35
        id: changed-files
        with:
          base_sha: ${{ github.event.pull_request.head.sha }}~1  # 最新提交的父提交
          head_sha: ${{ github.event.pull_request.head.sha }}     # PR源分支的最新提交

      - name: 输出变更文件
        run: echo "变更文件列表:${{ steps.changed-files.outputs.all_changed_files }}"

替代方案推荐

1. 直接用Git命令(无需第三方Action)

如果不想依赖第三方Action,可直接通过Git命令获取变更文件:

on: pull_request 
jobs:
  get-latest-changes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 2  # 仅需拉取最近2次提交即可对比
          ref: ${{ github.event.pull_request.head.ref }}

      - name: 提取变更文件
        id: changed-files
        run: |
          # 将变更文件列表转为空格分隔的字符串存入输出变量
          echo "all_changed_files=$(git diff --name-only HEAD~1 HEAD | tr '\n' ' ')" >> $GITHUB_OUTPUT

      - name: 输出变更文件
        run: echo "变更文件列表:${{ steps.changed-files.outputs.all_changed_files }}"

2. 使用dorny/paths-filter Action

该Action不仅能获取变更文件,还支持按路径过滤,适合需要针对性执行后续逻辑的场景:

on: pull_request 
jobs:
  check-changes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 2
          ref: ${{ github.event.pull_request.head.ref }}

      - uses: dorny/paths-filter@v2
        id: filter
        with:
          base: HEAD~1
          head: HEAD
          filters: |
            src_files:
              - 'src/**/*'
            docs_files:
              - 'docs/**/*'

      - name: 若源码变更则执行
        if: steps.filter.outputs.src_files == 'true'
        run: echo "源码目录有变更,执行编译逻辑"

      - name: 若文档变更则执行
        if: steps.filter.outputs.docs_files == 'true'
        run: echo "文档目录有变更,执行部署逻辑"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:52:51