2016-03-11 22:12:41 +01:00
|
|
|
import logging
|
|
|
|
import re
|
2018-05-10 19:34:01 +02:00
|
|
|
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
|
2017-11-16 00:43:10 +01:00
|
|
|
|
2016-03-11 22:12:41 +01:00
|
|
|
import ujson
|
2017-11-16 00:43:10 +01:00
|
|
|
from django.conf import settings
|
|
|
|
from django.http import HttpRequest, HttpResponse
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2017-11-16 00:43:10 +01:00
|
|
|
from zerver.decorator import authenticated_api_view, \
|
2018-04-26 06:54:51 +02:00
|
|
|
to_non_negative_int
|
2018-04-26 19:11:46 +02:00
|
|
|
from zerver.lib.request import REQ, has_request_variables, JsonableError
|
2017-11-16 00:43:10 +01:00
|
|
|
from zerver.lib.response import json_success
|
|
|
|
from zerver.lib.validator import check_dict
|
2018-11-09 20:59:15 +01:00
|
|
|
from zerver.lib.webhooks.git import TOPIC_WITH_BRANCH_TEMPLATE, \
|
|
|
|
TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE, \
|
2017-11-16 00:43:10 +01:00
|
|
|
get_commits_comment_action_message, get_force_push_commits_event_message, \
|
|
|
|
get_issue_event_message, get_pull_request_event_message, \
|
|
|
|
get_push_commits_event_message, get_remove_branch_event_message
|
|
|
|
from zerver.models import UserProfile, get_client
|
|
|
|
from zerver.views.messages import send_message_backend
|
2016-06-26 10:34:24 +02:00
|
|
|
|
2016-04-20 21:24:01 +02:00
|
|
|
ZULIP_TEST_REPO_NAME = 'zulip-test'
|
|
|
|
ZULIP_TEST_REPO_ID = 6893087
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def flexible_boolean(boolean: str) -> bool:
|
2018-04-26 06:54:51 +02:00
|
|
|
"""Returns True for any of "1", "true", or "True". Returns False otherwise."""
|
|
|
|
if boolean in ("1", "true", "True"):
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def is_test_repository(repository: Mapping[str, Any]) -> bool:
|
2016-04-20 21:25:53 +02:00
|
|
|
return repository['name'] == ZULIP_TEST_REPO_NAME and repository['id'] == ZULIP_TEST_REPO_ID
|
|
|
|
|
2016-04-20 21:34:16 +02:00
|
|
|
class UnknownEventType(Exception):
|
|
|
|
pass
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def github_pull_request_content(payload: Mapping[str, Any]) -> str:
|
2016-10-11 18:58:04 +02:00
|
|
|
pull_request = payload['pull_request']
|
2016-10-19 22:16:24 +02:00
|
|
|
action = get_pull_request_or_issue_action(payload)
|
2016-10-20 16:42:44 +02:00
|
|
|
|
2016-10-11 18:58:04 +02:00
|
|
|
if action in ('opened', 'edited'):
|
|
|
|
return get_pull_request_event_message(
|
|
|
|
payload['sender']['login'],
|
|
|
|
action,
|
|
|
|
pull_request['html_url'],
|
2016-10-26 21:13:00 +02:00
|
|
|
pull_request['number'],
|
2016-10-11 18:58:04 +02:00
|
|
|
pull_request['head']['ref'],
|
|
|
|
pull_request['base']['ref'],
|
|
|
|
pull_request['body'],
|
2016-10-19 22:16:24 +02:00
|
|
|
get_pull_request_or_issue_assignee(pull_request)
|
2016-10-11 18:58:04 +02:00
|
|
|
)
|
|
|
|
return get_pull_request_event_message(
|
2017-01-24 07:06:13 +01:00
|
|
|
payload['sender']['login'],
|
|
|
|
action,
|
|
|
|
pull_request['html_url'],
|
|
|
|
pull_request['number']
|
2017-01-24 06:02:39 +01:00
|
|
|
)
|
2016-04-20 21:34:16 +02:00
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def github_issues_content(payload: Mapping[str, Any]) -> str:
|
2016-10-19 22:16:24 +02:00
|
|
|
issue = payload['issue']
|
|
|
|
action = get_pull_request_or_issue_action(payload)
|
2016-10-20 16:42:44 +02:00
|
|
|
|
2016-10-19 22:16:24 +02:00
|
|
|
if action in ('opened', 'edited'):
|
|
|
|
return get_issue_event_message(
|
|
|
|
payload['sender']['login'],
|
|
|
|
action,
|
|
|
|
issue['html_url'],
|
2016-10-26 21:13:00 +02:00
|
|
|
issue['number'],
|
2016-10-19 22:16:24 +02:00
|
|
|
issue['body'],
|
|
|
|
get_pull_request_or_issue_assignee(issue)
|
|
|
|
)
|
|
|
|
return get_issue_event_message(
|
2017-01-24 07:06:13 +01:00
|
|
|
payload['sender']['login'],
|
|
|
|
action,
|
|
|
|
issue['html_url'],
|
|
|
|
issue['number'],
|
2017-01-24 06:02:39 +01:00
|
|
|
)
|
2016-10-19 22:16:24 +02:00
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def github_object_commented_content(payload: Mapping[str, Any], type: str) -> str:
|
2016-10-20 16:42:44 +02:00
|
|
|
comment = payload['comment']
|
|
|
|
issue = payload['issue']
|
2016-10-26 20:47:12 +02:00
|
|
|
action = u'[commented]({}) on'.format(comment['html_url'])
|
2016-10-20 16:42:44 +02:00
|
|
|
|
|
|
|
return get_pull_request_event_message(
|
|
|
|
comment['user']['login'],
|
|
|
|
action,
|
|
|
|
issue['html_url'],
|
2016-10-26 21:13:00 +02:00
|
|
|
issue['number'],
|
2016-10-20 16:42:44 +02:00
|
|
|
message=comment['body'],
|
|
|
|
type=type
|
|
|
|
)
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def get_pull_request_or_issue_action(payload: Mapping[str, Any]) -> str:
|
2016-10-19 22:16:24 +02:00
|
|
|
return 'synchronized' if payload['action'] == 'synchronize' else payload['action']
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def get_pull_request_or_issue_assignee(object_payload: Mapping[str, Any]) -> Optional[str]:
|
2016-10-19 22:16:24 +02:00
|
|
|
assignee_dict = object_payload.get('assignee')
|
|
|
|
if assignee_dict:
|
|
|
|
return assignee_dict.get('login')
|
2017-03-03 23:15:18 +01:00
|
|
|
return None
|
2016-10-19 22:16:24 +02:00
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def get_pull_request_or_issue_subject(repository: Mapping[str, Any],
|
|
|
|
payload_object: Mapping[str, Any],
|
|
|
|
type: str) -> str:
|
2018-11-09 20:59:15 +01:00
|
|
|
return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
|
2017-01-24 07:06:13 +01:00
|
|
|
repo=repository['name'],
|
|
|
|
type=type,
|
|
|
|
id=payload_object['number'],
|
|
|
|
title=payload_object['title']
|
2017-01-24 06:02:39 +01:00
|
|
|
)
|
2016-10-19 22:16:24 +02:00
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def github_generic_subject(noun: str, topic_focus: str, blob: Mapping[str, Any]) -> str:
|
2016-03-11 22:12:41 +01:00
|
|
|
# issue and pull_request objects have the same fields we're interested in
|
2016-06-26 10:23:21 +02:00
|
|
|
return u'%s: %s %d: %s' % (topic_focus, noun, blob['number'], blob['title'])
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2017-11-04 07:47:46 +01:00
|
|
|
def api_github_v1(user_profile: UserProfile,
|
2018-05-10 19:34:01 +02:00
|
|
|
event: str,
|
|
|
|
payload: Mapping[str, Any],
|
|
|
|
branches: str,
|
|
|
|
stream: str,
|
|
|
|
**kwargs: Any) -> Tuple[str, str, str]:
|
2016-03-11 22:12:41 +01:00
|
|
|
"""
|
|
|
|
processes github payload with version 1 field specification
|
|
|
|
`payload` comes in unmodified from github
|
|
|
|
`stream` is set to 'commits' if otherwise unset
|
|
|
|
"""
|
|
|
|
commit_stream = stream
|
|
|
|
issue_stream = 'issues'
|
2017-11-05 02:48:25 +01:00
|
|
|
return api_github_v2(user_profile, event, payload, branches,
|
|
|
|
stream, commit_stream, issue_stream, **kwargs)
|
2016-03-11 22:12:41 +01:00
|
|
|
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def api_github_v2(user_profile: UserProfile, event: str, payload: Mapping[str, Any],
|
|
|
|
branches: str, default_stream: str, commit_stream: str,
|
|
|
|
issue_stream: str, topic_focus: Optional[str]=None) -> Tuple[str, str, str]:
|
2016-03-11 22:12:41 +01:00
|
|
|
"""
|
|
|
|
processes github payload with version 2 field specification
|
|
|
|
`payload` comes in unmodified from github
|
|
|
|
`default_stream` is set to what `stream` is in v1 above
|
|
|
|
`commit_stream` and `issue_stream` fall back to `default_stream` if they are empty
|
|
|
|
This and allowing alternative endpoints is what distinguishes v1 from v2 of the github configuration
|
|
|
|
"""
|
2016-04-20 21:30:55 +02:00
|
|
|
target_stream = commit_stream if commit_stream else default_stream
|
|
|
|
issue_stream = issue_stream if issue_stream else default_stream
|
2016-03-11 22:12:41 +01:00
|
|
|
repository = payload['repository']
|
2017-05-24 23:03:06 +02:00
|
|
|
updated_topic_focus = topic_focus if topic_focus else repository['name']
|
|
|
|
|
2016-03-11 22:12:41 +01:00
|
|
|
# Event Handlers
|
|
|
|
if event == 'pull_request':
|
2016-10-19 22:16:24 +02:00
|
|
|
subject = get_pull_request_or_issue_subject(repository, payload['pull_request'], 'PR')
|
2016-10-11 18:58:04 +02:00
|
|
|
content = github_pull_request_content(payload)
|
2016-03-11 22:12:41 +01:00
|
|
|
elif event == 'issues':
|
|
|
|
# in v1, we assume that this stream exists since it is
|
|
|
|
# deprecated and the few realms that use it already have the
|
|
|
|
# stream
|
|
|
|
target_stream = issue_stream
|
2016-10-19 22:16:24 +02:00
|
|
|
subject = get_pull_request_or_issue_subject(repository, payload['issue'], 'Issue')
|
|
|
|
content = github_issues_content(payload)
|
2016-03-11 22:12:41 +01:00
|
|
|
elif event == 'issue_comment':
|
|
|
|
# Comments on both issues and pull requests come in as issue_comment events
|
|
|
|
issue = payload['issue']
|
|
|
|
if 'pull_request' not in issue or issue['pull_request']['diff_url'] is None:
|
|
|
|
# It's an issues comment
|
|
|
|
target_stream = issue_stream
|
2016-10-20 16:42:44 +02:00
|
|
|
type = 'Issue'
|
|
|
|
subject = get_pull_request_or_issue_subject(repository, payload['issue'], type)
|
2016-03-11 22:12:41 +01:00
|
|
|
else:
|
|
|
|
# It's a pull request comment
|
2016-10-20 16:42:44 +02:00
|
|
|
type = 'PR'
|
|
|
|
subject = get_pull_request_or_issue_subject(repository, payload['issue'], type)
|
|
|
|
|
|
|
|
content = github_object_commented_content(payload, type)
|
|
|
|
|
2016-03-11 22:12:41 +01:00
|
|
|
elif event == 'push':
|
2017-05-24 23:03:06 +02:00
|
|
|
subject, content = build_message_from_gitlog(user_profile, updated_topic_focus,
|
2016-03-11 22:12:41 +01:00
|
|
|
payload['ref'], payload['commits'],
|
|
|
|
payload['before'], payload['after'],
|
|
|
|
payload['compare'],
|
|
|
|
payload['pusher']['name'],
|
|
|
|
forced=payload['forced'],
|
2017-05-16 04:38:25 +02:00
|
|
|
created=payload['created'],
|
|
|
|
deleted=payload['deleted'])
|
2016-03-11 22:12:41 +01:00
|
|
|
elif event == 'commit_comment':
|
2017-05-24 23:03:06 +02:00
|
|
|
subject = updated_topic_focus
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2017-05-24 23:03:06 +02:00
|
|
|
comment = payload['comment']
|
2016-10-27 21:43:15 +02:00
|
|
|
action = u'[commented]({})'.format(comment['html_url'])
|
|
|
|
content = get_commits_comment_action_message(
|
2016-10-26 21:29:23 +02:00
|
|
|
comment['user']['login'],
|
|
|
|
action,
|
|
|
|
comment['html_url'].split('#', 1)[0],
|
2016-10-27 21:43:15 +02:00
|
|
|
comment['commit_id'],
|
|
|
|
comment['body'],
|
2016-10-26 21:29:23 +02:00
|
|
|
)
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2016-04-20 21:34:16 +02:00
|
|
|
else:
|
2017-12-22 14:03:18 +01:00
|
|
|
raise UnknownEventType(u'Event %s is unknown and cannot be handled' % (event,))
|
2016-04-20 21:34:16 +02:00
|
|
|
|
2016-04-20 21:27:51 +02:00
|
|
|
return target_stream, subject, content
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2016-05-18 20:35:35 +02:00
|
|
|
@authenticated_api_view(is_webhook=True)
|
2016-03-11 22:12:41 +01:00
|
|
|
@has_request_variables
|
2018-05-10 19:34:01 +02:00
|
|
|
def api_github_landing(request: HttpRequest, user_profile: UserProfile, event: str=REQ(),
|
|
|
|
payload: Mapping[str, Any]=REQ(validator=check_dict([])),
|
|
|
|
branches: str=REQ(default=''),
|
|
|
|
stream: str=REQ(default=''),
|
2017-12-30 08:52:28 +01:00
|
|
|
version: int=REQ(converter=to_non_negative_int, default=1),
|
2018-05-10 19:34:01 +02:00
|
|
|
commit_stream: str=REQ(default=''),
|
|
|
|
issue_stream: str=REQ(default=''),
|
2017-12-30 08:52:28 +01:00
|
|
|
exclude_pull_requests: bool=REQ(converter=flexible_boolean, default=False),
|
|
|
|
exclude_issues: bool=REQ(converter=flexible_boolean, default=False),
|
|
|
|
exclude_commits: bool=REQ(converter=flexible_boolean, default=False),
|
|
|
|
emphasize_branch_in_topic: bool=REQ(converter=flexible_boolean, default=False),
|
|
|
|
) -> HttpResponse:
|
2016-03-11 22:12:41 +01:00
|
|
|
|
|
|
|
repository = payload['repository']
|
|
|
|
|
|
|
|
# Special hook for capturing event data. If we see our special test repo, log the payload from github.
|
|
|
|
try:
|
2016-04-20 21:25:53 +02:00
|
|
|
if is_test_repository(repository) and settings.PRODUCTION:
|
2016-03-11 22:12:41 +01:00
|
|
|
with open('/var/log/zulip/github-payloads', 'a') as f:
|
|
|
|
f.write(ujson.dumps({'event': event,
|
|
|
|
'payload': payload,
|
|
|
|
'branches': branches,
|
|
|
|
'stream': stream,
|
|
|
|
'version': version,
|
|
|
|
'commit_stream': commit_stream,
|
|
|
|
'issue_stream': issue_stream,
|
|
|
|
'exclude_pull_requests': exclude_pull_requests,
|
|
|
|
'exclude_issues': exclude_issues,
|
|
|
|
'exclude_commits': exclude_commits,
|
|
|
|
'emphasize_branch_in_topic': emphasize_branch_in_topic,
|
|
|
|
}))
|
2016-04-20 21:35:38 +02:00
|
|
|
f.write('\n')
|
2016-03-11 22:12:41 +01:00
|
|
|
except Exception:
|
2016-04-20 21:35:38 +02:00
|
|
|
logging.exception('Error while capturing Github event')
|
2016-03-11 22:12:41 +01:00
|
|
|
|
|
|
|
if not stream:
|
|
|
|
stream = 'commits'
|
|
|
|
|
2016-04-20 21:35:38 +02:00
|
|
|
short_ref = re.sub(r'^refs/heads/', '', payload.get('ref', ''))
|
2016-03-11 22:12:41 +01:00
|
|
|
kwargs = dict()
|
|
|
|
|
|
|
|
if emphasize_branch_in_topic and short_ref:
|
|
|
|
kwargs['topic_focus'] = short_ref
|
|
|
|
|
|
|
|
allowed_events = set()
|
|
|
|
if not exclude_pull_requests:
|
|
|
|
allowed_events.add('pull_request')
|
|
|
|
|
|
|
|
if not exclude_issues:
|
2016-04-20 21:35:38 +02:00
|
|
|
allowed_events.add('issues')
|
|
|
|
allowed_events.add('issue_comment')
|
2016-03-11 22:12:41 +01:00
|
|
|
|
|
|
|
if not exclude_commits:
|
2016-04-20 21:35:38 +02:00
|
|
|
allowed_events.add('push')
|
|
|
|
allowed_events.add('commit_comment')
|
2016-03-11 22:12:41 +01:00
|
|
|
|
|
|
|
if event not in allowed_events:
|
|
|
|
return json_success()
|
|
|
|
|
|
|
|
# We filter issue_comment events for issue creation events
|
|
|
|
if event == 'issue_comment' and payload['action'] != 'created':
|
|
|
|
return json_success()
|
|
|
|
|
|
|
|
if event == 'push':
|
|
|
|
# If we are given a whitelist of branches, then we silently ignore
|
|
|
|
# any push notification on a branch that is not in our whitelist.
|
2018-07-02 00:05:24 +02:00
|
|
|
if branches and short_ref not in re.split(r'[\s,;|]+', branches):
|
2016-03-11 22:12:41 +01:00
|
|
|
return json_success()
|
|
|
|
|
|
|
|
# Map payload to the handler with the right version
|
|
|
|
if version == 2:
|
2016-07-17 19:49:53 +02:00
|
|
|
target_stream, subject, content = api_github_v2(user_profile, event, payload, branches,
|
|
|
|
stream, commit_stream, issue_stream,
|
|
|
|
**kwargs)
|
2016-03-11 22:12:41 +01:00
|
|
|
else:
|
2016-07-17 19:49:53 +02:00
|
|
|
target_stream, subject, content = api_github_v1(user_profile, event, payload, branches,
|
|
|
|
stream, **kwargs)
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2018-04-26 19:13:19 +02:00
|
|
|
request.client = get_client('ZulipGitHubLegacyWebhook')
|
2016-03-11 22:12:41 +01:00
|
|
|
return send_message_backend(request, user_profile,
|
2016-04-20 21:35:38 +02:00
|
|
|
message_type_name='stream',
|
2016-03-11 22:12:41 +01:00
|
|
|
message_to=[target_stream],
|
2017-10-27 14:53:28 +02:00
|
|
|
forged=False, topic_name=subject,
|
2016-03-11 22:12:41 +01:00
|
|
|
message_content=content)
|
|
|
|
|
2018-05-10 19:34:01 +02:00
|
|
|
def build_message_from_gitlog(user_profile: UserProfile, name: str, ref: str,
|
|
|
|
commits: List[Dict[str, str]], before: str, after: str,
|
|
|
|
url: str, pusher: str, forced: Optional[str]=None,
|
|
|
|
created: Optional[str]=None, deleted: Optional[bool]=False
|
|
|
|
) -> Tuple[str, str]:
|
2016-03-11 22:12:41 +01:00
|
|
|
short_ref = re.sub(r'^refs/heads/', '', ref)
|
2018-11-09 20:59:15 +01:00
|
|
|
subject = TOPIC_WITH_BRANCH_TEMPLATE.format(repo=name, branch=short_ref)
|
2016-03-11 22:12:41 +01:00
|
|
|
|
|
|
|
if re.match(r'^0+$', after):
|
2016-10-06 16:21:33 +02:00
|
|
|
content = get_remove_branch_event_message(pusher, short_ref)
|
2016-03-11 22:12:41 +01:00
|
|
|
# 'created' and 'forced' are github flags; the second check is for beanstalk
|
|
|
|
elif (forced and not created) or (forced is None and len(commits) == 0):
|
2016-10-05 20:50:17 +02:00
|
|
|
content = get_force_push_commits_event_message(pusher, url, short_ref, after[:7])
|
2016-03-11 22:12:41 +01:00
|
|
|
else:
|
2016-09-26 17:28:14 +02:00
|
|
|
commits = _transform_commits_list_to_common_format(commits)
|
2018-04-26 19:11:46 +02:00
|
|
|
try:
|
|
|
|
content = get_push_commits_event_message(pusher, url, short_ref, commits, deleted=deleted)
|
|
|
|
except TypeError: # nocoverage This error condition seems to
|
|
|
|
# be caused by a change in GitHub's APIs. Since we've
|
|
|
|
# deprecated this webhook, just suppress them with a 40x error.
|
|
|
|
raise JsonableError(
|
|
|
|
"Malformed commit data")
|
2016-03-11 22:12:41 +01:00
|
|
|
|
2016-04-20 21:27:51 +02:00
|
|
|
return subject, content
|
2016-09-26 17:28:14 +02:00
|
|
|
|
2017-11-04 07:47:46 +01:00
|
|
|
def _transform_commits_list_to_common_format(commits: List[Dict[str, Any]]) -> List[Dict[str, str]]:
|
2016-09-26 17:28:14 +02:00
|
|
|
new_commits_list = []
|
|
|
|
for commit in commits:
|
|
|
|
new_commits_list.append({
|
2017-05-24 23:03:06 +02:00
|
|
|
'name': commit['author'].get('username'),
|
2016-09-26 17:28:14 +02:00
|
|
|
'sha': commit.get('id'),
|
|
|
|
'url': commit.get('url'),
|
|
|
|
'message': commit.get('message'),
|
|
|
|
})
|
|
|
|
return new_commits_list
|