AX Semantics Developer Blog
  • Home
  • Categories
  • Tags
  • Archives

git - Prepare commit msg

Problem

Every now and then you forget a print statement in your Python code. Why not add a note below the prepared commit message with all the prints you have added. Maybe you want to keep some of them.

How to add a prepare-commit-msg

We have lots of repositories and this hook should be run in all of them.

So add a global hook template:

git config --global init.templatedir '~/.git-templates'

and create a hooks folder:

mkdir -p ~/.git-templates/hooks

now add the prepare-commit-msg to find prints added in this current commit:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/bin/bash
root=$(git rev-parse --show-toplevel)
orig_msg_file="$root/$1"
tmp_basename=/tmp/git-precommit-print-hook
files=$(git status --porcelain --untracked-files=no | cut -c4- | grep -E '\.py$')
if [ -n "$files" ]; then
    msgs=$(grep -HEn '^\s* print' $files)
fi
if [ -n "$msgs" ]; then
    msg_file=$(mktemp "$tmp_basename-XXXX")
    cat $orig_msg_file >> $msg_file
    echo "# " >> $msg_file
    echo "# found print messages:" >> $msg_file
    echo "$msgs" | sed 's/^/#   /' >> $msg_file
    mv -f $msg_file $orig_msg_file
fi
exit 0

and set execute rights to file:

chmod a+x ~/.git-templates/hooks/prepare-commit-msg

This template is now used for every new git repository. But we want the old ones using it too.

To add hooks from the template folder to an existing repository run git init and the are updated if they don't exist already.

Tell us what you think about this. Is something unclear? Do you have questions or ideas? Leave your comments below.

Comments
comments powered by Disqus

  • « Django and Postgres' jsonb field beyond the basics

Published

Feb 7, 2017

Category

Techstack

Tags

  • git 1
  • python 8
  • AX Semantics Developer Blog - Technical stuff and learnings we had while developing the AX environment
  • Powered by Pelican. Theme: Elegant by Talha Mansoor