Skip to content

Commit bd406b0

Browse files
committed
black format
1 parent e6559f8 commit bd406b0

File tree

5 files changed

+71
-83
lines changed

5 files changed

+71
-83
lines changed

hooks/__init__.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,29 @@
1-
# -*- coding: utf-8 -*-
21
#
32
import sys
43
import importlib
54

6-
__all__ = ['ping']
5+
__all__ = ["ping"]
76
# CHECKME: import hooks here
87
# from . import ping
98
for hook in __all__:
10-
importlib.import_module('.%s' % hook, 'hooks')
9+
importlib.import_module(".%s" % hook, "hooks")
1110

1211

1312
def get_hooks():
14-
return [k.replace('hooks.', '') for k in list(sys.modules.keys()) if k.startswith('hooks.')]
13+
return [
14+
k.replace("hooks.", "")
15+
for k in list(sys.modules.keys())
16+
if k.startswith("hooks.")
17+
]
1518

1619

1720
def has_hook(hook):
1821
return hook in get_hooks()
1922

2023

2124
def run_hook(hook, payload=None):
22-
mod_name = 'hooks.%s' % hook
25+
mod_name = "hooks.%s" % hook
2326
try:
24-
return getattr(sys.modules[mod_name], 'run')(payload)
27+
return getattr(sys.modules[mod_name], "run")(payload)
2528
except Exception as e:
26-
return {'exception': e}
29+
return {"exception": e}

hooks/ping.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
1-
# -*- coding: utf-8 -*-
21
#
32
import logging
43
import sys
54

65
logging.basicConfig(stream=sys.stderr)
7-
logging.debug('Loading ping')
6+
logging.debug("Loading ping")
87

98

109
def run(payload):
11-
logging.debug('Running ping')
12-
return {'msg': 'pong'}
10+
logging.debug("Running ping")
11+
return {"msg": "pong"}
1312

1413

15-
if __name__ == '__main__':
16-
logging.warning('Main ping')
14+
if __name__ == "__main__":
15+
logging.warning("Main ping")

requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
Flask==1.1.2
1+
Flask==2.0.0
22
ipaddress==1.0.23
33
requests==2.25.1

tests/test_webhooks.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,38 @@
11
import unittest
22
import os
33
import sys
4+
45
# import pytest
56

67
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
78
from webhooks import application as app
89

910

1011
class WebhooksTest(unittest.TestCase):
11-
1212
def setUp(self):
13-
app.config['TESTING'] = True
13+
app.config["TESTING"] = True
1414
self.app = app.test_client()
1515
self.output = False
1616

1717
def show_response(self, response):
1818
if not self.output:
1919
return
20-
print('Status Code: %s' % response.status_code)
20+
print("Status Code: %s" % response.status_code)
2121
print(response.headers)
2222
print(response.data)
2323

2424
def test_unit_get(self):
25-
response = self.app.get('/')
25+
response = self.app.get("/")
2626
self.show_response(response)
2727
self.assertEqual(response.status_code, 405)
2828

2929
def test_unit_post(self):
30-
response = self.app.post('/')
30+
response = self.app.post("/")
3131
self.show_response(response)
3232
self.assertEqual(response.status_code, 200)
3333
self.assertEqual(response.data, b'{"msg":"pong"}\n')
3434

3535
def test_unit_notfound(self):
36-
response = self.app.get('/notfound')
36+
response = self.app.get("/notfound")
3737
self.show_response(response)
3838
self.assertEqual(response.status_code, 404)

webhooks.py

Lines changed: 49 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
#
32
# Copyright (C) 2014, 2015, 2016 Carlos Jenkins <carlos@jenkins.co.cr>
43
#
@@ -34,13 +33,13 @@
3433
try:
3534
from hooks import has_hook, run_hook
3635
except Exception as e:
37-
logging.error('Import hooks failed')
38-
raise(e)
36+
logging.error("Import hooks failed")
37+
raise (e)
3938

4039
application = Flask(__name__)
4140

4241

