Skip to content

Instantly share code, notes, and snippets.

@DrSAR
Forked from dandye/pre-commit.py
Last active June 11, 2016 07:16
Show Gist options
  • Save DrSAR/eb50d9b2b993384267db4ee9fd5e210f to your computer and use it in GitHub Desktop.
Save DrSAR/eb50d9b2b993384267db4ee9fd5e210f to your computer and use it in GitHub Desktop.
pre-commit hook to re-write the TravisCI Badge with the current branch. Save as `.git/hooks/prepare-commit-msg` (without the .py extension)
#!/usr/bin/env python
"""
Referencing current branch in github readme.md[1]
This pre-commit hook[2] updates the README.md file's
Travis badge with the current branch. Gist at[4].
[1] http://stackoverflow.com/questions/18673694/referencing-current-branch-in-github-readme-md
[2] http://www.git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
[3] https://docs.travis-ci.com/user/status-images/
[4] https://gist.github.com/DrSAR/eb50d9b2b993384267db4ee9fd5e210f
"""
import subprocess
import re
# Hard-Coded for your repo (ToDo: get from remote?)
REPOurl=subprocess.check_output(['git','config','--local', 'remote.origin.url']).decode()
GITHUB_USER=re.match('.*:([a-zA-Z0-9]*)\/', REPOurl).groups()[0]
REPO=re.match('.*\/([a-zA-Z0-9]*).git', REPOurl).groups()[0]
print("Starting pre-commit hook for {0} on {1}...".format(GITHUB_USER, REPO))
BRANCH=subprocess.check_output(["git",
"rev-parse",
"--abbrev-ref",
"HEAD"]).strip()
# String with hard-coded values
# See Embedding Status Images[3] for alternate formats (private repos, svg, etc)
# [![Build Status](https://travis-ci.org/
# joegattnet/joegattnet_v3.png?
# branch=staging)][travis]
# Output String with Variable substitution
travis="###branch: {BRANCH} [![Build Status](https://travis-ci.org/" \
"{GITHUB_USER}/{REPO}.svg?" \
"branch={BRANCH})](https://travis-ci.org/{GITHUB_USER}/{REPO})\n".format(BRANCH=BRANCH.decode(),
GITHUB_USER=GITHUB_USER,
REPO=REPO)
sentinal_str="[![Build Status]"
readmelines=open("README.md").readlines()
with open("README.md", "w") as fh:
for aline in readmelines:
if sentinal_str in aline and travis != aline:
print("Replacing:\n\t{aline}\nwith:\n\t{travis}".format(
aline=aline,
travis=travis))
fh.write(travis)
else:
fh.write(aline)
subprocess.check_output(["git", "add", "README.md" ])
print("pre-commit hook complete.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment