Skip to content

Commit ef40167

Browse files
committed
Update branch determination logic to handle events other than pushes.
1 parent 6eb553e commit ef40167

File tree

2 files changed

+34
-8
lines changed

2 files changed

+34
-8
lines changed

README.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,9 @@ executable and has a shebang. A simple example in Python could be:
9393
with open(outfile, 'w') as f:
9494
f.write(json.dumps(payload))
9595

96+
Not all events have an associated branch, so a branch-specific hook cannot
97+
fire for such events. For events that contain a pull_request object, the
98+
base branch (target for the pull request) is used, not the head branch.
9699

97100
Deploy
98101
======

webhooks.py

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -86,21 +86,44 @@ def index():
8686
# Gather data
8787
try:
8888
payload = loads(request.data)
89+
90+
# Determining the branch is tricky, as it only appears for certain event types an at different levels
91+
branch = None
92+
try:
93+
# Case 1: a ref_type indicates the type of ref. This is create and delete events.
94+
if 'ref_type' in payload:
95+
if payload['ref_type'] == 'branch':
96+
branch = paylaod['ref']
97+
# Case 2: a pull_request object is involved. This is pull_request and pull_request_review_comment events.
98+
elif 'pull_request' in payload:
99+
# This is the TARGET branch for the pull-request, not the source branch
100+
branch = payload['pull_request']['base']['ref']
101+
elif event in ['push']:
102+
# Push events provide a full Git ref in 'ref' and not a 'ref_type'. Isn't that great?
103+
branch = payload['ref'].split('/')[2]
104+
except KeyError:
105+
# If the payload structure isn't what we expect, we'll live without the branch name
106+
pass
107+
108+
# All current events have a repository, but some legacy events do not, so let's be safe
109+
name = payload['repository']['name'] if 'repository' in payload else None
110+
89111
meta = {
90-
'name': payload['repository']['name'],
91-
'branch': payload['ref'].split('/')[2],
112+
'name': name,
113+
'branch': branch,
92114
'event': event
93115
}
94116
except:
95117
abort(400)
96118

97119
# Possible hooks
98-
scripts = [
99-
join(hooks, '{event}-{name}-{branch}'.format(**meta)),
100-
join(hooks, '{event}-{name}'.format(**meta)),
101-
join(hooks, '{event}'.format(**meta)),
102-
join(hooks, 'all')
103-
]
120+
scripts = []
121+
if branch and name:
122+
scripts.append(join(hooks, '{event}-{name}-{branch}'.format(**meta)))
123+
if name:
124+
scripts.append(join(hooks, '{event}-{name}'.format(**meta)))
125+
scripts.append(join(hooks, '{event}'.format(**meta)))
126+
scripts.append(join(hooks, 'all'))
104127

105128
# Check permissions
106129
scripts = [s for s in scripts if isfile(s) and access(s, X_OK)]

0 commit comments

Comments
 (0)