Skip to content

Instantly share code, notes, and snippets.

@dandye
Last active January 14, 2023 09:30
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dandye/dfe0870a6a1151c89ed9 to your computer and use it in GitHub Desktop.
Save dandye/dfe0870a6a1151c89ed9 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/pre-commit` (without the .py extension)
#!/usr/bin/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
[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/
"""
import subprocess
# Hard-Coded for your repo (ToDo: get from remote?)
GITHUB_USER="joegattnet"
REPO="joegattnet_v3"
print "Starting pre-commit hook..."
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="[![Build Status](https://travis-ci.org/" \
"{GITHUB_USER}/{REPO}.png?" \
"branch={BRANCH})][travis]\n".format(BRANCH=BRANCH,
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."
@jclaveau
Copy link

jclaveau commented Jun 10, 2021

I updated your work here to handle much more case and support Python 3.

I also added a license so authors are protected. Please tell me if GPL v3 doesn't suit you.

https://gist.github.com/jclaveau/af2271b9fdf05f7f1983f492af5592f8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment