如何在Github Actions中运行git diff

21

我得到了这个:

Command failed: git diff --name-only HEAD^..HEAD
fatal: ambiguous argument 'HEAD^..HEAD': unknown revision or path not in the working tree.

我想在我的分支中运行 git diff --name-only HEAD^..HEAD 以获取已更改文件的列表。这在本地上有效,但在GitHub actions上无效。我该怎么做?

我的代码是这样的:

name: build
on:
  push:
    branches:
      - main
jobs:
  run:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
      - name: Configure Node.js
        uses: actions/setup-node@v2
        with:
          node-version: 14.x
      - name: Install dependencies
        run: yarn install
      - name: Publish file changes to Slack
        # HERE I run `git diff` in node.js process
        run: "SLACK_TOKEN=${{ secrets.GITHUB_TOKEN }} npx ts-node scripts/publishSlackUpdate"
      - name: Build TOC
        run: make toc
      - name: Commit build changes
        uses: EndBug/add-and-commit@v7
        with:
          author_name: Docs Builder
          author_email: docs@mysite.com
          message: 'Updated build'
          add: '*.md'

你在 action 中检查了你的代码库吗?如果你能展示出失败的工作流,我们就可以更容易地帮助你。 - larsks
我无法展示失败的工作流程,因为它是私有仓库。不,我没有检出它,我该怎么做?它在一个特定的分支上,即当前的PR分支。我的配置已经更新。 - alien
“失败的工作流”是指您发布的工作流定义。谢谢!看起来您已经通过actions/checkout@v2操作检查了存储库。让我看看能否重现故障... - larsks
3个回答

32

如果您查看 actions/checkout@v2 操作的文档,您会发现它默认执行浅克隆,只有一个修订版本:

    # Number of commits to fetch. 0 indicates all history for all branches and tags.
    # Default: 1
    fetch-depth: ''

因为它只获取一个修订版本,所以没有HEAD^

您可以通过在检出操作上设置fetch-depth选项来解决此问题。将其设置为0将获取整个历史记录;或者,针对您要执行的操作,您可能只需将其设置为2

    steps:
      - name: Checkout repo
        uses: actions/checkout@v2
        with:
          fetch-depth: 2

3
设置为0将获取完整的历史记录。 - larsks
1
我试过了,但它不起作用。他们还说这似乎是不可能的 https://github.com/actions/checkout/issues/161 ‍♂️ - hrdwdmrbl
@larsks 我没有看到你在你的两个工作流程 test-and-publish.yml 和 test-only.yml 中运行 git diff 的地方。 - hrdwdmrbl
2
@hrdwdmrbl 我为你制作了一个完整的示例[在这里](https://github.com/larsks/so-example-hrdwdmrbl)(我获取了GNU hello存储库并添加了一个工作流示例)。 - larsks
@larsks 好的,我复制了你的代码出现的问题。如果您指定特定的提取深度,则无法正常工作。请查看 - hrdwdmrbl
显示剩余3条评论

15

在分支名称前加上origin/对我有用。

git diff --name-only origin/main origin/${GITHUB_HEAD_REF}

我也有同样的情况。不确定为什么他们要强制执行这个规定。 - C Deepak
2
具体来说,我需要对比 'main' 分支的 git diff,因此在 checkout 时仍需要设置 fetch-depth: 0。此外,我还需要将我的 diff 设置为 origin/main。我假设拥有所有历史记录并不包括分支引用? - Windgazer
在一个环境中这对我起作用了。然后在另一个环境中它没有起作用,我不得不从特性分支中删除origin/。真的很奇怪为什么没有一致性。 - crazyPen

0

您可以使用jitterbit/get-changed-files GA操作:

- id: files
  uses: jitterbit/get-changed-files@v1
- run: |
    for changed_file in ${{ steps.files.outputs.all }}; do
      echo "Do something with this ${changed_file}."
    done

我找到了另一个没有被放弃并且具有相同功能的操作:tjactions/changed-files - Lea Reimann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接