Skip to content

Instantly share code, notes, and snippets.

@moa3
Last active May 14, 2018 22:58
Show Gist options
  • Save moa3/0c73255c370d1bbe7551e3055f0eb790 to your computer and use it in GitHub Desktop.
Save moa3/0c73255c370d1bbe7551e3055f0eb790 to your computer and use it in GitHub Desktop.
Python post-commit hook for Posting github commit URLs on Trello cards
#!/usr/bin/env python3
# Git post-commit hook that
# parses the commit message for a trello card URL
# checks if the core "origin" url of the current repository is a github URL
# POSTs a comment on the aforementioned Trello card with a github link to the commit
# just put this file in your .git/hooks dir
# name it post-commit
# chmod +x .git/hooks/post-commit
# requires python3 and pip3 install dulwich
import os
import os.path
import re
import inspect
from dulwich.repo import Repo
import requests
import configparser
if __name__ == "__main__":
config_file = '%s/trello.cfg' % os.path.dirname(os.path.abspath(__file__))
if os.path.isfile(config_file):
config = configparser.ConfigParser()
config.read(config_file)
trello_auth = config['Auth']
else :
print(inspect.cleandoc("""
Trello config file not found.
Get an app key from https://trello.com/app-key
Use it to generate a token from https://trello.com/1/authorize?expiration=never&scope=read,write,account&response_type=token&name=Server%20Token&key=yourTrelloKey
Create the file .git/hooks/trello.cfg
with the following content
[Auth]
key: yourTrelloKey
token: yourTrelloToken
"""))
quit()
r = Repo('.')
config = r.get_config()
repo_url = config.get(('remote', 'origin'), 'url').decode()
url_match = re.match(r'.*github.com[:\/]([^\/]*)\/([^\.]+)\.git', repo_url)
if url_match:
project_org = url_match.group(1)
project_name = url_match.group(2)
else :
quit()
headHash = r.head()
commit = r[headHash]
match = re.match(r'.*https:\/\/trello\.com\/c\/(.+)\/([^\s]*)', commit.message.decode(), re.S)
if match:
card_url = "https://api.trello.com/1/cards/%s/actions/comments" % match.group(1)
querystring = {
"text":"https://github.com/%s/%s/commit/%s" % (project_org, project_name, headHash.decode()),
"key":trello_auth['key'],
"token":trello_auth['token']}
response = requests.request("POST", card_url, params=querystring)
if response.status_code == 200:
print("Trello card https://trello.com/c/%s/%s updated\n\n" % (match.group(1), match.group(2)))
else :
print("There was a problem accessing the Trello API (%d)" % response.status_code)
else :
quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment