ruff: Fix SIM102 nested if statements.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg
2023-01-17 20:59:37 -05:00
committed by Tim Abbott
parent 50cf9bc4b8
commit b0e569f07c
38 changed files with 333 additions and 327 deletions

View File

@@ -79,9 +79,8 @@ def get_avatar_field(
will return None and let the client compute the gravatar
url.
"""
if settings.ENABLE_GRAVATAR:
if avatar_source == UserProfile.AVATAR_FROM_GRAVATAR:
return None
if settings.ENABLE_GRAVATAR and avatar_source == UserProfile.AVATAR_FROM_GRAVATAR:
return None
"""
If we get this far, we'll compute an avatar URL that may be
@@ -139,10 +138,9 @@ def absolute_avatar_url(user_profile: UserProfile) -> str:
def is_avatar_new(ldap_avatar: bytes, user_profile: UserProfile) -> bool:
new_avatar_hash = user_avatar_content_hash(ldap_avatar)
if user_profile.avatar_hash:
if user_profile.avatar_hash == new_avatar_hash:
# If an avatar exists and is the same as the new avatar,
# then, no need to change the avatar.
return False
if user_profile.avatar_hash and user_profile.avatar_hash == new_avatar_hash:
# If an avatar exists and is the same as the new avatar,
# then, no need to change the avatar.
return False
return True

View File

@@ -204,14 +204,16 @@ def fetch_initial_state_data(
user_draft_dicts = [draft.to_dict() for draft in user_draft_objects]
state["drafts"] = user_draft_dicts
if want("muted_topics"):
if want("muted_topics") and (
# Suppress muted_topics data for clients that explicitly
# support user_topic. This allows clients to request both the
# user_topic and muted_topics, and receive the duplicate
# muted_topics data only from older servers that don't yet
# support user_topic.
if event_types is None or not want("user_topic"):
state["muted_topics"] = [] if user_profile is None else get_topic_mutes(user_profile)
event_types is None
or not want("user_topic")
):
state["muted_topics"] = [] if user_profile is None else get_topic_mutes(user_profile)
if want("muted_users"):
state["muted_users"] = [] if user_profile is None else get_user_mutes(user_profile)
@@ -542,21 +544,20 @@ def fetch_initial_state_data(
[] if user_profile is None else get_starred_message_ids(user_profile)
)
if want("stream"):
if include_streams:
# The web app doesn't use the data from here; instead,
# it uses data from state["subscriptions"] and other
# places.
if user_profile is not None:
state["streams"] = do_get_streams(
user_profile, include_all_active=user_profile.is_realm_admin
)
else:
# TODO: This line isn't used by the web app because it
# gets these data via the `subscriptions` key; it will
# be used when the mobile apps support logged-out
# access.
state["streams"] = get_web_public_streams(realm) # nocoverage
if want("stream") and include_streams:
# The web app doesn't use the data from here; instead,
# it uses data from state["subscriptions"] and other
# places.
if user_profile is not None:
state["streams"] = do_get_streams(
user_profile, include_all_active=user_profile.is_realm_admin
)
else:
# TODO: This line isn't used by the web app because it
# gets these data via the `subscriptions` key; it will
# be used when the mobile apps support logged-out
# access.
state["streams"] = get_web_public_streams(realm) # nocoverage
if want("default_streams"):
if settings_user.is_guest:
# Guest users and logged-out users don't have access to
@@ -707,13 +708,17 @@ def apply_event(
# Below, we handle maintaining first_message_id.
for sub_dict in state.get("subscriptions", []):
if event["message"]["stream_id"] == sub_dict["stream_id"]:
if sub_dict["first_message_id"] is None:
sub_dict["first_message_id"] = event["message"]["id"]
if (
event["message"]["stream_id"] == sub_dict["stream_id"]
and sub_dict["first_message_id"] is None
):
sub_dict["first_message_id"] = event["message"]["id"]
for stream_dict in state.get("streams", []):
if event["message"]["stream_id"] == stream_dict["stream_id"]:
if stream_dict["first_message_id"] is None:
stream_dict["first_message_id"] = event["message"]["id"]
if (
event["message"]["stream_id"] == stream_dict["stream_id"]
and stream_dict["first_message_id"] is None
):
stream_dict["first_message_id"] = event["message"]["id"]
elif event["type"] == "heartbeat":
# It may be impossible for a heartbeat event to actually reach
@@ -767,9 +772,8 @@ def apply_event(
if event["op"] == "add":
person = copy.deepcopy(person)
if client_gravatar:
if person["avatar_url"].startswith("https://secure.gravatar.com/"):
person["avatar_url"] = None
if client_gravatar and person["avatar_url"].startswith("https://secure.gravatar.com/"):
person["avatar_url"] = None
person["is_active"] = True
if not person["is_bot"]:
person["profile_data"] = {}
@@ -857,11 +861,14 @@ def apply_event(
if not was_admin and now_admin:
state["realm_bots"] = get_owned_bot_dicts(user_profile)
if client_gravatar and "avatar_url" in person:
if (
client_gravatar
and "avatar_url" in person
# Respect the client_gravatar setting in the `users` data.
if person["avatar_url"].startswith("https://secure.gravatar.com/"):
person["avatar_url"] = None
person["avatar_url_medium"] = None
and person["avatar_url"].startswith("https://secure.gravatar.com/")
):
person["avatar_url"] = None
person["avatar_url_medium"] = None
if person_user_id in state["raw_users"]:
p = state["raw_users"][person_user_id]
@@ -1011,11 +1018,13 @@ def apply_event(
if permission in state:
state[permission] = user_profile.has_permission(policy)
if event["property"] in policy_permission_dict:
if policy_permission_dict[event["property"]] in state:
state[policy_permission_dict[event["property"]]] = user_profile.has_permission(
event["property"]
)
if (
event["property"] in policy_permission_dict
and policy_permission_dict[event["property"]] in state
):
state[policy_permission_dict[event["property"]]] = user_profile.has_permission(
event["property"]
)
# Finally, we need to recompute this value from its inputs.
state["can_create_streams"] = (

View File

@@ -1595,9 +1595,8 @@ def export_files_from_s3(
count = 0
for bkey in bucket.objects.filter(Prefix=object_prefix):
if valid_hashes is not None:
if bkey.Object().key not in valid_hashes:
continue
if valid_hashes is not None and bkey.Object().key not in valid_hashes:
continue
key = bucket.Object(bkey.key)

View File

@@ -306,9 +306,8 @@ def url_embed_preview_enabled(
if no_previews:
return False
if realm is None:
if message is not None:
realm = message.get_realm()
if realm is None and message is not None:
realm = message.get_realm()
if realm is None:
# realm can be None for odd use cases
@@ -328,9 +327,8 @@ def image_preview_enabled(
if no_previews:
return False
if realm is None:
if message is not None:
realm = message.get_realm()
if realm is None and message is not None:
realm = message.get_realm()
if realm is None:
# realm can be None for odd use cases
@@ -1780,12 +1778,16 @@ class MarkdownListPreprocessor(markdown.preprocessors.Preprocessor):
# a newline.
li1 = self.LI_RE.match(lines[i])
li2 = self.LI_RE.match(lines[i + 1])
if not in_code_fence and lines[i]:
if (li2 and not li1) or (
li1 and li2 and (len(li1.group(1)) == 1) != (len(li2.group(1)) == 1)
):
copy.insert(i + inserts + 1, "")
inserts += 1
if (
not in_code_fence
and lines[i]
and (
(li2 and not li1)
or (li1 and li2 and (len(li1.group(1)) == 1) != (len(li2.group(1)) == 1))
)
):
copy.insert(i + inserts + 1, "")
inserts += 1
return copy
@@ -1865,9 +1867,8 @@ class UserMentionPattern(CompiledInlineProcessor):
# name matches the full_name of user in mention_data.
# This enforces our decision that
# @**user_1_name|id_for_user_2** should be invalid syntax.
if full_name:
if user and user.full_name != full_name:
return None, None, None
if full_name and user and user.full_name != full_name:
return None, None, None
else:
# For @**name** syntax.
user = db_data.mention_data.get_user_by_name(name)
@@ -2538,9 +2539,8 @@ def do_convert(
# * Nothing is passed in other than content -> just run default options (e.g. for docs)
# * message is passed, but no realm is -> look up realm from message
# * message_realm is passed -> use that realm for Markdown purposes
if message is not None:
if message_realm is None:
message_realm = message.get_realm()
if message is not None and message_realm is None:
message_realm = message.get_realm()
if message_realm is None:
linkifiers_key = DEFAULT_MARKDOWN_KEY
else:
@@ -2551,12 +2551,15 @@ def do_convert(
else:
logging_message_id = "unknown"
if message is not None and message_realm is not None:
if message_realm.is_zephyr_mirror_realm:
if message.sending_client.name == "zephyr_mirror":
# Use slightly customized Markdown processor for content
# delivered via zephyr_mirror
linkifiers_key = ZEPHYR_MIRROR_MARKDOWN_KEY
if (
message is not None
and message_realm is not None
and message_realm.is_zephyr_mirror_realm
and message.sending_client.name == "zephyr_mirror"
):
# Use slightly customized Markdown processor for content
# delivered via zephyr_mirror
linkifiers_key = ZEPHYR_MIRROR_MARKDOWN_KEY
maybe_update_markdown_engines(linkifiers_key, email_gateway)
md_engine_key = (linkifiers_key, email_gateway)

View File

@@ -135,9 +135,8 @@ Missing required -X argument in curl command:
for line in lines:
regex = r'curl [-](sS)?X "?(GET|DELETE|PATCH|POST)"?'
if line.startswith("curl"):
if re.search(regex, line) is None:
raise MarkdownRenderingError(error_msg.format(command=line.strip()))
if line.startswith("curl") and re.search(regex, line) is None:
raise MarkdownRenderingError(error_msg.format(command=line.strip()))
CODE_VALIDATORS: Dict[Optional[str], Callable[[List[str]], None]] = {

View File

@@ -42,17 +42,18 @@ class NestedCodeBlocksRendererTreeProcessor(markdown.treeprocessors.Treeprocesso
for code_tag in code_tags:
parent: Any = code_tag.family.parent
grandparent: Any = code_tag.family.grandparent
if parent.tag == "p" and grandparent.tag == "li":
if (
parent.tag == "p"
and grandparent.tag == "li"
and parent.text is None
and len(list(parent)) == 1
and len(list(parent.itertext())) == 1
):
# if the parent (<p>) has no text, and no children,
# that means that the <code> element inside is its
# only thing inside the bullet, we can confidently say
# that this is a nested code block
if (
parent.text is None
and len(list(parent)) == 1
and len(list(parent.itertext())) == 1
):
nested_code_blocks.append(code_tag)
nested_code_blocks.append(code_tag)
return nested_code_blocks

View File

@@ -1284,10 +1284,12 @@ def apply_unread_message_event(
topic=topic,
)
if stream_id not in state["muted_stream_ids"]:
if (
stream_id not in state["muted_stream_ids"]
# This next check hits the database.
if not topic_is_muted(user_profile, stream_id, topic):
state["unmuted_stream_msgs"].add(message_id)
and not topic_is_muted(user_profile, stream_id, topic)
):
state["unmuted_stream_msgs"].add(message_id)
elif message_type == "private":
if len(others) == 1:
@@ -1311,9 +1313,8 @@ def apply_unread_message_event(
if "mentioned" in flags:
state["mentions"].add(message_id)
if "wildcard_mentioned" in flags:
if message_id in state["unmuted_stream_msgs"]:
state["mentions"].add(message_id)
if "wildcard_mentioned" in flags and message_id in state["unmuted_stream_msgs"]:
state["mentions"].add(message_id)
def remove_message_id_from_unread_mgs(state: RawUnreadMessagesResult, message_id: int) -> None:

View File

@@ -95,22 +95,23 @@ def filter_by_subscription_history(
stream_messages = stream_messages[i:]
break
final_msg_count = len(stream_messages)
if initial_msg_count == final_msg_count:
if stream_messages[-1]["id"] <= event_last_message_id:
stream_messages = []
if (
initial_msg_count == final_msg_count
and stream_messages[-1]["id"] <= event_last_message_id
):
stream_messages = []
else:
raise AssertionError(f"{log_entry.event_type} is not a subscription event.")
if len(stream_messages) > 0:
# We do this check for last event since if the last subscription
# event was a subscription_deactivated then we don't want to create
# UserMessage rows for any of the remaining messages.
if stream_subscription_logs[-1].event_type in (
RealmAuditLog.SUBSCRIPTION_ACTIVATED,
RealmAuditLog.SUBSCRIPTION_CREATED,
):
for stream_message in stream_messages:
store_user_message_to_insert(stream_message)
# We do this check for last event since if the last subscription
# event was a subscription_deactivated then we don't want to create
# UserMessage rows for any of the remaining messages.
if len(stream_messages) > 0 and stream_subscription_logs[-1].event_type in (
RealmAuditLog.SUBSCRIPTION_ACTIVATED,
RealmAuditLog.SUBSCRIPTION_CREATED,
):
for stream_message in stream_messages:
store_user_message_to_insert(stream_message)
return user_messages_to_insert

View File

@@ -284,9 +284,8 @@ def validate_user_access_to_subscribers_helper(
# With the exception of web-public streams, a guest must
# be subscribed to a stream (even a public one) in order
# to see subscribers.
if user_profile.is_guest:
if check_user_subscribed(user_profile):
return
if user_profile.is_guest and check_user_subscribed(user_profile):
return
# We could explicitly handle the case where guests aren't
# subscribed here in an `else` statement or we can fall
# through to the subsequent logic. Tim prefers the latter.

View File

@@ -1019,10 +1019,13 @@ Output:
body=content,
realm=recipient_realm,
)
if not UserMessage.objects.filter(user_profile=sender, message_id=message_id).exists():
if not sender.is_bot and not allow_unsubscribed_sender:
raise AssertionError(
f"""
if (
not UserMessage.objects.filter(user_profile=sender, message_id=message_id).exists()
and not sender.is_bot
and not allow_unsubscribed_sender
):
raise AssertionError(
f"""
It appears that the sender did not get a UserMessage row, which is
almost certainly an artificial symptom that in your test setup you
have decided to send a message to a stream without the sender being
@@ -1034,7 +1037,7 @@ Output:
{self.subscribed_stream_name_list(sender)}
"""
)
)
return message_id

View File

@@ -84,7 +84,7 @@ def check_send_webhook_message(
),
unquote_url_parameters: bool = False,
) -> None:
if complete_event_type is not None:
if complete_event_type is not None and (
# Here, we implement Zulip's generic support for filtering
# events sent by the third-party service.
#
@@ -95,14 +95,16 @@ def check_send_webhook_message(
#
# We match items in only_events and exclude_events using Unix
# shell-style wildcards.
if (
(
only_events is not None
and all(not fnmatch.fnmatch(complete_event_type, pattern) for pattern in only_events)
) or (
)
or (
exclude_events is not None
and any(fnmatch.fnmatch(complete_event_type, pattern) for pattern in exclude_events)
):
return
)
):
return
client = RequestNotes.get_notes(request).client
assert client is not None
@@ -150,9 +152,11 @@ def standardize_headers(input_headers: Union[None, Dict[str, Any]]) -> Dict[str,
for raw_header in input_headers:
polished_header = raw_header.upper().replace("-", "_")
if polished_header not in ["CONTENT_TYPE", "CONTENT_LENGTH"]:
if not polished_header.startswith("HTTP_"):
polished_header = "HTTP_" + polished_header
if polished_header not in [
"CONTENT_TYPE",
"CONTENT_LENGTH",
] and not polished_header.startswith("HTTP_"):
polished_header = "HTTP_" + polished_header
canonical_headers[polished_header] = str(input_headers[raw_header])
return canonical_headers

View File

@@ -217,13 +217,16 @@ def get_pull_request_event_message(
main_message = f"{main_message} {branch_info}"
punctuation = ":" if message else "."
if assignees or assignee or (target_branch and base_branch) or (title is None):
main_message = f"{main_message}{punctuation}"
elif title is not None:
if (
assignees
or assignee
or (target_branch and base_branch)
or title is None
# Once we get here, we know that the message ends with a title
# which could already have punctuation at the end
if title[-1] not in string.punctuation:
main_message = f"{main_message}{punctuation}"
or title[-1] not in string.punctuation
):
main_message = f"{main_message}{punctuation}"
if message:
main_message += "\n" + CONTENT_MESSAGE_TEMPLATE.format(message=message)