How to move a git tag using GitHub Actions

Forketyfork
Level Up Coding
Published in
3 min readJan 25, 2021

--

Image by Prettysleepy from Pixabay

Sometimes you may want to move or advance a tag as part of your GitHub Actions pipeline.

First, make sure you know what you’re doing — moving tags in a git repository is generally a bad idea, since it may mess with other people’s repositories and incur non-reproducible build and deployment issues. However, there are some workflows and cases that justify moving tags.

For instance, you may have a latest, or a nightly tag in your repository, which you use to execute a nightly build.

If you want to manually move a tag using your local development environment, this would be as simple as:

# delete the tag both locally and in the origin remote
git tag -d nightly
git push origin :nightly
# recreate the tag at the new location
git tag nightly
git push origin nightly

But manual work is no fun. Let’s try to automate it using GitHub Actions.

First, we’re going to create a new advance-nightly-tag.yaml file and put it into our .github/workflows folder. For testing purposes, let’s just trigger it on push:

name: "advance nightly tag"
on:
push:
jobs:
advanceNightlyTag:
runs-on: ubuntu-latest

There will be a single step using the actions/github-script action:

steps:
- name: Advance nightly tag
uses: actions/github-script@v3
with:
github-token: ${{secrets.GITHUB_TOKEN}}
script: |

Inside the script section, we may basically write any JavaScript code. We’re going to use oktokit/rest.js which is made available inside this script under by github-script, under the variable name github. It allows us to call into GitHub API using JavaScript. Here’s a call that would remove a nightly tag:

github.git.deleteRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: "tags/nightly"
})

And here’s a call that would create it anew, note the context.sha parameter that points to the current commit:

github.git.createRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: "refs/tags/nightly",
sha: context.sha
})

--

--

Software developer @ JetBrains Space. I write technical how-to articles and occasional rants on software development in general. Opinions are my own.