Check if there are new commits since the latest tag

Viewed 816

Currently I have the following GitHub workflow for tagging nightly snapshots on the master branch of a repository:

name: Nightly Snapshot

on:
  schedule:
  - cron: "0 0 * * *"

jobs:
  tag:
    name: Tag
    runs-on: linux-latest
    steps:
      - name: Checkout master branch
        uses: actions/checkout@v2
        with:
          ref: 'master'
      - name: Get current date
        id: date
        run: echo "::set-output name=date::$(date +'%Y-%m-%d')"
      - name: Tag snapshot
        uses: tvdias/github-tagger@v0.0.1
        with:
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          tag: ${{ steps.date.outputs.date }}

However, there aren't always new commits to the master branch. I want to modify the workflow to only create new tags if there are new commits after when the latest tag was created. How should I do it?

2 Answers

This should be enough to get you on the right lines, i haven't tested the code but the ideas are all there.

  1. Get the SHA to your current master
      - name: Get Git SHA
        id: gitsha
        run: echo "::set-output name=gitsha::$(git rev-parse HEAD)"
  1. Fetch all tags
- uses: actions/checkout@v2
- run: git fetch --depth=1 origin +refs/tags/*:refs/tags/*
  1. Get the last tag that was created, by getting yesterdays date then getting that tag and outputting the commit SHA
      - name: Get yesterdays date
        id: ydate
        run: echo "::set-output name=ydate::$(date -d "yesterday 13:00" +'%Y-%m-%d')"
      - uses: actions/checkout@v2
        with:
          ref: refs/tags/${{ steps.ydate.outputs.ydate }}
      - name: Get Yesterdays Git SHA
        id: ygitsha
        run: echo "::set-output name=ygitsha::$(git rev-parse HEAD)"
  1. If they are the same don't do another deploy
      - name: Deploy if anything has changed
        if: steps.ygitsha.outputs.ygitsha == steps.gitsha.outputs.gitsha
        run: <your code>

Sounds like you might also want to loop and check the existence of tags until you find the last one, in that case simply keep subtracting 1 more from the date and use something like this to check if the tag exists and loop until you find a tag.

if git rev-parse "$TAG" >/dev/null 2>&1; then
  echo "tag exists";
else
  echo "tag does not exist"
fi

Refer this. This workflow will trigger the deploy only when a tag deployment is pushed. Although, the build will be triggered with every commit in master.

Related