Skip to content

Instantly share code, notes, and snippets.

@shadowmoose
Last active February 22, 2024 14:25
Show Gist options
  • Save shadowmoose/80fd3efecb3930491b2a4ae62b07a6b7 to your computer and use it in GitHub Desktop.
Save shadowmoose/80fd3efecb3930491b2a4ae62b07a6b7 to your computer and use it in GitHub Desktop.
Git pre-commit hook to make sure you incremented your program's internal version variable.
#!/usr/bin/env bash
# Checks the latest release version of your GitHub project, and makes sure the local version variable has been incremented.
# This script will run before any commits happen, and interrupt if the local version has not been incremented since the last release.
# It's intended for use with projects who primarily increment versions around their release schedule.
#
# Requires that GitHub releases use tags that match the internal version. Supports oAuth info in the event of GitHub rate limiting.
# The parsing done in here is super hacky, but it's fast and it works cross-platform with minimal requirements.
# Works with any version tag format you use, and should be runnable on Windows/Linux.
#
# TO USE:
# 1) Save as "pre-commit" (no extension) in your project '.git/hooks/' directory.
# 2) Edit the config variables below.
# ===== CONFIG: ===========
VERSION_FILE='./main.py' # The file, relative to the project base, that contains the current internal version.
VERSION_VAR='__version__' # The name of the variable responsible for holding the version, as it appears within the file.
GH_CLIENT_ID='' # If GitHub throttles you, register an oAuth client and use its ID & Password here.
GH_CLIENT_SECRET='' # (See above). https://github.com/settings/developers
#============================
remote=$(git config --get remote.origin.url)
REPO_OWNER=$(echo "$remote" | cut -d/ -f 4)
REPO_NAME=$(echo "$remote" | cut -d/ -f 5 | cut -d. -f 1)
gh_credentials=""
if [ -n "$GH_CLIENT_ID" ]; then
gh_credentials="client_id=$GH_CLIENT_ID&client_secret=$GH_CLIENT_SECRET"
fi
remote_version=$(curl -s https://api.github.com/repos/$REPO_OWNER/$REPO_NAME/releases/latest?$gh_credentials| sed 's/ //g')
# Tags cannot contain spaces, so strip them out to make using regex on JSON more possible.
array=(${remote_version//,/ })
for i in "${!array[@]}"
do
if [[ "${array[i]}" = *"tag_name"* ]]; then
found_version=$(echo "${array[i]}"| cut -d\" -f 4)
fi
done
if [ -z "$found_version" ]; then
echo "Found no release versions in GitHub's response"
echo "You may be over the limit for API requests?"
exit 2
fi
cat $VERSION_FILE | grep "$VERSION_VAR\s*="| grep $found_version|while read LINE
do
echo "ERROR: The Internal Version has not been incremented since the last release tag!"
echo "Found on line: \"$LINE\""
echo "Remote version: \"$found_version\""
exit 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment