Skip to content

Instantly share code, notes, and snippets.

@yeger00
Last active September 24, 2020 05:41
Show Gist options
  • Save yeger00/c7cf1d1be5578372fd08484c82c5c749 to your computer and use it in GitHub Desktop.
Save yeger00/c7cf1d1be5578372fd08484c82c5c749 to your computer and use it in GitHub Desktop.
#!/bin/bash
# This script prints the "version" of the repository.
# The defenition of version is:
# If there is a tag points to the current commit - the prefix will be the tag. If not, it will be the current commit.
# If the repository is dirty, it will add "-dirty" as suffix.
# Examples:
# Tag and not dirty: v1.2.3
# Tag and dirty: v1.2.3-dirty
# Not a tag and not dirty: 3cccdf4a163d0b9fea760d5de83ad2ed23dc938d
# Not a tag and dirty: 3cccdf4a163d0b9fea760d5de83ad2ed23dc938d-dirty
_is_repo()
{
git branch > /dev/null 2>&1;
if [ $? -eq 0 ]; then
return;
fi
false;
}
_is_clean()
{
git status | grep -q "nothing to commit" ;
if [ $? -eq 0 ]; then
return;
fi
false;
}
_get_commit()
{
local commit=`git rev-parse HEAD` 2> /dev/null;
echo "$commit"
}
_get_tag()
{
local commit=$1
local tag=`git describe --exact-match $commit 2> /dev/null` ;
echo "$tag";
}
get_repo_version()
{
if ! _is_repo; then
>&2 echo "Not git repository"
exit 1;
fi
tag=$(_get_tag);
if [ -z $tag ]; then
version=$(_get_commit)
else
version=$tag
fi
if ! _is_clean; then
version=$version-dirty
fi
echo $version
}
BASH_SOURCE=".$0" # cannot be changed in bash
test ".$0" != ".$BASH_SOURCE" || get_repo_version
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment