How to run git diff in github actions

Viewed 10232

I am getting this:

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

I want to run git diff --name-only HEAD^..HEAD in my branch to get a list of the files that were changed. It's working locally but not on GitHub actions. What must I do?

My code is this:

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'
2 Answers

If you take a look at the documentation for the actions/checkout@v2 action, you'll see it performs a shallow clone with a single revision by default:

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

Because it only fetches a single revision, there is no HEAD^.

You can fix this by setting the fetch-depth option on the checkout action. Setting it to 0 will fetch the entire history; alternatively, for what you're doing you could probably just set it to 2:

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

Putting origin/ before branch name worked for me

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