Skip to content

Commit

Permalink
ruff: Fix SIM102 nested if statements.
Browse files Browse the repository at this point in the history
Signed-off-by: Anders Kaseorg <[email protected]>
  • Loading branch information
andersk authored and timabbott committed Jan 23, 2023
1 parent 50cf9bc commit b0e569f
Show file tree
Hide file tree
Showing 38 changed files with 333 additions and 327 deletions.
15 changes: 7 additions & 8 deletions analytics/tests/test_counts.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,14 +227,13 @@ def assertTableState(
kwargs[arg_keys[i]] = values[i]
for key, value in defaults.items():
kwargs[key] = kwargs.get(key, value)
if table is not InstallationCount:
if "realm" not in kwargs:
if "user" in kwargs:
kwargs["realm"] = kwargs["user"].realm
elif "stream" in kwargs:
kwargs["realm"] = kwargs["stream"].realm
else:
kwargs["realm"] = self.default_realm
if table is not InstallationCount and "realm" not in kwargs:
if "user" in kwargs:
kwargs["realm"] = kwargs["user"].realm
elif "stream" in kwargs:
kwargs["realm"] = kwargs["stream"].realm
else:
kwargs["realm"] = self.default_realm
self.assertEqual(table.objects.filter(**kwargs).count(), 1)
self.assert_length(arg_values, table.objects.count())

Expand Down
5 changes: 2 additions & 3 deletions manage.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,8 @@ def get_filtered_commands() -> Dict[str, str]:
for command, app in all_commands.items():
if app not in documented_apps:
continue
if app in documented_command_subsets:
if command not in documented_command_subsets[app]:
continue
if app in documented_command_subsets and command not in documented_command_subsets[app]:
continue

documented_commands[command] = app
return documented_commands
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,17 @@ if not options.nagios and not options.munin:
print("No output options specified! Please provide --munin or --nagios")
sys.exit(0)

if options.munin:
if options.config == "config":
print(
"""graph_title Send-Receive times
if options.munin and options.config == "config":
print(
"""graph_title Send-Receive times
graph_info The number of seconds it takes to send and receive a message from the server
graph_args -u 5 -l 0
graph_vlabel RTT (seconds)
sendreceive.label Send-receive round trip time
sendreceive.warning 3
sendreceive.critical 5"""
)
sys.exit(0)
)
sys.exit(0)

sys.path.append("/home/zulip/deployments/current")
os.environ["DJANGO_SETTINGS_MODULE"] = "zproject.settings"
Expand Down
8 changes: 5 additions & 3 deletions tools/check-schemas
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,13 @@ def from_openapi(node: Dict[str, Any]) -> Any:
return UnionType([from_openapi(n) for n in node["oneOf"]])

if node["type"] == "object":
if "additionalProperties" in node:
if (
"additionalProperties" in node
# this might be a glitch in our current spec? or
# maybe I just understand it yet
if isinstance(node["additionalProperties"], dict):
return StringDictType(from_openapi(node["additionalProperties"]))
and isinstance(node["additionalProperties"], dict)
):
return StringDictType(from_openapi(node["additionalProperties"]))

if "properties" not in node:
return dict
Expand Down
5 changes: 2 additions & 3 deletions tools/create-test-api-docs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,8 @@ def clean_up_pattern(s: str) -> str:
paren_level += 1
if c == "<" and prior_char == "P":
in_braces = True
if in_braces or (paren_level == 0):
if c != "?":
result += c
if (in_braces or paren_level == 0) and c != "?":
result += c
if c == ")":
paren_level -= 1
if c == ">":
Expand Down
9 changes: 6 additions & 3 deletions tools/lib/pretty_print.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,12 @@ def adjust_block_indentation(tokens: List[Token], fn: str) -> None:
continue

if start_token and token.indent is not None:
if not start_token.indent_is_final and token.indent == start_token.orig_indent:
if token_allows_children_to_skip_indents(start_token):
start_token.child_indent = start_token.indent
if (
not start_token.indent_is_final
and token.indent == start_token.orig_indent
and token_allows_children_to_skip_indents(start_token)
):
start_token.child_indent = start_token.indent
start_token.indent_is_final = True

# Detect start token by its having a end token
Expand Down
23 changes: 10 additions & 13 deletions tools/lib/template_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,16 +465,14 @@ def report_problem() -> Optional[str]:
tag = token.tag

if not state.foreign:
if kind == "html_start":
if tag in HTML_VOID_TAGS:
raise TemplateParserError(
f"Tag must be self-closing: {tag} at {fn} line {token.line}, col {token.col}"
)
elif kind == "html_singleton":
if tag not in HTML_VOID_TAGS:
raise TemplateParserError(
f"Tag must not be self-closing: {tag} at {fn} line {token.line}, col {token.col}"
)
if kind == "html_start" and tag in HTML_VOID_TAGS:
raise TemplateParserError(
f"Tag must be self-closing: {tag} at {fn} line {token.line}, col {token.col}"
)
elif kind == "html_singleton" and tag not in HTML_VOID_TAGS:
raise TemplateParserError(
f"Tag must not be self-closing: {tag} at {fn} line {token.line}, col {token.col}"
)

flavor = tag_flavor(token)
if flavor == "start":
Expand Down Expand Up @@ -511,9 +509,8 @@ def has_bad_indentation() -> bool:
if end_line > start_line + 1:
if is_inline_tag:
end_row_text = lines[end_line - 1]
if end_row_text.lstrip().startswith(end_token.s):
if end_col != start_col:
return True
if end_row_text.lstrip().startswith(end_token.s) and end_col != start_col:
return True
else:
if end_col != start_col:
return True
Expand Down
17 changes: 9 additions & 8 deletions tools/renumber-migrations
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,20 @@ if __name__ == "__main__":
migration_number = file[0:4]
counter = file_index.count(migration_number)

if counter > 1 and file[0:4] not in stack:
if (
counter > 1
and file[0:4] not in stack
# When we need to backport migrations to a previous
# release, we sometimes end up with multiple having
# the same ID number (which isn't a problem; the
# migrations graph structure, not the IDs, is what
# matters).
if migration_number not in MIGRATIONS_TO_SKIP:
conflicts += [
file_name
for file_name in files_list
if file_name.startswith(migration_number)
]
stack.append(migration_number)
and migration_number not in MIGRATIONS_TO_SKIP
):
conflicts += [
file_name for file_name in files_list if file_name.startswith(migration_number)
]
stack.append(migration_number)

if len(conflicts) > 0:
resolve_conflicts(conflicts, files_list)
Expand Down
95 changes: 47 additions & 48 deletions zerver/actions/message_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,55 +668,52 @@ def user_info(um: UserMessage) -> Dict[str, Any]:
# newly sent messages anyway) and having magical live-updates
# where possible.
users_to_be_notified = list(map(user_info, ums))
if stream_being_edited is not None:
if stream_being_edited.is_history_public_to_subscribers():
subscriptions = get_active_subscriptions_for_stream_id(
stream_id, include_deactivated_users=False
)
# We exclude long-term idle users, since they by
# definition have no active clients.
subscriptions = subscriptions.exclude(user_profile__long_term_idle=True)
# Remove duplicates by excluding the id of users already
# in users_to_be_notified list. This is the case where a
# user both has a UserMessage row and is a current
# Subscriber
subscriptions = subscriptions.exclude(
user_profile_id__in=[um.user_profile_id for um in ums]
)
if stream_being_edited is not None and stream_being_edited.is_history_public_to_subscribers():
subscriptions = get_active_subscriptions_for_stream_id(
stream_id, include_deactivated_users=False
)
# We exclude long-term idle users, since they by
# definition have no active clients.
subscriptions = subscriptions.exclude(user_profile__long_term_idle=True)
# Remove duplicates by excluding the id of users already
# in users_to_be_notified list. This is the case where a
# user both has a UserMessage row and is a current
# Subscriber
subscriptions = subscriptions.exclude(
user_profile_id__in=[um.user_profile_id for um in ums]
)

if new_stream is not None:
assert delete_event_notify_user_ids is not None
subscriptions = subscriptions.exclude(
user_profile_id__in=delete_event_notify_user_ids
)
if new_stream is not None:
assert delete_event_notify_user_ids is not None
subscriptions = subscriptions.exclude(user_profile_id__in=delete_event_notify_user_ids)

# All users that are subscribed to the stream must be
# notified when a message is edited
subscriber_ids = set(subscriptions.values_list("user_profile_id", flat=True))
# All users that are subscribed to the stream must be
# notified when a message is edited
subscriber_ids = set(subscriptions.values_list("user_profile_id", flat=True))

if new_stream is not None:
# TODO: Guest users don't see the new moved topic
# unless breadcrumb message for new stream is
# enabled. Excluding these users from receiving this
# event helps us avoid a error traceback for our
# clients. We should figure out a way to inform the
# guest users of this new topic if sending a 'message'
# event for these messages is not an option.
#
# Don't send this event to guest subs who are not
# subscribers of the old stream but are subscribed to
# the new stream; clients will be confused.
old_stream_unsubbed_guests = [
sub
for sub in subs_to_new_stream
if sub.user_profile.is_guest and sub.user_profile_id not in subscriber_ids
]
subscriptions = subscriptions.exclude(
user_profile_id__in=[sub.user_profile_id for sub in old_stream_unsubbed_guests]
)
subscriber_ids = set(subscriptions.values_list("user_profile_id", flat=True))
if new_stream is not None:
# TODO: Guest users don't see the new moved topic
# unless breadcrumb message for new stream is
# enabled. Excluding these users from receiving this
# event helps us avoid a error traceback for our
# clients. We should figure out a way to inform the
# guest users of this new topic if sending a 'message'
# event for these messages is not an option.
#
# Don't send this event to guest subs who are not
# subscribers of the old stream but are subscribed to
# the new stream; clients will be confused.
old_stream_unsubbed_guests = [
sub
for sub in subs_to_new_stream
if sub.user_profile.is_guest and sub.user_profile_id not in subscriber_ids
]
subscriptions = subscriptions.exclude(
user_profile_id__in=[sub.user_profile_id for sub in old_stream_unsubbed_guests]
)
subscriber_ids = set(subscriptions.values_list("user_profile_id", flat=True))

users_to_be_notified += list(map(subscriber_info, sorted(subscriber_ids)))
users_to_be_notified += list(map(subscriber_info, sorted(subscriber_ids)))

# UserTopic updates and the content of notifications depend on
# whether we've moved the entire topic, or just part of it. We
Expand Down Expand Up @@ -927,10 +924,12 @@ def check_update_message(

validate_message_edit_payload(message, stream_id, topic_name, propagate_mode, content)

if content is not None:
if (
content is not None
# You cannot edit the content of message sent by someone else.
if message.sender_id != user_profile.id:
raise JsonableError(_("You don't have permission to edit this message"))
and message.sender_id != user_profile.id
):
raise JsonableError(_("You don't have permission to edit this message"))

is_no_topic_msg = message.topic_name() == "(no topic)"

Expand Down
13 changes: 8 additions & 5 deletions zerver/actions/message_send.py
Original file line number Diff line number Diff line change
Expand Up @@ -1479,11 +1479,14 @@ def check_message(
limit_unread_user_ids=limit_unread_user_ids,
)

if stream is not None and message_send_dict.rendering_result.mentions_wildcard:
if not wildcard_mention_allowed(sender, stream):
raise JsonableError(
_("You do not have permission to use wildcard mentions in this stream.")
)
if (
stream is not None
and message_send_dict.rendering_result.mentions_wildcard
and not wildcard_mention_allowed(sender, stream)
):
raise JsonableError(
_("You do not have permission to use wildcard mentions in this stream.")
)
return message_send_dict


Expand Down
17 changes: 8 additions & 9 deletions zerver/actions/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,15 +355,14 @@ def get_service_dicts_for_bots(
}
for service in services
]
elif bot_type == UserProfile.EMBEDDED_BOT:
if bot_profile_id in embedded_bot_configs:
bot_config = embedded_bot_configs[bot_profile_id]
service_dicts = [
{
"config_data": bot_config,
"service_name": services[0].name,
}
]
elif bot_type == UserProfile.EMBEDDED_BOT and bot_profile_id in embedded_bot_configs:
bot_config = embedded_bot_configs[bot_profile_id]
service_dicts = [
{
"config_data": bot_config,
"service_name": services[0].name,
}
]
service_dicts_by_uid[bot_profile_id] = service_dicts
return service_dicts_by_uid

Expand Down
14 changes: 6 additions & 8 deletions zerver/lib/avatar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading

0 comments on commit b0e569f

Please sign in to comment.