ruff: Fix SIM102 Use a single if statement instead of nested if statements.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-10-29 17:08:47 -07:00
parent c75f5b3a09
commit 58a3026f37
5 changed files with 53 additions and 61 deletions

View file

@ -489,16 +489,13 @@ def process_notice(
# Only forward mail zephyrs if forwarding them is enabled. # Only forward mail zephyrs if forwarding them is enabled.
return return
if is_personal: if is_personal and body.startswith("CC:"):
if body.startswith("CC:"): is_huddle = True
is_huddle = True # Map "CC: user1 user2" => "user1@mit.edu, user2@mit.edu"
# Map "CC: user1 user2" => "user1@mit.edu, user2@mit.edu" huddle_recipients = [to_zulip_username(x.strip()) for x in body.split("\n")[0][4:].split()]
huddle_recipients = [ if zephyr_sender not in huddle_recipients:
to_zulip_username(x.strip()) for x in body.split("\n")[0][4:].split() huddle_recipients.append(to_zulip_username(zephyr_sender))
] body = body.split("\n", 1)[1]
if zephyr_sender not in huddle_recipients:
huddle_recipients.append(to_zulip_username(zephyr_sender))
body = body.split("\n", 1)[1]
if ( if (
options.forward_class_messages options.forward_class_messages
@ -1045,13 +1042,12 @@ on these streams and already use Zulip. They can subscribe you to them via the
", ".join(unauthorized), ", ".join(unauthorized),
) )
if len(skipped) > 0: if len(skipped) > 0 and verbose:
if verbose: logger.info(
logger.info( "\n%s\n",
"\n%s\n", "\n".join(
"\n".join( textwrap.wrap(
textwrap.wrap( """\
"""\
You have some lines in ~/.zephyr.subs that could not be You have some lines in ~/.zephyr.subs that could not be
synced to your Zulip subscriptions because they do not synced to your Zulip subscriptions because they do not
use "*" as both the instance and recipient and not one of use "*" as both the instance and recipient and not one of
@ -1061,9 +1057,9 @@ allow subscribing to only some subjects on a Zulip
stream, so this tool has not created a corresponding stream, so this tool has not created a corresponding
Zulip subscription to these lines in ~/.zephyr.subs: Zulip subscription to these lines in ~/.zephyr.subs:
""" """
) )
), ),
) )
for cls, instance, recipient, reason in skipped: for cls, instance, recipient, reason in skipped:
if verbose: if verbose:
@ -1071,20 +1067,19 @@ Zulip subscription to these lines in ~/.zephyr.subs:
logger.info(" [%s,%s,%s] (%s)", cls, instance, recipient, reason) logger.info(" [%s,%s,%s] (%s)", cls, instance, recipient, reason)
else: else:
logger.info(" [%s,%s,%s]", cls, instance, recipient) logger.info(" [%s,%s,%s]", cls, instance, recipient)
if len(skipped) > 0: if len(skipped) > 0 and verbose:
if verbose: logger.info(
logger.info( "\n%s\n",
"\n%s\n", "\n".join(
"\n".join( textwrap.wrap(
textwrap.wrap( """\
"""\
If you wish to be subscribed to any Zulip streams related If you wish to be subscribed to any Zulip streams related
to these .zephyrs.subs lines, please do so via the Zulip to these .zephyrs.subs lines, please do so via the Zulip
web interface. web interface.
""" """
) )
), ),
) )
def valid_stream_name(name: str) -> bool: def valid_stream_name(name: str) -> bool:

View file

@ -501,9 +501,8 @@ class Client:
else: # we have a client cert else: # we have a client cert
if not os.path.isfile(client_cert): if not os.path.isfile(client_cert):
raise ConfigNotFoundError(f"client cert '{client_cert}' does not exist") raise ConfigNotFoundError(f"client cert '{client_cert}' does not exist")
if client_cert_key is not None: if client_cert_key is not None and not os.path.isfile(client_cert_key):
if not os.path.isfile(client_cert_key): raise ConfigNotFoundError(f"client cert key '{client_cert_key}' does not exist")
raise ConfigNotFoundError(f"client cert key '{client_cert_key}' does not exist")
self.client_cert = client_cert self.client_cert = client_cert
self.client_cert_key = client_cert_key self.client_cert_key = client_cert_key
@ -652,10 +651,11 @@ class Client:
self.has_connected = True self.has_connected = True
# On 50x errors, try again after a short sleep # On 50x errors, try again after a short sleep
if str(res.status_code).startswith("5"): if str(res.status_code).startswith("5") and error_retry(
if error_retry(f" (server {res.status_code})"): f" (server {res.status_code})"
continue ):
# Otherwise fall through and process the python-requests error normally continue
# Otherwise fall through and process the python-requests error normally
except (requests.exceptions.Timeout, requests.exceptions.SSLError) as e: except (requests.exceptions.Timeout, requests.exceptions.SSLError) as e:
# 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

View file

@ -29,9 +29,11 @@ def get_bot_result(message_content: str, config: Dict[str, str], sender_id: str)
res_json["status"]["code"], res_json["status"]["errorDetails"] res_json["status"]["code"], res_json["status"]["errorDetails"]
) )
if res_json["result"]["fulfillment"]["speech"] == "": if res_json["result"]["fulfillment"]["speech"] == "":
if "alternateResult" in res_json.keys(): if (
if res_json["alternateResult"]["fulfillment"]["speech"] != "": "alternateResult" in res_json.keys()
return res_json["alternateResult"]["fulfillment"]["speech"] and res_json["alternateResult"]["fulfillment"]["speech"] != ""
):
return res_json["alternateResult"]["fulfillment"]["speech"]
return "Error. No result." return "Error. No result."
return res_json["result"]["fulfillment"]["speech"] return res_json["result"]["fulfillment"]["speech"]
except Exception as e: except Exception as e:

