Last active
September 5, 2024 08:44
-
-
Save jonasbn/11f1630d56dccbdc516a53209e991d7f to your computer and use it in GitHub Desktop.
Basic Perl script to sort semantic version numbers outputted from git tag command
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!perl | |
use warnings; | |
use strict; | |
use Data::Dumper; | |
use Getopt::Long; | |
my $reverse; | |
GetOptions ('reverse' => \$reverse) # flag | |
or die("Error in command line arguments\n"); | |
# read all from standard input | |
my @tags = <STDIN>; | |
# remove newlines | |
chomp @tags; | |
my @sorted_tags = sort { | |
($b =~ /v?(\d+)\.\d+\.\d+/)[0] <=> ($a =~ /v?(\d+)\.\d+\.\d+/)[0] | |
|| | |
($b =~ /v?\d+\.(\d+)\.\d+/)[0] <=> ($a =~ /v?\d+\.(\d+)\.\d+/)[0] | |
|| | |
($b =~ /v?\d+\.\d+\.(\d+)/)[0] <=> ($a =~ /v?\d+\.\d+\.(\d+)/)[0] | |
|| | |
fc($a) cmp fc($b) | |
} @tags; | |
# print sorted tags to standard output on separate lines | |
if ($reverse) { | |
print join("\n", reverse @sorted_tags), "\n"; | |
} else { | |
print join("\n", @sorted_tags), "\n"; | |
} | |
exit 0; | |
__END__ | |
=pod | |
=head1 USAGE | |
Normal usage with C<git tag>: | |
git tag|sort_semantic_version_numbers.pl | |
v0.13.1 | |
v0.13.0 | |
v0.12.0 | |
v0.11.0 | |
v0.10.0 | |
v0.9.0 | |
v0.8.0 | |
v0.7.0 | |
0.6.1 | |
0.6.0 | |
0.5.0 | |
0.4.0 | |
0.3.1 | |
0.3.0 | |
0.2.0 | |
0.1.0 | |
Reverse listing also with C<git tag>: | |
git tag|sort_semantic_version_numbers.pl --reverse | |
0.1.0 | |
0.2.0 | |
0.3.0 | |
0.3.1 | |
0.4.0 | |
0.5.0 | |
0.6.0 | |
0.6.1 | |
v0.7.0 | |
v0.8.0 | |
v0.9.0 | |
v0.10.0 | |
v0.11.0 | |
v0.12.0 | |
v0.13.0 | |
v0.13.1 | |
The shortform of C<--reverse> is C<-r>. | |
=head2 NOTES | |
Semantic version numbers can have the C<v> prefix, is does not interfere with the sorting. | |
=head1 AUTHOR | |
=over | |
=item jonasbn | |
=back | |
=head1 LICENSE | |
MIT | |
=head1 COPYRIGHT | |
2024, jonasbn | |
=cut |
GNU sort has a special parameter for sorting versions:
git tag | sort -r --version-sort
Awesome, thanks @jpralves I am on macOS, but I can install coreutils via Homebrew
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GNU sort has a special parameter for sorting versions: