1- # -*- coding: utf-8 -*-
21#
32# Copyright (C) 2014, 2015, 2016 Carlos Jenkins <carlos@jenkins.co.cr>
43#
3433try :
3534 from hooks import has_hook , run_hook
3635except Exception as e :
37- logging .error (' Import hooks failed' )
38- raise (e )
36+ logging .error (" Import hooks failed" )
37+ raise (e )
3938
4039application = Flask (__name__ )
4140
4241
43- @application .route ('/' , methods = [' GET' , ' POST' ])
42+ @application .route ("/" , methods = [" GET" , " POST" ])
4443def 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