43-
@application.route('/', methods=['GET', 'POST'])
42+
@application.route("/", methods=["GET", "POST"])
4443
def index():
4544
"""
4645
Main WSGI application entry.
@@ -49,54 +48,50 @@ def index():
4948
path = normpath(abspath(dirname(__file__)))
5049

5150
# Only POST is implemented - same effect as removing 'GET' in methods above
52-
if request.method != 'POST':
51+
if request.method != "POST":
5352
abort(405)
5453

5554
# Load config
56-
if isfile(join(path, 'config.json')):
57-
with open(join(path, 'config.json'), 'r') as cfg:
55+
if isfile(join(path, "config.json")):
56+
with open(join(path, "config.json")) as cfg:
5857
config = loads(cfg.read())
5958
else:
6059
# abort(503, 'Configuration file config.json is missing.')
6160
config = {
6261
"github_ips_only": False,
6362
"enforce_secret": "",
6463
"return_scripts_info": False,
65-
"hooks_path": "/missing"
64+
"hooks_path": "/missing",
6665
}
6766

68-
hooks = config.get('hooks_path', join(path, 'hooks'))
67+
hooks = config.get("hooks_path", join(path, "hooks"))
6968

7069
# Allow Github IPs only
71-
if config.get('github_ips_only', True):
72-
src_ip = ip_address(
73-
u'{}'.format(request.access_route[0]) # Fix stupid ipaddress issue
74-
)
75-
whitelist = requests.get('https://api.github.com/meta').json()['hooks']
70+
if config.get("github_ips_only", True):
71+
src_ip = ip_address(f"{request.access_route[0]}") # Fix stupid ipaddress issue
72+
whitelist = requests.get("https://api.github.com/meta").json()["hooks"]
7673

7774
for valid_ip in whitelist:
7875
if src_ip in ip_network(valid_ip):
7976
break
8077
else:
81-
logging.error('IP {} not allowed'.format(
82-
src_ip
83-
))
78+
logging.error(f"IP {src_ip} not allowed")
8479
abort(403)
8580

8681
# Enforce secret
87-
secret = config.get('enforce_secret', '')
82+
secret = config.get("enforce_secret", "")
8883
if secret:
8984
# Only SHA1 is supported
90-
header_signature = request.headers.get('X-Hub-Signature')
85+
header_signature = request.headers.get("X-Hub-Signature")
9186
if header_signature is None:
9287
abort(403)
9388

94-
sha_name, signature = header_signature.split('=')
95-
if sha_name != 'sha1':
89+
sha_name, signature = header_signature.split("=")
90+
if sha_name != "sha1":
9691
abort(501)
9792

9893
# HMAC requires the key to be bytes, but data is string
99-
mac = hmac.new(str(secret), msg=request.data, digestmod='sha1')
94+
mac = hmac.new(str(secret), msg=request.data, digestmod="sha1")
10095

10196
# Python prior to 2.7.7 does not have hmac.compare_digest
10297
if hexversion >= 0x020707F0:
@@ -110,17 +105,17 @@ def index():
110105
abort(403)
111106

112107
# Implement ping
113-
event = request.headers.get('X-GitHub-Event', 'ping')
114-
if event == 'ping':
108+
event = request.headers.get("X-GitHub-Event", "ping")
109+
if event == "ping":
115110
if has_hook(event):
116111
return jsonify(run_hook(event))
117-
return jsonify({'msg': 'pang'})
112+
return jsonify({"msg": "pang"})
118113

119114
# Gather data
120115
try:
121116
payload = request.get_json()
122117
except Exception:
123-
logging.warning('Request parsing failed')
118+
logging.warning("Request parsing failed")
124119
abort(400)
125120

126121
# Determining the branch is tricky, as it only appears for certain event
@@ -131,20 +126,20 @@ def index():
131126
try:
132127
# Case 1: a ref_type indicates the type of ref.
133128
# This true for create and delete events.
134-
if 'ref_type' in payload:
135-
if payload['ref_type'] == 'branch':
136-
branch = payload['ref']
129+
if "ref_type" in payload:
130+
if payload["ref_type"] == "branch":
131+
branch = payload["ref"]
137132

138133
# Case 2: a pull_request object is involved. This is pull_request and
139134
# pull_request_review_comment events.
140-
elif 'pull_request' in payload:
135+
elif "pull_request" in payload:
141136
# This is the TARGET branch for the pull-request, not the source
142137
# branch
143-
branch = payload['pull_request']['base']['ref']
138+
branch = payload["pull_request"]["base"]["ref"]
144139

145-
elif event in ['push']:
140+
elif event in ["push"]:
146141
# Push events provide a full Git ref in 'ref' and not a 'ref_type'.
147-
branch = payload['ref'].split('/', 2)[2]
142+
branch = payload["ref"].split("/", 2)[2]
148143

149144
except KeyError:
150145
# If the payload structure isn't what we expect, we'll live without
@@ -153,72 +148,63 @@ def index():
153148

154149
# All current events have a repository, but some legacy events do not,
155150
# so let's be safe
156-
name = payload['repository']['name'] if 'repository' in payload else None
151+
name = payload["repository"]["name"] if "repository" in payload else None
157152

158-
meta = {
159-
'name': name,
160-
'branch': branch,
161-
'event': event
162-
}
163-
logging.info('Metadata:\n{}'.format(dumps(meta)))
153+
meta = {"name": name, "branch": branch, "event": event}
154+
logging.info(f"Metadata:\n{dumps(meta)}")
164155

165156
# Skip push-delete
166-
if event == 'push' and payload['deleted']:
167-
logging.info('Skipping push-delete event for {}'.format(dumps(meta)))
168-
return jsonify({'status': 'skipped'})
157+
if event == "push" and payload["deleted"]:
158+
logging.info(f"Skipping push-delete event for {dumps(meta)}")
159+
return jsonify({"status": "skipped"})
169160

170161
# Possible hooks
171162
scripts = []
172163
if branch and name:
173-
scripts.append(join(hooks, '{event}-{name}-{branch}'.format(**meta)))
164+
scripts.append(join(hooks, "{event}-{name}-{branch}".format(**meta)))
174165
if name:
175-
scripts.append(join(hooks, '{event}-{name}'.format(**meta)))
176-
scripts.append(join(hooks, '{event}'.format(**meta)))
177-
scripts.append(join(hooks, 'all'))
166+
scripts.append(join(hooks, "{event}-{name}".format(**meta)))
167+
scripts.append(join(hooks, "{event}".format(**meta)))
168+
scripts.append(join(hooks, "all"))
178169

179170
# Check permissions
180171
scripts = [s for s in scripts if isfile(s) and access(s, X_OK)]
181172
if not scripts:
182-
return jsonify({'status': 'nop'})
173+
return jsonify({"status": "nop"})
183174

184175
# Save payload to temporal file
185176
osfd, tmpfile = mkstemp()
186-
with fdopen(osfd, 'w') as pf:
177+
with fdopen(osfd, "w") as pf:
187178
pf.write(dumps(payload))
188179

189180
# Run scripts
190181
ran = {}
191182
for s in scripts:
192183

193-
proc = Popen(
194-
[s, tmpfile, event],
195-
stdout=PIPE, stderr=PIPE
196-
)
184+
proc = Popen([s, tmpfile, event], stdout=PIPE, stderr=PIPE)
197185
stdout, stderr = proc.communicate()
198186

199187
ran[basename(s)] = {
200-
'returncode': proc.returncode,
201-
'stdout': stdout.decode('utf-8'),
202-
'stderr': stderr.decode('utf-8'),
188+
"returncode": proc.returncode,
189+
"stdout": stdout.decode("utf-8"),
190+
"stderr": stderr.decode("utf-8"),
203191
}
204192

205193
# Log errors if a hook failed
206194
if proc.returncode != 0:
207-
logging.error('{} : {} \n{}'.format(
208-
s, proc.returncode, stderr
209-
))
195+
logging.error(f"{s} : {proc.returncode} \n{stderr}")
210196

211197
# Remove temporal file
212198
remove(tmpfile)
213199

214-
info = config.get('return_scripts_info', False)
200+
info = config.get("return_scripts_info", False)
215201
if not info:
216-
return jsonify({'status': 'done'})
202+
return jsonify({"status": "done"})
217203

218204
output = dumps(ran, sort_keys=True, indent=4)
219205
logging.info(output)
220206
return jsonify(ran)
221207

222208

223-
if __name__ == '__main__':
224-
application.run(debug=True, host='0.0.0.0')
209+
if __name__ == "__main__":
210+
application.run(debug=True, host="0.0.0.0")

0 commit comments

Comments
 (0)