cleanup: Move line breaks before binary operators.

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
This commit is contained in:
Anders Kaseorg 2020-04-18 17:33:01 -07:00 committed by Tim Abbott
parent 6f40bcf745
commit 17cf26aa1f
12 changed files with 152 additions and 77 deletions

View file

@ -68,6 +68,10 @@ def check_pep8(files: List[str]) -> bool:
# own check for this (see max_length) # own check for this (see max_length)
'E501', '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" # "do not assign a lambda expression, use a def"
# Fixing these would probably reduce readability in most cases. # Fixing these would probably reduce readability in most cases.
'E731', 'E731',

View file

@ -75,8 +75,10 @@ def matrix_to_zulip(
zulip_bot_user = ('@%s:matrix.org' % matrix_config['username']) zulip_bot_user = ('@%s:matrix.org' % matrix_config['username'])
# We do this to identify the messages generated from Zulip -> Matrix # 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. # and we make sure we don't forward it again to the Zulip stream.
not_from_zulip_bot = ('body' not in event['content'] or not_from_zulip_bot = (
event['sender'] != zulip_bot_user) 'body' not in event['content']
or event['sender'] != zulip_bot_user
)
if not_from_zulip_bot and content: if not_from_zulip_bot and content:
try: try:

View file

@ -59,8 +59,10 @@ def send_bot_message(oldrev: str, newrev: str, refname: str) -> None:
new_head = newrev[:12] new_head = newrev[:12]
old_head = oldrev[:12] old_head = oldrev[:12]
if (oldrev == '0000000000000000000000000000000000000000' or if (
newrev == '0000000000000000000000000000000000000000'): oldrev == '0000000000000000000000000000000000000000'
or newrev == '0000000000000000000000000000000000000000'
):
# New branch pushed or old branch removed # New branch pushed or old branch removed
added = '' added = ''
removed = '' removed = ''

View file

@ -66,9 +66,11 @@ def jid_to_zulip(jid: JID) -> str:
def zulip_to_jid(email: str, jabber_domain: str) -> JID: def zulip_to_jid(email: str, jabber_domain: str) -> JID:
jid = JID(email, domain=jabber_domain) jid = JID(email, domain=jabber_domain)
if (options.zulip_email_suffix and if (
options.zulip_email_suffix in jid.username and options.zulip_email_suffix
not jid.username.endswith("-bot")): and options.zulip_email_suffix in jid.username
and not jid.username.endswith("-bot")
):
jid.username = jid.username.rpartition(options.zulip_email_suffix)[0] jid.username = jid.username.rpartition(options.zulip_email_suffix)[0]
return jid return jid
@ -393,8 +395,10 @@ option does not affect login credentials.'''.replace("\n", " "))
pass pass
for option in ("jid", "jabber_password", "conference_domain", "mode", "zulip_email_suffix", for option in ("jid", "jabber_password", "conference_domain", "mode", "zulip_email_suffix",
"jabber_server_address", "jabber_server_port"): "jabber_server_address", "jabber_server_port"):
if (getattr(options, option) is None and if (
config.has_option("jabber_mirror", option)): getattr(options, option) is None
and config.has_option("jabber_mirror", option)
):
setattr(options, option, config.get("jabber_mirror", option)) setattr(options, option, config.get("jabber_mirror", option))
for option in ("no_use_tls",): for option in ("no_use_tls",):

View file

@ -74,8 +74,10 @@ class ZulipPlugin(Component):
`old_values` is a dictionary containing the previous values of the `old_values` is a dictionary containing the previous values of the
fields that have changed. fields that have changed.
""" """
if not (set(old_values.keys()).intersection(set(config.TRAC_NOTIFY_FIELDS)) or if not (
(comment and "comment" in set(config.TRAC_NOTIFY_FIELDS))): set(old_values.keys()).intersection(set(config.TRAC_NOTIFY_FIELDS))
or (comment and "comment" in set(config.TRAC_NOTIFY_FIELDS))
):
return return
content = "%s updated %s" % (author, markdown_ticket_url(ticket)) content = "%s updated %s" % (author, markdown_ticket_url(ticket))

View file

@ -61,9 +61,11 @@ def to_zephyr_username(zulip_username: str) -> str:
# line. # line.
def different_paragraph(line: str, next_line: str) -> bool: def different_paragraph(line: str, next_line: str) -> bool:
words = next_line.split() words = next_line.split()
return (len(line + " " + words[0]) < len(next_line) * 0.8 or return (
len(line + " " + words[0]) < 50 or len(line + " " + words[0]) < len(next_line) * 0.8
len(line) < len(words[0])) or len(line + " " + words[0]) < 50
or len(line) < len(words[0])
)
# Linewrapping algorithm based on: # 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 # 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] previous_line = lines[0]
for line in lines[1:]: for line in lines[1:]:
line = line.rstrip() line = line.rstrip()
if (re.match(r'^\W', line, flags=re.UNICODE) and if (
re.match(r'^\W', previous_line, flags=re.UNICODE)): re.match(r'^\W', line, flags=re.UNICODE)
and re.match(r'^\W', previous_line, flags=re.UNICODE)
):
result += previous_line + "\n" result += previous_line + "\n"
elif (line == "" or elif (
previous_line == "" or line == ""
re.match(r'^\W', line, flags=re.UNICODE) or or previous_line == ""
different_paragraph(previous_line, 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 # Use 2 newlines to separate sections so that we
# trigger proper Markdown processing on things like # trigger proper Markdown processing on things like
# bulleted lists # bulleted lists
@ -178,8 +184,10 @@ def update_subscriptions() -> None:
classes_to_subscribe = set() classes_to_subscribe = set()
for stream in public_streams: for stream in public_streams:
zephyr_class = stream.encode("utf-8") zephyr_class = stream.encode("utf-8")
if (options.shard is not None and if (
not hashlib.sha1(zephyr_class).hexdigest().startswith(options.shard)): 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. # This stream is being handled by a different zephyr_mirror job.
continue continue
if zephyr_class in current_zephyr_subs: if zephyr_class in current_zephyr_subs:
@ -198,9 +206,10 @@ def maybe_kill_child() -> None:
logger.exception("") logger.exception("")
def maybe_restart_mirroring_script() -> None: def maybe_restart_mirroring_script() -> None:
if os.stat(os.path.join(options.stamp_path, "stamps", "restart_stamp")).st_mtime > start_time or \ 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 (options.user == "tabbott" or options.user == "tabbott/extra")
os.stat(os.path.join(options.stamp_path, "stamps", "tabbott_stamp")).st_mtime > start_time): and os.stat(os.path.join(options.stamp_path, "stamps", "tabbott_stamp")).st_mtime > start_time
):
logger.warning("") logger.warning("")
logger.warning("zephyr mirroring script has been updated; restarting...") logger.warning("zephyr mirroring script has been updated; restarting...")
maybe_kill_child() 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]: def parse_zephyr_body(zephyr_data: str, notice_format: str) -> Tuple[str, str]:
try: try:
(zsig, body) = zephyr_data.split("\x00", 1) (zsig, body) = zephyr_data.split("\x00", 1)
if (notice_format == 'New transaction [$1] entered in $2\nFrom: $3 ($5)\nSubject: $4' or if (
notice_format == 'New transaction [$1] entered in $2\nFrom: $3\nSubject: $4'): 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 # Logic based off of owl_zephyr_get_message in barnowl
fields = body.split('\x00') fields = body.split('\x00')
if len(fields) == 5: 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))"): if notice.format.startswith("Zephyr error: See") or notice.format.endswith("@(@color(blue))"):
logger.debug("Skipping message we got from Zulip!") logger.debug("Skipping message we got from Zulip!")
return return
if (zephyr_class == "mail" and notice.instance.lower() == "inbox" and is_personal and if (
not options.forward_mail_zephyrs): 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. # Only forward mail zephyrs if forwarding them is enabled.
return return
@ -606,8 +621,10 @@ Feedback button or at support@zulipchat.com."""
# Forward messages sent to '(instance "WHITESPACE")' back to the # Forward messages sent to '(instance "WHITESPACE")' back to the
# appropriate WHITESPACE instance for bidirectional mirroring # appropriate WHITESPACE instance for bidirectional mirroring
instance = match_whitespace_instance.group(1) instance = match_whitespace_instance.group(1)
elif (instance == "instance %s" % (zephyr_class,) or elif (
instance == "test instance %s" % (zephyr_class,)): instance == "instance %s" % (zephyr_class,)
or instance == "test instance %s" % (zephyr_class,)
):
# Forward messages to e.g. -c -i white-magic back from the # Forward messages to e.g. -c -i white-magic back from the
# place we forward them to # place we forward them to
if instance.startswith("test"): if instance.startswith("test"):
@ -675,8 +692,10 @@ returned the following warning:
%s""" % (support_heading, stderr, support_closing)) %s""" % (support_heading, stderr, support_closing))
return return
elif code != 0 and (stderr.startswith("zwrite: Ticket expired while sending notice to ") or elif code != 0 and (
stderr.startswith("zwrite: No credentials cache found while sending notice to ")): 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, # Retry sending the message unauthenticated; if that works,
# just notify the user that they need to renew their tickets # just notify the user that they need to renew their tickets
(code, stderr) = send_unauthed_zephyr(zwrite_args, wrapped_content) (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: def maybe_forward_to_zephyr(message: Dict[str, Any]) -> None:
# The key string can be used to direct any type of text. # The key string can be used to direct any type of text.
if (message["sender_email"] == zulip_account_email): if (message["sender_email"] == zulip_account_email):
if not ((message["type"] == "stream") or if not (
(message["type"] == "private" and (message["type"] == "stream")
False not in [u["email"].lower().endswith("mit.edu") for u in or (
message["display_recipient"]])): 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 # Don't try forward private messages with non-MIT users
# to MIT Zephyr. # to MIT Zephyr.
return return

View file

@ -55,9 +55,11 @@ class CountingBackoff:
self.last_attempt_time = time.time() self.last_attempt_time = time.time()
def _check_success_timeout(self) -> None: def _check_success_timeout(self) -> None:
if (self.timeout_success_equivalent is not None and if (
self.last_attempt_time != 0 and self.timeout_success_equivalent is not None
time.time() - self.last_attempt_time > self.timeout_success_equivalent): and self.last_attempt_time != 0
and time.time() - self.last_attempt_time > self.timeout_success_equivalent
):
self.number_of_retries = 0 self.number_of_retries = 0
class RandomExponentialBackoff(CountingBackoff): class RandomExponentialBackoff(CountingBackoff):
@ -236,8 +238,10 @@ def get_default_config_filename() -> Optional[str]:
return None return None
config_file = os.path.join(os.environ["HOME"], ".zuliprc") config_file = os.path.join(os.environ["HOME"], ".zuliprc")
if (not os.path.exists(config_file) and if (
os.path.exists(os.path.join(os.environ["HOME"], ".humbugrc"))): 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" raise ZulipError("The Zulip API configuration file is now ~/.zuliprc; please run:\n\n"
" mv ~/.humbugrc ~/.zuliprc\n") " mv ~/.humbugrc ~/.zuliprc\n")
return config_file return config_file
@ -530,8 +534,10 @@ class Client:
# Timeouts are either a Timeout or an SSLError; we # Timeouts are either a Timeout or an SSLError; we
# want the later exception handlers to deal with any # want the later exception handlers to deal with any
# non-timeout other SSLErrors # non-timeout other SSLErrors
if (isinstance(e, requests.exceptions.SSLError) and if (
str(e) != "The read operation timed out"): isinstance(e, requests.exceptions.SSLError)
and str(e) != "The read operation timed out"
):
raise UnrecoverableNetworkError('SSL Error') raise UnrecoverableNetworkError('SSL Error')
if longpolling: if longpolling:
# When longpolling, we expect the timeout to fire, # When longpolling, we expect the timeout to fire,

View file

@ -147,10 +147,14 @@ class BaremetricsHandler:
'Amounts:']) 'Amounts:'])
response = ['**Listing plans:**'] response = ['**Listing plans:**']
for index, plan in enumerate(plans_data): for index, plan in enumerate(plans_data):
response += ([template.format(_count=index + 1, **plan)] + response += (
[' - {amount} {currency}'.format(**amount) [template.format(_count=index + 1, **plan)]
for amount in plan['amounts']] + + [
['']) ' - {amount} {currency}'.format(**amount)
for amount in plan['amounts']
]
+ ['']
)
return '\n'.join(response) return '\n'.join(response)
@ -171,10 +175,11 @@ class BaremetricsHandler:
'Current Plans:']) 'Current Plans:'])
response = ['**Listing customers:**'] response = ['**Listing customers:**']
for index, customer in enumerate(customers_data): for index, customer in enumerate(customers_data):
response += ([template.format(_count=index + 1, **customer)] + response += (
[' - {name}'.format(**plan) [template.format(_count=index + 1, **customer)]
for plan in customer['current_plans']] + + [' - {name}'.format(**plan) for plan in customer['current_plans']]
['']) + ['']
)
return '\n'.join(response) return '\n'.join(response)
@ -194,13 +199,21 @@ class BaremetricsHandler:
'Plan Amounts:']) 'Plan Amounts:'])
response = ['**Listing subscriptions:**'] response = ['**Listing subscriptions:**']
for index, subscription in enumerate(subscriptions_data): for index, subscription in enumerate(subscriptions_data):
response += ([template.format(_count=index + 1, response += (
[
template.format(
_count=index + 1,
_active=subscription['active'], _active=subscription['active'],
_plan_name=subscription['plan']['name'], _plan_name=subscription['plan']['name'],
**subscription['customer'])] + **subscription['customer']
[' - {amount} {symbol}'.format(**amount) )
for amount in subscription['plan']['amounts']] + ]
['']) + [
' - {amount} {symbol}'.format(**amount)
for amount in subscription['plan']['amounts']
]
+ ['']
)
return '\n'.join(response) return '\n'.join(response)

View file

@ -95,8 +95,10 @@ def get_bot_converter_response(message: Dict[str, str], bot_handler: Any) -> str
base_unit = uf_to_std[2] base_unit = uf_to_std[2]
if uf_to_std[2] != ut_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 unit_from = unit_from.capitalize() if uf_to_std[2] == 'kelvin' else unit_from
results.append('`' + unit_to.capitalize() + '` and `' + unit_from + '`' + results.append(
' are not from the same category. ' + utils.QUICK_HELP) '`' + unit_to.capitalize() + '` and `' + unit_from + '`'
+ ' are not from the same category. ' + utils.QUICK_HELP
)
continue continue
# perform the conversion between the units # perform the conversion between the units

View file

@ -332,14 +332,14 @@ def check_is_editing_something(match: Any) -> bool:
- match: The regex match object. - match: The regex match object.
''' '''
return bool( return bool(
match.group('summary') or match.group('summary')
match.group('project_key') or or match.group('project_key')
match.group('type_name') or or match.group('type_name')
match.group('description') or or match.group('description')
match.group('assignee') or or match.group('assignee')
match.group('priority_name') or or match.group('priority_name')
match.group('labels') or or match.group('labels')
match.group('due_date') or match.group('due_date')
) )
handler_class = JiraHandler handler_class = JiraHandler

View file

@ -75,8 +75,11 @@ class MentionHandler:
'sources': ['web'] 'sources': ['web']
} # type: Any } # type: Any
response = requests.post('https://api.mention.net/api/accounts/' + self.account_id + response = requests.post(
'/alerts', data=create_alert_data, headers=create_alert_header) 'https://api.mention.net/api/accounts/' + self.account_id
+ '/alerts',
data=create_alert_data, headers=create_alert_header,
)
data_json = response.json() data_json = response.json()
alert_id = data_json['alert']['id'] alert_id = data_json['alert']['id']
return alert_id return alert_id
@ -86,8 +89,11 @@ class MentionHandler:
'Authorization': 'Bearer ' + self.access_token, 'Authorization': 'Bearer ' + self.access_token,
'Accept-Version': '1.15', 'Accept-Version': '1.15',
} }
response = requests.get('https://api.mention.net/api/accounts/' + self.account_id + response = requests.get(
'/alerts/' + alert_id + '/mentions', headers=get_mentions_header) 'https://api.mention.net/api/accounts/' + self.account_id
+ '/alerts/' + alert_id + '/mentions',
headers=get_mentions_header,
)
data_json = response.json() data_json = response.json()
mentions = data_json['mentions'] mentions = data_json['mentions']
return mentions return mentions

View file

@ -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 ''' 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. ''' in the triplet are blank. '''
for triplet in self.triplets: for triplet in self.triplets:
if (self.get_value(board, triplet[0]) == self.get_value(board, triplet[1]) == if (
self.get_value(board, triplet[2]) != 0): self.get_value(board, triplet[0])
== self.get_value(board, triplet[1])
== self.get_value(board, triplet[2])
!= 0
):
return True return True
return False 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. # 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: for row, col in blank_locations:
if (1 not in my_board[row] and my_board[0][col] != 1 and my_board[1][col] != if (
1 and my_board[2][col] != 1): 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 board[row][col] = 2
return board return board