Skip to content

Instantly share code, notes, and snippets.

@tilleryd
Created August 5, 2017 17:40
Show Gist options
  • Save tilleryd/1b0f2e1497cb243dd93de0343855e0b5 to your computer and use it in GitHub Desktop.
Save tilleryd/1b0f2e1497cb243dd93de0343855e0b5 to your computer and use it in GitHub Desktop.
git pre-commit hook for setting CircleCI badge for current branch
#!/usr/bin/python
"""
Referencing current branch in github readme.md[1]
This pre-commit hook[2] updates the README.md file's
CircleCI 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://circleci.com/docs/1.0/status-badges/
[4] https://gist.github.com/dandye/dfe0870a6a1151c89ed9
"""
import subprocess
# Hard-Coded for your repo (ToDo: get from remote?)
GITHUB_ORGANIZATION="github org or user"
REPO="repo"
CIRCLECI_ACCESS_TOKEN=""
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)
# [![CircleCI](https://circleci.com/gh/user/repo/tree/master.svg?style=shield
# &circle-token=123456789)](https://circleci.com/gh/user/repo/tree/master)
# Output String with Variable substitution
circle="[![CircleCI](https://circleci.com/gh/" \
"{GITHUB_ORGANIZATION}/{REPO}/tree/" \
"branch={BRANCH}.svg?style=shield&circle-token={CIRCLECI_ACCESS_TOKEN})" \
"(https://circleci.com/gh/{GITHUB_ORGANIZATION}/{REPO}/tree/{BRANCH})][circle]\n".format(BRANCH=BRANCH,
GITHUB_ORGANIZATION=GITHUB_ORGANIZATION,
REPO=REPO,
CIRCLECI_ACCESS_TOKEN=CIRCLECI_ACCESS_TOKEN)
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