From 17cf26aa1fea103f4f14bd84335f79cde10553fe Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Sat, 18 Apr 2020 17:33:01 -0700 Subject: [PATCH] cleanup: Move line breaks before binary operators. Signed-off-by: Anders Kaseorg --- tools/pep8.py | 4 + .../bridge_with_matrix/matrix_bridge.py | 6 +- zulip/integrations/git/post-receive | 6 +- .../jabber/jabber_mirror_backend.py | 14 ++-- zulip/integrations/trac/zulip_trac.py | 6 +- .../zephyr/zephyr_mirror_backend.py | 78 ++++++++++++------- zulip/zulip/__init__.py | 20 +++-- .../bots/baremetrics/baremetrics.py | 43 ++++++---- .../zulip_bots/bots/converter/converter.py | 6 +- zulip_bots/zulip_bots/bots/jira/jira.py | 16 ++-- zulip_bots/zulip_bots/bots/mention/mention.py | 14 +++- .../zulip_bots/bots/tictactoe/tictactoe.py | 16 +++- 12 files changed, 152 insertions(+), 77 deletions(-) diff --git a/tools/pep8.py b/tools/pep8.py index 47d740c..0f1ac2d 100644 --- a/tools/pep8.py +++ b/tools/pep8.py @@ -68,6 +68,10 @@ def check_pep8(files: List[str]) -> bool: # own check for this (see max_length) 'E501', + # "line break before binary operator" + # This was obsoleted in favor of the opposite W504. + 'W503', + # "do not assign a lambda expression, use a def" # Fixing these would probably reduce readability in most cases. 'E731', diff --git a/zulip/integrations/bridge_with_matrix/matrix_bridge.py b/zulip/integrations/bridge_with_matrix/matrix_bridge.py index 6897dd5..ba7779d 100644 --- a/zulip/integrations/bridge_with_matrix/matrix_bridge.py +++ b/zulip/integrations/bridge_with_matrix/matrix_bridge.py @@ -75,8 +75,10 @@ def matrix_to_zulip( zulip_bot_user = ('@%s:matrix.org' % matrix_config['username']) # We do this to identify the messages generated from Zulip -> Matrix # and we make sure we don't forward it again to the Zulip stream. - not_from_zulip_bot = ('body' not in event['content'] or - event['sender'] != zulip_bot_user) + not_from_zulip_bot = ( + 'body' not in event['content'] + or event['sender'] != zulip_bot_user + ) if not_from_zulip_bot and content: try: diff --git a/zulip/integrations/git/post-receive b/zulip/integrations/git/post-receive index 150c311..95e7633 100755 --- a/zulip/integrations/git/post-receive +++ b/zulip/integrations/git/post-receive @@ -59,8 +59,10 @@ def send_bot_message(oldrev: str, newrev: str, refname: str) -> None: new_head = newrev[:12] old_head = oldrev[:12] - if (oldrev == '0000000000000000000000000000000000000000' or - newrev == '0000000000000000000000000000000000000000'): + if ( + oldrev == '0000000000000000000000000000000000000000' + or newrev == '0000000000000000000000000000000000000000' + ): # New branch pushed or old branch removed added = '' removed = '' diff --git a/zulip/integrations/jabber/jabber_mirror_backend.py b/zulip/integrations/jabber/jabber_mirror_backend.py index 18158f4..dfda56b 100755 --- a/zulip/integrations/jabber/jabber_mirror_backend.py +++ b/zulip/integrations/jabber/jabber_mirror_backend.py @@ -66,9 +66,11 @@ def jid_to_zulip(jid: JID) -> str: def zulip_to_jid(email: str, jabber_domain: str) -> JID: jid = JID(email, domain=jabber_domain) - if (options.zulip_email_suffix and - options.zulip_email_suffix in jid.username and - not jid.username.endswith("-bot")): + if ( + options.zulip_email_suffix + and options.zulip_email_suffix in jid.username + and not jid.username.endswith("-bot") + ): jid.username = jid.username.rpartition(options.zulip_email_suffix)[0] return jid @@ -393,8 +395,10 @@ option does not affect login credentials.'''.replace("\n", " ")) pass for option in ("jid", "jabber_password", "conference_domain", "mode", "zulip_email_suffix", "jabber_server_address", "jabber_server_port"): - if (getattr(options, option) is None and - config.has_option("jabber_mirror", option)): + if ( + getattr(options, option) is None + and config.has_option("jabber_mirror", option) + ): setattr(options, option, config.get("jabber_mirror", option)) for option in ("no_use_tls",): diff --git a/zulip/integrations/trac/zulip_trac.py b/zulip/integrations/trac/zulip_trac.py index 6afa913..d607721 100644 --- a/zulip/integrations/trac/zulip_trac.py +++ b/zulip/integrations/trac/zulip_trac.py @@ -74,8 +74,10 @@ class ZulipPlugin(Component): `old_values` is a dictionary containing the previous values of the fields that have changed. """ - if not (set(old_values.keys()).intersection(set(config.TRAC_NOTIFY_FIELDS)) or - (comment and "comment" in set(config.TRAC_NOTIFY_FIELDS))): + if not ( + set(old_values.keys()).intersection(set(config.TRAC_NOTIFY_FIELDS)) + or (comment and "comment" in set(config.TRAC_NOTIFY_FIELDS)) + ): return content = "%s updated %s" % (author, markdown_ticket_url(ticket)) diff --git a/zulip/integrations/zephyr/zephyr_mirror_backend.py b/zulip/integrations/zephyr/zephyr_mirror_backend.py index 617bc2e..9f7f17c 100755 --- a/zulip/integrations/zephyr/zephyr_mirror_backend.py +++ b/zulip/integrations/zephyr/zephyr_mirror_backend.py @@ -61,9 +61,11 @@ def to_zephyr_username(zulip_username: str) -> str: # line. def different_paragraph(line: str, next_line: str) -> bool: words = next_line.split() - return (len(line + " " + words[0]) < len(next_line) * 0.8 or - len(line + " " + words[0]) < 50 or - len(line) < len(words[0])) + return ( + len(line + " " + words[0]) < len(next_line) * 0.8 + or len(line + " " + words[0]) < 50 + or len(line) < len(words[0]) + ) # Linewrapping algorithm based on: # http://gcbenison.wordpress.com/2011/07/03/a-program-to-intelligently-remove-carriage-returns-so-you-can-paste-text-without-having-it-look-awful/ #ignorelongline @@ -73,13 +75,17 @@ def unwrap_lines(body: str) -> str: previous_line = lines[0] for line in lines[1:]: line = line.rstrip() - if (re.match(r'^\W', line, flags=re.UNICODE) and - re.match(r'^\W', previous_line, flags=re.UNICODE)): + if ( + re.match(r'^\W', line, flags=re.UNICODE) + and re.match(r'^\W', previous_line, flags=re.UNICODE) + ): result += previous_line + "\n" - elif (line == "" or - previous_line == "" or - re.match(r'^\W', line, flags=re.UNICODE) or - different_paragraph(previous_line, line)): + elif ( + line == "" + or previous_line == "" + or re.match(r'^\W', line, flags=re.UNICODE) + or different_paragraph(previous_line, line) + ): # Use 2 newlines to separate sections so that we # trigger proper Markdown processing on things like # bulleted lists @@ -178,8 +184,10 @@ def update_subscriptions() -> None: classes_to_subscribe = set() for stream in public_streams: zephyr_class = stream.encode("utf-8") - if (options.shard is not None and - not hashlib.sha1(zephyr_class).hexdigest().startswith(options.shard)): + if ( + options.shard is not None + and not hashlib.sha1(zephyr_class).hexdigest().startswith(options.shard) + ): # This stream is being handled by a different zephyr_mirror job. continue if zephyr_class in current_zephyr_subs: @@ -198,9 +206,10 @@ def maybe_kill_child() -> None: logger.exception("") def maybe_restart_mirroring_script() -> None: - if os.stat(os.path.join(options.stamp_path, "stamps", "restart_stamp")).st_mtime > start_time or \ - ((options.user == "tabbott" or options.user == "tabbott/extra") and - os.stat(os.path.join(options.stamp_path, "stamps", "tabbott_stamp")).st_mtime > start_time): + if os.stat(os.path.join(options.stamp_path, "stamps", "restart_stamp")).st_mtime > start_time or ( + (options.user == "tabbott" or options.user == "tabbott/extra") + and os.stat(os.path.join(options.stamp_path, "stamps", "tabbott_stamp")).st_mtime > start_time + ): logger.warning("") logger.warning("zephyr mirroring script has been updated; restarting...") maybe_kill_child() @@ -258,8 +267,10 @@ def process_loop(log: Optional[IO[Any]]) -> None: def parse_zephyr_body(zephyr_data: str, notice_format: str) -> Tuple[str, str]: try: (zsig, body) = zephyr_data.split("\x00", 1) - if (notice_format == 'New transaction [$1] entered in $2\nFrom: $3 ($5)\nSubject: $4' or - notice_format == 'New transaction [$1] entered in $2\nFrom: $3\nSubject: $4'): + if ( + notice_format == 'New transaction [$1] entered in $2\nFrom: $3 ($5)\nSubject: $4' + or notice_format == 'New transaction [$1] entered in $2\nFrom: $3\nSubject: $4' + ): # Logic based off of owl_zephyr_get_message in barnowl fields = body.split('\x00') if len(fields) == 5: @@ -351,8 +362,12 @@ def process_notice(notice: Any, log: Optional[IO[Any]]) -> None: if notice.format.startswith("Zephyr error: See") or notice.format.endswith("@(@color(blue))"): logger.debug("Skipping message we got from Zulip!") return - if (zephyr_class == "mail" and notice.instance.lower() == "inbox" and is_personal and - not options.forward_mail_zephyrs): + if ( + zephyr_class == "mail" + and notice.instance.lower() == "inbox" + and is_personal + and not options.forward_mail_zephyrs + ): # Only forward mail zephyrs if forwarding them is enabled. return @@ -606,8 +621,10 @@ Feedback button or at support@zulipchat.com.""" # Forward messages sent to '(instance "WHITESPACE")' back to the # appropriate WHITESPACE instance for bidirectional mirroring instance = match_whitespace_instance.group(1) - elif (instance == "instance %s" % (zephyr_class,) or - instance == "test instance %s" % (zephyr_class,)): + elif ( + instance == "instance %s" % (zephyr_class,) + or instance == "test instance %s" % (zephyr_class,) + ): # Forward messages to e.g. -c -i white-magic back from the # place we forward them to if instance.startswith("test"): @@ -675,8 +692,10 @@ returned the following warning: %s""" % (support_heading, stderr, support_closing)) return - elif code != 0 and (stderr.startswith("zwrite: Ticket expired while sending notice to ") or - stderr.startswith("zwrite: No credentials cache found while sending notice to ")): + elif code != 0 and ( + stderr.startswith("zwrite: Ticket expired while sending notice to ") + or stderr.startswith("zwrite: No credentials cache found while sending notice to ") + ): # Retry sending the message unauthenticated; if that works, # just notify the user that they need to renew their tickets (code, stderr) = send_unauthed_zephyr(zwrite_args, wrapped_content) @@ -711,10 +730,17 @@ received it, Zephyr users did not. The error message from zwrite was: def maybe_forward_to_zephyr(message: Dict[str, Any]) -> None: # The key string can be used to direct any type of text. if (message["sender_email"] == zulip_account_email): - if not ((message["type"] == "stream") or - (message["type"] == "private" and - False not in [u["email"].lower().endswith("mit.edu") for u in - message["display_recipient"]])): + if not ( + (message["type"] == "stream") + or ( + message["type"] == "private" + and False + not in [ + u["email"].lower().endswith("mit.edu") + for u in message["display_recipient"] + ] + ) + ): # Don't try forward private messages with non-MIT users # to MIT Zephyr. return diff --git a/zulip/zulip/__init__.py b/zulip/zulip/__init__.py index 12aa92e..378f190 100644 --- a/zulip/zulip/__init__.py +++ b/zulip/zulip/__init__.py @@ -55,9 +55,11 @@ class CountingBackoff: self.last_attempt_time = time.time() def _check_success_timeout(self) -> None: - if (self.timeout_success_equivalent is not None and - self.last_attempt_time != 0 and - time.time() - self.last_attempt_time > self.timeout_success_equivalent): + if ( + self.timeout_success_equivalent is not None + and self.last_attempt_time != 0 + and time.time() - self.last_attempt_time > self.timeout_success_equivalent + ): self.number_of_retries = 0 class RandomExponentialBackoff(CountingBackoff): @@ -236,8 +238,10 @@ def get_default_config_filename() -> Optional[str]: return None config_file = os.path.join(os.environ["HOME"], ".zuliprc") - if (not os.path.exists(config_file) and - os.path.exists(os.path.join(os.environ["HOME"], ".humbugrc"))): + if ( + not os.path.exists(config_file) + and os.path.exists(os.path.join(os.environ["HOME"], ".humbugrc")) + ): raise ZulipError("The Zulip API configuration file is now ~/.zuliprc; please run:\n\n" " mv ~/.humbugrc ~/.zuliprc\n") return config_file @@ -530,8 +534,10 @@ class Client: # Timeouts are either a Timeout or an SSLError; we # want the later exception handlers to deal with any # non-timeout other SSLErrors - if (isinstance(e, requests.exceptions.SSLError) and - str(e) != "The read operation timed out"): + if ( + isinstance(e, requests.exceptions.SSLError) + and str(e) != "The read operation timed out" + ): raise UnrecoverableNetworkError('SSL Error') if longpolling: # When longpolling, we expect the timeout to fire, diff --git a/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py b/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py index 45bef60..46eda42 100644 --- a/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py +++ b/zulip_bots/zulip_bots/bots/baremetrics/baremetrics.py @@ -147,10 +147,14 @@ class BaremetricsHandler: 'Amounts:']) response = ['**Listing plans:**'] for index, plan in enumerate(plans_data): - response += ([template.format(_count=index + 1, **plan)] + - [' - {amount} {currency}'.format(**amount) - for amount in plan['amounts']] + - ['']) + response += ( + [template.format(_count=index + 1, **plan)] + + [ + ' - {amount} {currency}'.format(**amount) + for amount in plan['amounts'] + ] + + [''] + ) return '\n'.join(response) @@ -171,10 +175,11 @@ class BaremetricsHandler: 'Current Plans:']) response = ['**Listing customers:**'] for index, customer in enumerate(customers_data): - response += ([template.format(_count=index + 1, **customer)] + - [' - {name}'.format(**plan) - for plan in customer['current_plans']] + - ['']) + response += ( + [template.format(_count=index + 1, **customer)] + + [' - {name}'.format(**plan) for plan in customer['current_plans']] + + [''] + ) return '\n'.join(response) @@ -194,13 +199,21 @@ class BaremetricsHandler: 'Plan Amounts:']) response = ['**Listing subscriptions:**'] for index, subscription in enumerate(subscriptions_data): - response += ([template.format(_count=index + 1, - _active=subscription['active'], - _plan_name=subscription['plan']['name'], - **subscription['customer'])] + - [' - {amount} {symbol}'.format(**amount) - for amount in subscription['plan']['amounts']] + - ['']) + response += ( + [ + template.format( + _count=index + 1, + _active=subscription['active'], + _plan_name=subscription['plan']['name'], + **subscription['customer'] + ) + ] + + [ + ' - {amount} {symbol}'.format(**amount) + for amount in subscription['plan']['amounts'] + ] + + [''] + ) return '\n'.join(response) diff --git a/zulip_bots/zulip_bots/bots/converter/converter.py b/zulip_bots/zulip_bots/bots/converter/converter.py index 1f2ef3c..cd546bd 100644 --- a/zulip_bots/zulip_bots/bots/converter/converter.py +++ b/zulip_bots/zulip_bots/bots/converter/converter.py @@ -95,8 +95,10 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: Any) -> str base_unit = uf_to_std[2] if uf_to_std[2] != ut_to_std[2]: unit_from = unit_from.capitalize() if uf_to_std[2] == 'kelvin' else unit_from - results.append('`' + unit_to.capitalize() + '` and `' + unit_from + '`' + - ' are not from the same category. ' + utils.QUICK_HELP) + results.append( + '`' + unit_to.capitalize() + '` and `' + unit_from + '`' + + ' are not from the same category. ' + utils.QUICK_HELP + ) continue # perform the conversion between the units diff --git a/zulip_bots/zulip_bots/bots/jira/jira.py b/zulip_bots/zulip_bots/bots/jira/jira.py index ea97f6a..01da474 100644 --- a/zulip_bots/zulip_bots/bots/jira/jira.py +++ b/zulip_bots/zulip_bots/bots/jira/jira.py @@ -332,14 +332,14 @@ def check_is_editing_something(match: Any) -> bool: - match: The regex match object. ''' return bool( - match.group('summary') or - match.group('project_key') or - match.group('type_name') or - match.group('description') or - match.group('assignee') or - match.group('priority_name') or - match.group('labels') or - match.group('due_date') + match.group('summary') + or match.group('project_key') + or match.group('type_name') + or match.group('description') + or match.group('assignee') + or match.group('priority_name') + or match.group('labels') + or match.group('due_date') ) handler_class = JiraHandler diff --git a/zulip_bots/zulip_bots/bots/mention/mention.py b/zulip_bots/zulip_bots/bots/mention/mention.py index 1519ca5..93732b5 100644 --- a/zulip_bots/zulip_bots/bots/mention/mention.py +++ b/zulip_bots/zulip_bots/bots/mention/mention.py @@ -75,8 +75,11 @@ class MentionHandler: 'sources': ['web'] } # type: Any - response = requests.post('https://api.mention.net/api/accounts/' + self.account_id + - '/alerts', data=create_alert_data, headers=create_alert_header) + response = requests.post( + 'https://api.mention.net/api/accounts/' + self.account_id + + '/alerts', + data=create_alert_data, headers=create_alert_header, + ) data_json = response.json() alert_id = data_json['alert']['id'] return alert_id @@ -86,8 +89,11 @@ class MentionHandler: 'Authorization': 'Bearer ' + self.access_token, 'Accept-Version': '1.15', } - response = requests.get('https://api.mention.net/api/accounts/' + self.account_id + - '/alerts/' + alert_id + '/mentions', headers=get_mentions_header) + response = requests.get( + 'https://api.mention.net/api/accounts/' + self.account_id + + '/alerts/' + alert_id + '/mentions', + headers=get_mentions_header, + ) data_json = response.json() mentions = data_json['mentions'] return mentions diff --git a/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py b/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py index 7676deb..840e4b1 100644 --- a/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py +++ b/zulip_bots/zulip_bots/bots/tictactoe/tictactoe.py @@ -56,8 +56,12 @@ class TicTacToeModel: ''' Returns true if all coordinates in a triplet have the same value in them (x or o) and no coordinates in the triplet are blank. ''' for triplet in self.triplets: - if (self.get_value(board, triplet[0]) == self.get_value(board, triplet[1]) == - self.get_value(board, triplet[2]) != 0): + if ( + self.get_value(board, triplet[0]) + == self.get_value(board, triplet[1]) + == self.get_value(board, triplet[2]) + != 0 + ): return True return False @@ -144,8 +148,12 @@ class TicTacToeModel: # Assuming nobody will win in their next move, now I'll find the best place for the computer to win. for row, col in blank_locations: - if (1 not in my_board[row] and my_board[0][col] != 1 and my_board[1][col] != - 1 and my_board[2][col] != 1): + if ( + 1 not in my_board[row] + and my_board[0][col] != 1 + and my_board[1][col] != 1 + and my_board[2][col] != 1 + ): board[row][col] = 2 return board