From 653b0b0436baca494b5a794270b6637ac7c9827a Mon Sep 17 00:00:00 2001 From: Anders Kaseorg Date: Mon, 13 Jan 2025 15:31:03 -0800 Subject: [PATCH] ruff: Partially reformat Python with Ruff 0.9 (2025 style). These are the changes that are backwards compatible with the 2024 style. Signed-off-by: Anders Kaseorg --- .../commands/update_analytics_counts.py | 3 +-- corporate/lib/stripe.py | 2 +- corporate/tests/test_stripe.py | 4 +-- scripts/lib/zulip_tools.py | 3 +-- scripts/purge-old-deployments | 3 +-- tools/lint | 3 +-- .../generate-user-messages-screenshot | 2 +- zerver/data_import/mattermost.py | 2 +- zerver/data_import/rocketchat.py | 8 +++--- zerver/data_import/slack.py | 2 +- zerver/forms.py | 4 +-- zerver/management/commands/merge_streams.py | 6 ++--- zerver/management/commands/scrub_realm.py | 2 +- .../commands/send_to_email_mirror.py | 3 +-- zerver/tests/test_markdown.py | 26 +++++++------------ zerver/tests/test_message_edit.py | 4 +-- zerver/tests/test_openapi.py | 2 +- zerver/tests/test_signup.py | 3 +-- zerver/tests/test_users.py | 2 +- zerver/views/reactions.py | 5 +--- zerver/webhooks/front/tests.py | 6 ++--- zerver/webhooks/splunk/view.py | 2 +- zilencer/management/commands/populate_db.py | 3 +-- 23 files changed, 38 insertions(+), 62 deletions(-) diff --git a/analytics/management/commands/update_analytics_counts.py b/analytics/management/commands/update_analytics_counts.py index ebae777b4a..541ebf07b5 100644 --- a/analytics/management/commands/update_analytics_counts.py +++ b/analytics/management/commands/update_analytics_counts.py @@ -26,8 +26,7 @@ class Command(ZulipBaseCommand): parser.add_argument( "--time", "-t", - help="Update stat tables from current state to " - "--time. Defaults to the current time.", + help="Update stat tables from current state to --time. Defaults to the current time.", default=timezone_now().isoformat(), ) parser.add_argument("--utc", action="store_true", help="Interpret --time in UTC.") diff --git a/corporate/lib/stripe.py b/corporate/lib/stripe.py index 2e3c16d078..48b5975e9d 100644 --- a/corporate/lib/stripe.py +++ b/corporate/lib/stripe.py @@ -347,7 +347,7 @@ def get_idempotency_key(ledger_entry: LicenseLedger) -> str | None: def cents_to_dollar_string(cents: int) -> str: - return f"{cents / 100.:,.2f}" + return f"{cents / 100.0:,.2f}" # Should only be called if the customer is being charged automatically diff --git a/corporate/tests/test_stripe.py b/corporate/tests/test_stripe.py index cfd4b52bc1..0bd93ba63e 100644 --- a/corporate/tests/test_stripe.py +++ b/corporate/tests/test_stripe.py @@ -1001,7 +1001,7 @@ class StripeTest(StripeTestCase): "Zulip Cloud Plus", str(self.seat_count), "Number of licenses", - f"{ self.seat_count }", + f"{self.seat_count}", "Your plan will automatically renew on", "January 2, 2013", f"${120 * self.seat_count}.00", @@ -1271,7 +1271,7 @@ class StripeTest(StripeTestCase): "Zulip Cloud Standard", str(self.seat_count), "Number of licenses", - f"{ self.seat_count }", + f"{self.seat_count}", "Your plan will automatically renew on", "January 2, 2013", f"${80 * self.seat_count}.00", diff --git a/scripts/lib/zulip_tools.py b/scripts/lib/zulip_tools.py index e19ff9f236..507c3e7471 100755 --- a/scripts/lib/zulip_tools.py +++ b/scripts/lib/zulip_tools.py @@ -94,8 +94,7 @@ def parse_cache_script_args(description: str) -> argparse.Namespace: "--no-print-headings", dest="no_headings", action="store_true", - help="If specified then script will not print headings for " - "what will be deleted/kept back.", + help="If specified then script will not print headings for what will be deleted/kept back.", ) args = parser.parse_args() diff --git a/scripts/purge-old-deployments b/scripts/purge-old-deployments index a4c5fb4bd4..cefd8bf775 100755 --- a/scripts/purge-old-deployments +++ b/scripts/purge-old-deployments @@ -46,8 +46,7 @@ def parse_args() -> argparse.Namespace: "--no-print-headings", dest="no_headings", action="store_true", - help="If specified then script will not print headings for " - "what will be deleted/kept back.", + help="If specified then script will not print headings for what will be deleted/kept back.", ) args = parser.parse_args() diff --git a/tools/lint b/tools/lint index 5d1ec02b2b..d14669c5a5 100755 --- a/tools/lint +++ b/tools/lint @@ -109,8 +109,7 @@ def run() -> None: "openapi", ["node", "tools/check-openapi"], ["yaml"], - description="Validates our OpenAPI/Swagger API documentation " - "(zerver/openapi/zulip.yaml) ", + description="Validates our OpenAPI/Swagger API documentation (zerver/openapi/zulip.yaml) ", fix_arg="--fix", ) linter_config.external_linter( diff --git a/tools/screenshots/generate-user-messages-screenshot b/tools/screenshots/generate-user-messages-screenshot index 3f0a7e6291..1024bf23dc 100755 --- a/tools/screenshots/generate-user-messages-screenshot +++ b/tools/screenshots/generate-user-messages-screenshot @@ -86,7 +86,7 @@ class MessageThread(BaseModel): def create_user(full_name: str, avatar_filename: str | None) -> None: - email = f'{full_name.replace(" ", "")}@zulip.com' + email = f"{full_name.replace(' ', '')}@zulip.com" try: user = UserProfile.objects.get(realm=realm, full_name=full_name) except UserProfile.DoesNotExist: diff --git a/zerver/data_import/mattermost.py b/zerver/data_import/mattermost.py index a1dc08225a..530e966f1c 100644 --- a/zerver/data_import/mattermost.py +++ b/zerver/data_import/mattermost.py @@ -339,7 +339,7 @@ def process_message_attachments( attachment_full_path = os.path.join(mattermost_data_dir, "data", attachment_path) file_name = attachment_path.split("/")[-1] - file_ext = f'.{file_name.split(".")[-1]}' + file_ext = f".{file_name.split('.')[-1]}" if file_ext.lower() in IMAGE_EXTENSIONS: has_image = True diff --git a/zerver/data_import/rocketchat.py b/zerver/data_import/rocketchat.py index 867a900c2a..275a08d201 100644 --- a/zerver/data_import/rocketchat.py +++ b/zerver/data_import/rocketchat.py @@ -148,7 +148,7 @@ def truncate_name(name: str, name_id: int, max_length: int = 60) -> str: def get_stream_name(rc_channel: dict[str, Any]) -> str: if rc_channel.get("teamMain"): - stream_name = f'[TEAM] {rc_channel["name"]}' + stream_name = f"[TEAM] {rc_channel['name']}" else: stream_name = rc_channel["name"] @@ -286,7 +286,7 @@ def build_custom_emoji( # Build custom emoji for rc_emoji in custom_emoji_data["emoji"]: # Subject to change with changes in database - emoji_file_id = f'{rc_emoji["name"]}.{rc_emoji["extension"]}' + emoji_file_id = f"{rc_emoji['name']}.{rc_emoji['extension']}" emoji_file_info = emoji_file_data[emoji_file_id] @@ -391,7 +391,7 @@ def process_message_attachment( upload_file_data = upload_id_to_upload_data_map[upload["_id"]] file_name = upload["name"] - file_ext = f'.{upload["type"].split("/")[-1]}' + file_ext = f".{upload['type'].split('/')[-1]}" has_image = False if file_ext.lower() in IMAGE_EXTENSIONS: @@ -423,7 +423,7 @@ def process_message_attachment( upload_file.write(b"".join(upload_file_data["chunk"])) attachment_content = ( - f'{upload_file_data.get("description", "")}\n\n[{file_name}](/user_uploads/{s3_path})' + f"{upload_file_data.get('description', '')}\n\n[{file_name}](/user_uploads/{s3_path})" ) fileinfo = { diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.py index 4f8e96321f..f42438328f 100644 --- a/zerver/data_import/slack.py +++ b/zerver/data_import/slack.py @@ -455,7 +455,7 @@ def get_user_email(user: ZerverFieldsT, domain_name: str) -> str: if "email" in user["profile"]: return user["profile"]["email"] if user["is_mirror_dummy"]: - return Address(username=user["name"], domain=f'{user["team_domain"]}.slack.com').addr_spec + return Address(username=user["name"], domain=f"{user['team_domain']}.slack.com").addr_spec if "bot_id" in user["profile"]: return SlackBotEmail.get_email(user["profile"], domain_name) if get_user_full_name(user).lower() == "slackbot": diff --git a/zerver/forms.py b/zerver/forms.py index fe6c3875d1..f446271d77 100644 --- a/zerver/forms.py +++ b/zerver/forms.py @@ -273,9 +273,7 @@ class HomepageForm(forms.Form): if not from_multiuse_invite and realm.invite_required: raise ValidationError( _( - "Please request an invite for {email} " - "from the organization " - "administrator." + "Please request an invite for {email} from the organization administrator." ).format(email=email) ) diff --git a/zerver/management/commands/merge_streams.py b/zerver/management/commands/merge_streams.py index b85a7c9e98..578c192c46 100644 --- a/zerver/management/commands/merge_streams.py +++ b/zerver/management/commands/merge_streams.py @@ -26,6 +26,6 @@ class Command(ZulipBaseCommand): stream_to_keep = get_stream(options["stream_to_keep"], realm) stream_to_destroy = get_stream(options["stream_to_destroy"], realm) stats = merge_streams(realm, stream_to_keep, stream_to_destroy) - print(f"Added { stats[0] } subscriptions") - print(f"Moved { stats[1] } messages") - print(f"Deactivated { stats[2] } subscriptions") + print(f"Added {stats[0]} subscriptions") + print(f"Moved {stats[1]} messages") + print(f"Deactivated {stats[2]} subscriptions") diff --git a/zerver/management/commands/scrub_realm.py b/zerver/management/commands/scrub_realm.py index 42642fcda1..8a3985460f 100644 --- a/zerver/management/commands/scrub_realm.py +++ b/zerver/management/commands/scrub_realm.py @@ -21,7 +21,7 @@ class Command(ZulipBaseCommand): assert realm is not None # Should be ensured by parser if not realm.deactivated: raise CommandError( - f'Realm {options["realm_id"]} is active. Please deactivate the realm the first.' + f"Realm {options['realm_id']} is active. Please deactivate the realm the first." ) print("Scrubbing", options["realm_id"]) do_scrub_realm(realm, acting_user=None) diff --git a/zerver/management/commands/send_to_email_mirror.py b/zerver/management/commands/send_to_email_mirror.py index ecffac7c98..b7a4804747 100644 --- a/zerver/management/commands/send_to_email_mirror.py +++ b/zerver/management/commands/send_to_email_mirror.py @@ -53,8 +53,7 @@ Example: parser.add_argument( "-s", "--stream", - help="The name of the stream to which you'd like to send " - "the message. Default: Denmark", + help="The name of the stream to which you'd like to send the message. Default: Denmark", ) parser.add_argument( "--sender-id", diff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.py index 562ed7670c..dcbd7683ce 100644 --- a/zerver/tests/test_markdown.py +++ b/zerver/tests/test_markdown.py @@ -753,7 +753,7 @@ class MarkdownEmbedsTest(ZulipTestCase): @override_settings(EXTERNAL_URI_SCHEME="https://") def test_static_image_preview_skip_camo(self) -> None: - content = f"{ settings.STATIC_URL }/thing.jpeg" + content = f"{settings.STATIC_URL}/thing.jpeg" thumbnail_img = f"""
""" converted = markdown_convert_wrapper(content) @@ -761,15 +761,15 @@ class MarkdownEmbedsTest(ZulipTestCase): @override_settings(EXTERNAL_URI_SCHEME="https://") def test_realm_image_preview_skip_camo(self) -> None: - content = f"https://zulip.{ settings.EXTERNAL_HOST }/thing.jpeg" + content = f"https://zulip.{settings.EXTERNAL_HOST}/thing.jpeg" converted = markdown_convert_wrapper(content) self.assertNotIn(converted, get_camo_url(content)) @override_settings(EXTERNAL_URI_SCHEME="https://") def test_cross_realm_image_preview_use_camo(self) -> None: - content = f"https://otherrealm.{ settings.EXTERNAL_HOST }/thing.jpeg" + content = f"https://otherrealm.{settings.EXTERNAL_HOST}/thing.jpeg" - thumbnail_img = f"""
""" + thumbnail_img = f"""
""" converted = markdown_convert_wrapper(content) self.assertIn(converted, thumbnail_img) @@ -870,7 +870,7 @@ class MarkdownEmbedsTest(ZulipTestCase): self.assertEqual(converted.rendered_content, expected) urls.append("https://www.google.com/images/srpr/logo4w.png") - content = f"{urls[0]}\n\n" f">{urls[1]}\n\n" f"* {urls[2]}\n" f"* {urls[3]}" + content = f"{urls[0]}\n\n>{urls[1]}\n\n* {urls[2]}\n* {urls[3]}" expected = ( f'
' f'
\n

{urls[1]}

\n
\n' @@ -2284,9 +2284,7 @@ class MarkdownMentionTest(ZulipTestCase): rendering_result = render_message_markdown(msg, content) self.assertEqual( rendering_result.rendered_content, - '

' - "King Hamlet

", + f'

King Hamlet

', ) self.assertEqual(rendering_result.mentions_user_ids, set()) @@ -2305,9 +2303,7 @@ class MarkdownMentionTest(ZulipTestCase): rendering_result = render_message_markdown(msg, content) self.assertEqual( rendering_result.rendered_content, - '

' - "King Hamlet

", + f'

King Hamlet

', ) self.assertEqual(rendering_result.mentions_user_ids, set()) @@ -2326,9 +2322,7 @@ class MarkdownMentionTest(ZulipTestCase): rendering_result = render_message_markdown(msg, content) self.assertEqual( rendering_result.rendered_content, - '

' - "King Hamlet

", + f'

King Hamlet

', ) self.assertEqual(rendering_result.mentions_user_ids, set()) @@ -2685,9 +2679,7 @@ class MarkdownMentionTest(ZulipTestCase): rendering_result = render_message_markdown(msg, content) self.assertEqual( rendering_result.rendered_content, - '

' - "@Atomic #123

", + f'

@Atomic #123

', ) self.assertEqual(rendering_result.mentions_user_ids, {test_user.id}) content = "@_**Atomic #123**" diff --git a/zerver/tests/test_message_edit.py b/zerver/tests/test_message_edit.py index e24a5c09cb..b8ae8fa4f7 100644 --- a/zerver/tests/test_message_edit.py +++ b/zerver/tests/test_message_edit.py @@ -555,9 +555,7 @@ class EditMessageTest(ZulipTestCase): content="content before edit, line 1\n\ncontent before edit, line 3", ) new_content_2 = ( - "content before edit, line 1\n" - "content after edit, line 2\n" - "content before edit, line 3" + "content before edit, line 1\ncontent after edit, line 2\ncontent before edit, line 3" ) result_2 = self.client_patch( f"/json/messages/{msg_id_2}", diff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.py index 3bac4a9766..41a1fe5b6d 100644 --- a/zerver/tests/test_openapi.py +++ b/zerver/tests/test_openapi.py @@ -417,7 +417,7 @@ do not match the types declared in the implementation of {function.__name__}.\n" self.assertIn( function_schema_type, (int, bool), - f'\nUnexpected content type {actual_param_schema["contentMediaType"]} on function parameter {actual_param.param_name}, which does not match the OpenAPI definition.', + f"\nUnexpected content type {actual_param_schema['contentMediaType']} on function parameter {actual_param.param_name}, which does not match the OpenAPI definition.", ) function_params.add( (actual_param.request_var_name, schema_type(actual_param_schema, defs_mapping)) diff --git a/zerver/tests/test_signup.py b/zerver/tests/test_signup.py index 5c320fa1d2..39cb190bd8 100644 --- a/zerver/tests/test_signup.py +++ b/zerver/tests/test_signup.py @@ -438,8 +438,7 @@ class AddNewUserHistoryTest(ZulipTestCase): with patch("zerver.models.Recipient.label", return_value="recip"): self.assertEqual( repr(message), - ">", + f">", ) user_message = most_recent_usermessage(user_profile) diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py index 9c3accc7d4..e5ba995e09 100644 --- a/zerver/tests/test_users.py +++ b/zerver/tests/test_users.py @@ -1874,7 +1874,7 @@ class ActivateTest(ZulipTestCase): self.login("iago") # Organization administrator cannot deactivate organization owner. - result = self.client_delete(f'/json/users/{self.example_user("desdemona").id}') + result = self.client_delete(f"/json/users/{self.example_user('desdemona').id}") self.assert_json_error(result, "Must be an organization owner") iago = self.example_user("iago") diff --git a/zerver/views/reactions.py b/zerver/views/reactions.py index 55ad9c91bb..a9cfb1bee3 100644 --- a/zerver/views/reactions.py +++ b/zerver/views/reactions.py @@ -45,10 +45,7 @@ def remove_reaction( if emoji_code is None: if emoji_name is None: raise JsonableError( - _( - "At least one of the following arguments " - "must be present: emoji_name, emoji_code" - ) + _("At least one of the following arguments must be present: emoji_name, emoji_code") ) # A correct full Zulip client implementation should always # pass an emoji_code, because of the corner cases discussed in diff --git a/zerver/webhooks/front/tests.py b/zerver/webhooks/front/tests.py index c3676847b1..30da481b44 100644 --- a/zerver/webhooks/front/tests.py +++ b/zerver/webhooks/front/tests.py @@ -96,8 +96,7 @@ class FrontHookTests(WebhookTestCase): def test_mention_all(self) -> None: expected_topic_name = "cnv_keo696" expected_message = ( - "**Leela Turanga** left a comment:\n" - "```quote\n@all Could someone else take this?\n```" + "**Leela Turanga** left a comment:\n```quote\n@all Could someone else take this?\n```" ) self.check_webhook( @@ -177,8 +176,7 @@ class FrontHookTests(WebhookTestCase): def test_mention(self) -> None: expected_topic_name = "cnv_keocka" expected_message = ( - "**Leela Turanga** left a comment:\n" - "```quote\n@bender Could you take it from here?\n```" + "**Leela Turanga** left a comment:\n```quote\n@bender Could you take it from here?\n```" ) self.check_webhook( diff --git a/zerver/webhooks/splunk/view.py b/zerver/webhooks/splunk/view.py index b83ed7fac5..8023c2c29f 100644 --- a/zerver/webhooks/splunk/view.py +++ b/zerver/webhooks/splunk/view.py @@ -35,7 +35,7 @@ def api_splunk_webhook( # for the default topic, use search name but truncate if too long if len(search_name) >= MAX_TOPIC_NAME_LENGTH: - topic_name = f"{search_name[:(MAX_TOPIC_NAME_LENGTH - 3)]}..." + topic_name = f"{search_name[: (MAX_TOPIC_NAME_LENGTH - 3)]}..." else: topic_name = search_name diff --git a/zilencer/management/commands/populate_db.py b/zilencer/management/commands/populate_db.py index c8f27f33b0..0c80bb4ed9 100644 --- a/zilencer/management/commands/populate_db.py +++ b/zilencer/management/commands/populate_db.py @@ -301,8 +301,7 @@ class Command(ZulipBaseCommand): parser.add_argument( "--test-suite", action="store_true", - help="Configures populate_db to create a deterministic " - "data set for the backend tests.", + help="Configures populate_db to create a deterministic data set for the backend tests.", ) @override