Find a Git tag with a commit

Find a Git tag that contains a commit

At Amedia, we create Git tags that match an container image tag that we use when deploying to snapshot and production.

They can either be found on the GitHub Releases page, or with Git itself on a repository.

Since this is a task I do multiple times a day, I wrote a script for it.

As developers do, we all probably have a way to accomplish the same task. I have not seen anyone share theirs yet, so here is mine.

Basic usage

In general, in case a commit exists on multiple branches, the script will list all of them. The examples below found a single tag that matches. In workflows that use git-merge, more tags will be identified. In git-rebase workflows, there will most often be a single tag.

commit-tag repo [ref] [org]

The repo is required, and ref and org are optional that defaults to HEAD and amedia respectively.

To get the tags that contain the last commit on master in the cmx repo:

$ commit-tag cmx
finding tags for: 40b4b96f26b021425c07cc743af64431326dca63

tags with commit:
master-40b4b96

I can then use master-40b4b96 for app deploy, or whatever else I need it for.

Additional usage

Tags with a specific commit

Since the script accept a ref as well, I can either specify a commit I want the tags for:

$ commit-tag cmx 8942061f074e3a4506f67d0cfce8ccbe325d968a
finding tags for: 8942061f074e3a4506f67d0cfce8ccbe325d968a

tags with commit:
master-8942061

Tags for a branch

As well as specify a branch to get the tags that contain the HEAD commit on that branch:

commit-tag cmx relative-true
finding tags for: eaaf2513a7d68be1cbacc3f4cd8b73861a96e8ce

tags with commit:
relative-true-eaaf251

Source

The script requires jq and gh (the GitHub CLI), and a relatively recent bash (I use 5.2, untested on others).

#!/bin/bash

repo="$1"
ref="${2:-HEAD}"
org=${3:-amedia}

sha=$(gh api \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  "/repos/$org/$repo/commits/$ref" \
  | jq --raw-output '.sha'
)

echo "finding tags for: $sha"

tags=$(gh api \
  --paginate \
  -H "Accept: application/vnd.github+json" \
  -H "X-GitHub-Api-Version: 2022-11-28" \
  "/repos/$org/$repo/tags" \
  | jq --raw-output --arg sha "$sha" '.[] | select(.commit.sha == $sha) | .name'
)

echo ""

if [[ -n "$tags" ]]; then
  echo "tags with commit:"
  for tag in "${tags[@]}"; do
      echo "$tag"
  done
else
  echo "no tags with commit found"
fi

Hope it helps !

/v.