Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Forked from bartoszmajsak/prepare-commit-msg.sh
Last active May 11, 2016 15:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mgaitan/f20e27a7a146874d3c33 to your computer and use it in GitHub Desktop.
Save mgaitan/f20e27a7a146874d3c33 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
no more embarrasing "removed pdb, sorry" commits
install
-------
save it as .git/hooks/pre-commit giving +x permission
"""
import sys
from subprocess import Popen, PIPE
proc = Popen(['git', 'grep', '-E', '-n', '[ ;]i?pdb'], stdout=PIPE)
pdb_check, _ = proc.communicate()
if proc.returncode == 0:
print("\033[31mPdb breakpoint found, shame on you! Please remove before commiting.\033[39m")
print(pdb_check)
sys.exit(-1)
#!/usr/bin/env python
"""
This script, used as a git's prepare-commit-msg hook, parse the current branch name
to extract issues IDs, (like XYZ-123) and mention that in the commit message.
It's particularly useful to integrate Stash and Jira
Install
-------
Just save it as .git/hooks/prepare-commit-msg in your repo and make the file executable.
"""
import re
import sys
import subprocess
excluded_branches = ['master', 'develop']
def expand(issue):
"""
a helper that expands a shortcut format used in some branch names
like XYZ-12+45 which stands for a branch related both to the issue
XYZ-12 and XYZ-45.
>>> expand('XX-12+45')
'XX-12 XX-45'
"""
if '+' not in issue:
return issue
key = issue.split('-')[0]
return ' '.join([("{}-{}".format(key, i) if not i.startswith(key) else i)
for i in issue.split('+')])
def main():
try:
current_branch = subprocess.check_output(['git', 'symbolic-ref', '--short', 'HEAD']).strip()
if not current_branch or current_branch in excluded_branches:
return
except subprocess.CalledProcessError:
return
# read the original commit message
with open(sys.argv[1]) as msg_file:
original = msg_file.read()
# only issues in branch not already mentioned in the branch name.
# useful to ignore repeated mention on rebases.
issues_mentioned = [issue for issue in re.findall(r'[A-Z]+\-[0-9+]+', current_branch)
if issue not in original]
if not issues_mentioned:
# if no issue were mentioned, leave the original commit message
return original
issues_mentioned = ' '.join(map(expand, issues_mentioned))
msg = "{}: {}".format(issues_mentioned, original)
with open(sys.argv[1], 'w') as msg_file:
msg_file.write(msg)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment