zerver/lib: Text-wrap long lines exceeding 110.

This commit is contained in:
rht
2017-11-10 03:34:13 +01:00
committed by Tim Abbott
parent d3914a5017
commit 09af29b051
14 changed files with 71 additions and 45 deletions

View File

@@ -2937,7 +2937,8 @@ def do_create_default_stream_group(realm: Realm, group_name: Text,
default_streams = get_default_streams_for_realm(realm.id)
for stream in streams:
if stream in default_streams:
raise JsonableError(_("'%s' is a default stream and cannot be added to '%s'") % (stream.name, group_name))
raise JsonableError(_("'%s' is a default stream and cannot be added to '%s'") % (
stream.name, group_name))
check_default_stream_group_name(group_name)
(group, created) = DefaultStreamGroup.objects.get_or_create(
@@ -2954,7 +2955,8 @@ def do_add_streams_to_default_stream_group(realm: Realm, group: DefaultStreamGro
default_streams = get_default_streams_for_realm(realm.id)
for stream in streams:
if stream in default_streams:
raise JsonableError(_("'%s' is a default stream and cannot be added to '%s'") % (stream.name, group.name))
raise JsonableError(_("'%s' is a default stream and cannot be added to '%s'") % (
stream.name, group.name))
if stream in group.streams.all():
raise JsonableError(_("Stream '%s' is already present in default stream group '%s'")
% (stream.name, group.name))

View File

@@ -27,7 +27,8 @@ def get_bot_handler(service_name):
# type: (str) -> Any
# Check that this service is present in EMBEDDED_BOTS, add exception handling.
is_present_in_registry = any(service_name == embedded_bot_service.name for embedded_bot_service in EMBEDDED_BOTS)
is_present_in_registry = any(service_name == embedded_bot_service.name for
embedded_bot_service in EMBEDDED_BOTS)
if not is_present_in_registry:
return None
bot_module_name = 'zulip_bots.bots.%s.%s' % (service_name, service_name)

View File

@@ -14,7 +14,8 @@ def get_bot_state(bot_profile, key):
try:
return BotUserStateData.objects.get(bot_profile=bot_profile, key=key).value
except BotUserStateData.DoesNotExist:
raise StateError("Cannot get state. {} doesn't have an entry with the key '{}'.".format(bot_profile, key))
raise StateError("Cannot get state. {} doesn't have "
"an entry with the key '{}'.".format(bot_profile, key))
def get_bot_state_size(bot_profile, key=None):
# type: (UserProfile, Optional[Text]) -> int

View File

@@ -152,21 +152,22 @@ def fetch_initial_state_data(user_profile, event_types, queue_id, client_gravata
# Most state is handled via the property_types framework;
# these manual entries are for those realm settings that don't
# fit into that framework.
state['realm_authentication_methods'] = user_profile.realm.authentication_methods_dict()
state['realm_allow_message_editing'] = user_profile.realm.allow_message_editing
state['realm_message_content_edit_limit_seconds'] = user_profile.realm.message_content_edit_limit_seconds
state['realm_icon_url'] = realm_icon_url(user_profile.realm)
state['realm_icon_source'] = user_profile.realm.icon_source
realm = user_profile.realm
state['realm_authentication_methods'] = realm.authentication_methods_dict()
state['realm_allow_message_editing'] = realm.allow_message_editing
state['realm_message_content_edit_limit_seconds'] = realm.message_content_edit_limit_seconds
state['realm_icon_url'] = realm_icon_url(realm)
state['realm_icon_source'] = realm.icon_source
state['max_icon_file_size'] = settings.MAX_ICON_FILE_SIZE
state['realm_bot_domain'] = user_profile.realm.get_bot_domain()
state['realm_uri'] = user_profile.realm.uri
state['realm_presence_disabled'] = user_profile.realm.presence_disabled
state['realm_show_digest_email'] = user_profile.realm.show_digest_email
state['realm_is_zephyr_mirror_realm'] = user_profile.realm.is_zephyr_mirror_realm
state['realm_email_auth_enabled'] = email_auth_enabled(user_profile.realm)
state['realm_password_auth_enabled'] = password_auth_enabled(user_profile.realm)
if user_profile.realm.notifications_stream and not user_profile.realm.notifications_stream.deactivated:
notifications_stream = user_profile.realm.notifications_stream
state['realm_bot_domain'] = realm.get_bot_domain()
state['realm_uri'] = realm.uri
state['realm_presence_disabled'] = realm.presence_disabled
state['realm_show_digest_email'] = realm.show_digest_email
state['realm_is_zephyr_mirror_realm'] = realm.is_zephyr_mirror_realm
state['realm_email_auth_enabled'] = email_auth_enabled(realm)
state['realm_password_auth_enabled'] = password_auth_enabled(realm)
if realm.notifications_stream and not realm.notifications_stream.deactivated:
notifications_stream = realm.notifications_stream
state['realm_notifications_stream_id'] = notifications_stream.id
else:
state['realm_notifications_stream_id'] = -1
@@ -232,7 +233,8 @@ def fetch_initial_state_data(user_profile, event_types, queue_id, client_gravata
if want('stream'):
state['streams'] = do_get_streams(user_profile)
if want('default_streams'):
state['realm_default_streams'] = streams_to_dicts_sorted(get_default_streams_for_realm(user_profile.realm_id))
state['realm_default_streams'] = streams_to_dicts_sorted(
get_default_streams_for_realm(user_profile.realm_id))
if want('default_stream_groups'):
state['realm_default_stream_groups'] = default_stream_groups_to_dicts_sorted(
get_default_stream_groups(user_profile.realm))

View File

@@ -545,7 +545,8 @@ def sanity_check_stream_data(response, config, context):
# complex to have a sanity check.
return
actual_streams = set([stream.name for stream in Stream.objects.filter(realm=response["zerver_realm"][0]['id'])])
actual_streams = set([stream.name for stream in Stream.objects.filter(
realm=response["zerver_realm"][0]['id'])])
streams_in_response = set([stream['name'] for stream in response['zerver_stream']])
if streams_in_response != actual_streams:
@@ -638,8 +639,8 @@ def fetch_huddle_objects(response, config, context):
user_profile_ids = set(r['id'] for r in response[config.parent.table])
# First we get all huddles involving someone in the realm.
realm_huddle_subs = Subscription.objects.select_related("recipient").filter(recipient__type=Recipient.HUDDLE,
user_profile__in=user_profile_ids)
realm_huddle_subs = Subscription.objects.select_related("recipient").filter(
recipient__type=Recipient.HUDDLE, user_profile__in=user_profile_ids)
realm_huddle_recipient_ids = set(sub.recipient_id for sub in realm_huddle_subs)
# Mark all Huddles whose recipient ID contains a cross-realm user.

View File

@@ -195,8 +195,10 @@ class WebhookIntegration(Integration):
class HubotLozenge(Integration):
GIT_URL_TEMPLATE = "https://github.com/hubot-scripts/hubot-{}"
def __init__(self, name, categories, display_name=None, logo=None, logo_alt=None, git_url=None, legacy=False):
# type: (str, List[str], Optional[str], Optional[str], Optional[str], Optional[str], Optional[bool]) -> None
def __init__(self, name: str, categories: List[str],
display_name: Optional[str]=None, logo: Optional[str]=None,
logo_alt: Optional[str]=None, git_url: Optional[str]=None,
legacy: bool=False) -> None:
if logo_alt is None:
logo_alt = "{} logo".format(name.title())
self.logo_alt = logo_alt
@@ -372,7 +374,8 @@ INTEGRATIONS = {
doc='zerver/integrations/discourse.md'),
'email': EmailIntegration('email', 'email', ['communication'],
doc='zerver/integrations/email.md'),
'errbot': Integration('errbot', 'errbot', ['meta-integration', 'bots'], doc='zerver/integrations/errbot.md'),
'errbot': Integration('errbot', 'errbot', ['meta-integration', 'bots'],
doc='zerver/integrations/errbot.md'),
'git': Integration('git', 'git', ['version-control'], doc='zerver/integrations/git.md'),
'google-calendar': Integration(
'google-calendar',
@@ -422,8 +425,10 @@ INTEGRATIONS = {
'phabricator': Integration('phabricator', 'phabricator', ['version-control'],
doc='zerver/integrations/phabricator.md'),
'puppet': Integration('puppet', 'puppet', ['deployment'], doc='zerver/integrations/puppet.md'),
'redmine': Integration('redmine', 'redmine', ['project-management'], doc='zerver/integrations/redmine.md'),
'rss': Integration('rss', 'rss', ['communication'], display_name='RSS', doc='zerver/integrations/rss.md'),
'redmine': Integration('redmine', 'redmine', ['project-management'],
doc='zerver/integrations/redmine.md'),
'rss': Integration('rss', 'rss', ['communication'],
display_name='RSS', doc='zerver/integrations/rss.md'),
'svn': Integration('svn', 'svn', ['version-control'], doc='zerver/integrations/svn.md'),
'trac': Integration('trac', 'trac', ['project-management'], doc='zerver/integrations/trac.md'),
'trello-plugin': Integration(

View File

@@ -114,6 +114,7 @@ You can use the command list_realms to find ID of the realms in this server."""
return UserProfile.objects.select_related().get(email__iexact=email.strip())
except MultipleObjectsReturned:
raise CommandError("This Zulip server contains multiple users with that email " +
"(in different realms); please pass `--realm` to specify which one to modify.")
"(in different realms); please pass `--realm` "
"to specify which one to modify.")
except UserProfile.DoesNotExist:
raise CommandError("This Zulip server does not contain a user with email '%s'" % (email,))

View File

@@ -336,10 +336,12 @@ def do_send_missedmessage_events_reply_in_zulip(user_profile, missed_messages, m
huddle_display_name = u"%s" % (" and ".join(other_recipients))
context.update({'huddle_display_name': huddle_display_name})
elif len(other_recipients) == 3:
huddle_display_name = u"%s, %s, and %s" % (other_recipients[0], other_recipients[1], other_recipients[2])
huddle_display_name = u"%s, %s, and %s" % (
other_recipients[0], other_recipients[1], other_recipients[2])
context.update({'huddle_display_name': huddle_display_name})
else:
huddle_display_name = u"%s, and %s others" % (', '.join(other_recipients[:2]), len(other_recipients) - 2)
huddle_display_name = u"%s, and %s others" % (
', '.join(other_recipients[:2]), len(other_recipients) - 2)
context.update({'huddle_display_name': huddle_display_name})
elif (missed_messages[0].recipient.type == Recipient.PERSONAL):
context.update({'private_message': True})

View File

@@ -13,8 +13,9 @@ def send_initial_pms(user):
# type: (UserProfile) -> None
organization_setup_text = ""
if user.is_realm_admin:
organization_setup_text = "* [Read the guide](%s) for getting your organization started with Zulip\n" \
% (user.realm.uri + "/help/getting-your-organization-started-with-zulip",)
help_url = user.realm.uri + "/help/getting-your-organization-started-with-zulip"
organization_setup_text = ("* [Read the guide](%s) for getting your organization "
"started with Zulip\n" % (help_url,))
content = (
"Hello, and welcome to Zulip!\n\nThis is a private message from me, Welcome Bot. "

View File

@@ -190,7 +190,8 @@ def notify_bot_owner(event, request_data, status_code=None, response_content=Non
"```\n%s\n```" % (response_content,)
if exception:
notification_message += "\nWhen trying to send a request to the webhook service, an exception " \
"of type %s occurred:\n```\n%s\n```" % (type(exception).__name__, str(exception))
"of type %s occurred:\n```\n%s\n```" % (
type(exception).__name__, str(exception))
send_response_message(bot_id, message_info, notification_message)
def request_retry(event, request_data, failure_message, exception=None):
@@ -205,7 +206,8 @@ def request_retry(event, request_data, failure_message, exception=None):
bot_user = get_user_profile_by_id(event['user_profile_id'])
fail_with_message(event, "Maximum retries exceeded! " + failure_message)
notify_bot_owner(event, request_data, exception=exception)
logging.warning("Maximum retries exceeded for trigger:%s event:%s" % (bot_user.email, event['command']))
logging.warning("Maximum retries exceeded for trigger:%s event:%s" % (
bot_user.email, event['command']))
retry_event('outgoing_webhooks', event, failure_processor)
@@ -245,19 +247,22 @@ def do_rest_call(rest_operation, request_data, event, service_handler, timeout=N
notify_bot_owner(event, request_data, response.status_code, response.content)
except requests.exceptions.Timeout as e:
logging.info("Trigger event %s on %s timed out. Retrying" % (event["command"], event['service_name']))
logging.info("Trigger event %s on %s timed out. Retrying" % (
event["command"], event['service_name']))
request_retry(event, request_data, 'Unable to connect with the third party.', exception=e)
except requests.exceptions.ConnectionError as e:
response_message = "The message `%s` resulted in a connection error when sending a request to an outgoing " \
"webhook! See the Zulip server logs for more information." % (event["command"],)
response_message = ("The message `%s` resulted in a connection error when "
"sending a request to an outgoing "
"webhook! See the Zulip server logs for more information." % (event["command"],))
logging.info("Trigger event %s on %s resulted in a connection error. Retrying"
% (event["command"], event['service_name']))
request_retry(event, request_data, response_message, exception=e)
except requests.exceptions.RequestException as e:
response_message = "An exception of type *%s* occurred for message `%s`! " \
"See the Zulip server logs for more information." % (type(e).__name__, event["command"],)
response_message = ("An exception of type *%s* occurred for message `%s`! "
"See the Zulip server logs for more information." % (
type(e).__name__, event["command"],))
logging.exception("Outhook trigger failed:\n %s" % (e,))
fail_with_message(event, response_message)
notify_bot_owner(event, request_data, exception=e)

View File

@@ -245,8 +245,8 @@ def incr_ratelimit(entity):
break
except redis.WatchError:
if count > 10:
logging.error("Failed to complete incr_ratelimit transaction without interference 10 times "
"in a row! Aborting rate-limit increment")
logging.error("Failed to complete incr_ratelimit transaction without "
"interference 10 times in a row! Aborting rate-limit increment")
break
count += 1

View File

@@ -11,7 +11,9 @@ from datetime import datetime, timedelta
# given dates
def seconds_usage_between(user_profile, begin, end):
# type: (UserProfile, datetime, datetime) -> timedelta
intervals = UserActivityInterval.objects.filter(user_profile=user_profile, end__gte=begin, start__lte=end)
intervals = UserActivityInterval.objects.filter(user_profile=user_profile,
end__gte=begin,
start__lte=end)
duration = timedelta(0)
for interval in intervals:
start = max(begin, interval.start)

View File

@@ -567,7 +567,8 @@ def upload_message_image(uploaded_file_name, uploaded_file_size,
content_type, file_data, user_profile, target_realm=None):
# type: (Text, int, Optional[Text], bytes, UserProfile, Optional[Realm]) -> Text
return upload_backend.upload_message_image(uploaded_file_name, uploaded_file_size,
content_type, file_data, user_profile, target_realm=target_realm)
content_type, file_data, user_profile,
target_realm=target_realm)
def claim_attachment(user_profile, path_id, message, is_message_realm_public):
# type: (UserProfile, Text, Message, bool) -> None

View File

@@ -23,11 +23,13 @@ PUSH_COMMITS_MESSAGE_TEMPLATE_WITHOUT_COMMITTERS = PUSH_COMMITS_BASE + u"""
{commits_data}
"""
PUSH_DELETE_BRANCH_MESSAGE_TEMPLATE = u"{user_name} [deleted]({compare_url}) the branch {branch_name}."
PUSH_LOCAL_BRANCH_WITHOUT_COMMITS_MESSAGE_TEMPLATE = u"{user_name} [pushed]({compare_url}) the branch {branch_name}."
PUSH_LOCAL_BRANCH_WITHOUT_COMMITS_MESSAGE_TEMPLATE = (u"{user_name} [pushed]({compare_url}) "
"the branch {branch_name}.")
PUSH_COMMITS_MESSAGE_EXTENSION = u"Commits by {}"
PUSH_COMMITTERS_LIMIT_INFO = 3
FORCE_PUSH_COMMITS_MESSAGE_TEMPLATE = u"{user_name} [force pushed]({url}) to branch {branch_name}. Head is now {head}"
FORCE_PUSH_COMMITS_MESSAGE_TEMPLATE = (u"{user_name} [force pushed]({url}) "
"to branch {branch_name}. Head is now {head}")
CREATE_BRANCH_MESSAGE_TEMPLATE = u"{user_name} created [{branch_name}]({url}) branch"
REMOVE_BRANCH_MESSAGE_TEMPLATE = u"{user_name} deleted branch {branch_name}"