user1074891
user1074891

Reputation: 289

How can I find the most recent tag across all branches in a git repo?

I'd like to know how can I find the most recent tag across all branches in a git repo.

I've tried using the following command, but this only appears to check on the current branch:

git describe --abbrev=0 --tags | sed 's/[^0-9.]*//g'

I'd like to check all branches however.

Upvotes: 3

Views: 79

Answers (2)

Sam H
Sam H

Reputation: 879

I use this script in PowerShell to find the most recent tag. (Note that this doesn't check whether the tag is associated with a branch.)

# Out of all the tags, sorted oldest-to-newest...
git for-each-ref --sort=creatordate --format '%(refname)' refs/tags `
    # Strip off the "refs/tags/" part of the name...
    | split-path -Leaf `
    # Take just the newest one.
    | Select-Object -Last 1

Upvotes: 0

ElpieKay
ElpieKay

Reputation: 30858

Here's a script in bash.

#!/bin/bash

#list all the tags 
git for-each-ref --shell refs/tags |
  awk '{
#transform the object name into the commit date as a Unix epoch timestamp 
    "git log -1 --pretty=%cd --date=unix "$1 | getline $1;
#if the tag does not refer to a commit, ignore it
    if($0 ~ /^[0-9a-f]/) print;
#sort by the timestamp reversely, from the youngest to the oldest
  }' | sort -r |
#get the first youngest tag
  head -1 | awk '{print $NF}' |
#get all the tags that point at this tag in case there are multiple youngest tags, 
#with a side effect to remove "refs/tags/"
  xargs -i git tag --points-at {}

One-line version:

git for-each-ref --shell refs/tags | awk '{"git log -1 --pretty=%cd --date=unix "$1 | getline $1;if($0 ~ /^[0-9a-f]/) print;}' | sort -r |head -1 | awk '{print $NF}' | xargs -i git tag --points-at {}

If you are using Git before v2.9.4, use --date=iso instead of --date=unix. With --date=iso there might be a bug that the timestamps can't be sorted as expected due to time zones. But I think it's rare to happen.

Upvotes: 1

Related Questions