View file

@ -34,12 +34,10 @@ class MerelsModel:
merels = database.MerelsStorage(self.topic, self.storage) merels = database.MerelsStorage(self.topic, self.storage)
data = game_data.GameData(merels.get_game_data(self.topic)) data = game_data.GameData(merels.get_game_data(self.topic))
if data.get_phase() > 1: return data.get_phase() > 1 and (
if (mechanics.get_piece("X", data.grid()) <= 2) or ( (mechanics.get_piece("X", data.grid()) <= 2)
mechanics.get_piece("O", data.grid()) <= 2 or (mechanics.get_piece("O", data.grid()) <= 2)
): )
return True
return False
def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any: def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any:
if self.storage.get(self.topic) == '["X", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]': if self.storage.get(self.topic) == '["X", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]':

View file

@ -603,9 +603,8 @@ class GameAdapter:
def get_user_by_name(self, name: str) -> Dict[str, Any]: def get_user_by_name(self, name: str) -> Dict[str, Any]:
name = name.strip() name = name.strip()
for user in self.user_cache.values(): for user in self.user_cache.values():
if "full_name" in user.keys(): if "full_name" in user.keys() and user["full_name"].lower() == name.lower():
if user["full_name"].lower() == name.lower(): return user
return user
return {} return {}
def get_number_of_players(self, game_id: str) -> int: def get_number_of_players(self, game_id: str) -> int:
@ -756,9 +755,8 @@ To move subjects, send your message again, otherwise join the game using the lin
return False return False
for invite in self.invites.values(): for invite in self.invites.values():
for u in invite.keys(): for u in invite.keys():
if u == "host": if u == "host" and user_email == invite["host"]:
if user_email == invite["host"]: return False
return False
if u == user_email and "a" in invite[u]: if u == user_email and "a" in invite[u]:
return False return False
return True return True
@ -776,15 +774,14 @@ To move subjects, send your message again, otherwise join the game using the lin
if private_recipients is not None: if private_recipients is not None:
for user in private_recipients: for user in private_recipients:
self.send_message(user, content, True) self.send_message(user, content, True)
if game_id in self.invites.keys(): if game_id in self.invites.keys() and self.invites[game_id]["subject"] != "###private###":
if self.invites[game_id]["subject"] != "###private###": self.send_message(
self.send_message( self.invites[game_id]["stream"],
self.invites[game_id]["stream"], content,
content, False,
False, self.invites[game_id]["subject"],
self.invites[game_id]["subject"], )
) return True
return True
if game_id in self.instances.keys(): if game_id in self.instances.keys():
self.send_message( self.send_message(
self.instances[game_id].stream, content, False, self.instances[game_id].subject self.instances[game_id].stream, content, False, self.instances[game_id].subject