#!/usr/bin/python3 # gentoo-infra: infra/githooks.git:local/gentoo_push_notification.py import hmac import sys import urllib.request import urllib.error import urllib.parse import json import time # rough json format; # dict(project=name, # repo_url=RO-checkout-url, # timestamp=epoch (integer) # updates_count=2, # updates=[ # dict(old="rev1", new="rev2", branch=name]), # dict(old="rev3", new="rev4") # ] # ) # finally, the string content of that is stuck into a # header named; Gentoo-Hook-HMAC; # this is done to allow simple validation that someone # isn't being a bastard. HMAC_HEADER = "Gentoo-Hook-HMAC" def convert_stdin(): d = {} updates = d["updates"] = [] for line in sys.stdin: old_ref, new_ref, name = line.split(None, 2) if not name.startswith("refs/heads/"): continue name = name.split("/", 2)[2].rstrip() updates.append(dict(old=old_ref, new=new_ref, branch=name)) i = d["updates_count"] = len(d["updates"]) if not i: # the hell? return {} d["timestamp"] = int(time.time()) return d def main(submit_url, hmac_key, project_name, checkout_url, timeout=None): data = convert_stdin() if not data: return 0 data["repository_url"] = checkout_url data["project"] = project_name data_s = json.dumps(data) chksum = hmac.new(hmac_key, msg=data_s).hexdigest() request = urllib.request.Request(submit_url, data_s, {HMAC_HEADER:chksum}) try: if timeout is not None: result = urllib.request.urlopen(request, timeout=float(timeout)) else: result = urllib.request.urlopen(request) except Exception as e: print("exception occured: %s" % (e,)) return 2 code = result.getcode() if code != 200: print(code) return 1 return 0 if __name__ == '__main__': sys.exit(main(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], timeout=sys.argv[5]))