|
| 1 | +#!/usr/bin/env bash |
| 2 | +#-----------------------------------------------------------------------------# |
| 3 | +# Post commit hook that looks for __version__ variable in __init__.py file, |
| 4 | +# compares it to the current tag, and updates the commit if the __version__ was |
| 5 | +# also updated. Copy to .git/hooks/post-commit to add this to any project. |
| 6 | +# See also: https://stackoverflow.com/a/27332476/4970632 |
| 7 | +# See also: https://stackoverflow.com/a/46972376/4970632 |
| 8 | +# This is currently very lightweight and assumes workflow where users |
| 9 | +# manually increment tag number, which is probably appropriate |
| 10 | +#-----------------------------------------------------------------------------# |
| 11 | +# Helper |
| 12 | +raise() { |
| 13 | + echo "Error: $@" |
| 14 | + exit 1 |
| 15 | +} |
| 16 | + |
| 17 | +# Bail if we are in middle of rebase |
| 18 | +base=$(git rev-parse --show-toplevel) |
| 19 | +[ $? -ne 0 ] && raise "Not in git repository." |
| 20 | +[ -d $base/.git/rebase-merge ] && exit 0 |
| 21 | + |
| 22 | +# Get head dir |
| 23 | +init=($(git ls-files | grep __init__.py | grep -v 'tests')) |
| 24 | +[ ${#init[@]} -eq 0 ] && raise "__init__.py not found." |
| 25 | +[ ${#init[@]} -gt 1 ] && raise "Multiple candidates for __init__.py: ${init[@]}" |
| 26 | + |
| 27 | +# Get version string |
| 28 | +version=$(cat $init | grep -E '^version|^__version') |
| 29 | +[ -z "$version" ] && raise "$init version string not found." |
| 30 | +[ $(echo "$version" | wc -l) -gt 1 ] && raise "Ambiguous version string in $init." |
| 31 | +version=$(echo "$version" | awk -F"['\"]" '{print $2}') # first string on line |
| 32 | + |
| 33 | +# Prompt user action |
| 34 | +# NOTE: Currently git suppresses interactivity but that's fine, just means |
| 35 | +# default action of adding tag is taken |
| 36 | +tag=$(git describe --tags $(git rev-list --tags --max-count=1)) |
| 37 | +if [ $? -ne 0 ] || [ "$tag" != "v$version" ]; then |
| 38 | + while true; do |
| 39 | + read -r -p "Increment tag from $tag --> v$version? ([y]/n) " response |
| 40 | + if [ -n "$response" ] && ! [[ "$response" =~ ^[NnYy]$ ]]; then |
| 41 | + echo "Invalid response." |
| 42 | + continue # invalid, so try again |
| 43 | + fi |
| 44 | + if ! [[ "$response" =~ ^[Nn]$ ]]; then |
| 45 | + git tag "v$version" |
| 46 | + [ $? -eq 0 ] && echo "Incremented tag from $tag --> v$version" |
| 47 | + fi |
| 48 | + break |
| 49 | + done |
| 50 | +fi |
0 commit comments