Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

[pyupgrade] groups/, federation/, events/, and crypto/ #9749

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/9749.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Run `pyupgrade --py36-plus` over the codebase.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This'll be the newsfile that i will use across all pyupgrade PRs, any adjustments?

1 change: 0 additions & 1 deletion synapse/crypto/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
7 changes: 3 additions & 4 deletions synapse/crypto/event_signing.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
Expand Down Expand Up @@ -53,21 +52,21 @@ def check_event_content_hash(
# nb it might be a frozendict or a dict
if not isinstance(hashes, collections.abc.Mapping):
raise SynapseError(
400, "Malformed 'hashes': %s" % (type(hashes),), Codes.UNAUTHORIZED
400, "Malformed 'hashes': {}".format(type(hashes)), Codes.UNAUTHORIZED
)

if name not in hashes:
raise SynapseError(
400,
"Algorithm %s not in hashes %s" % (name, list(hashes)),
"Algorithm {} not in hashes {}".format(name, list(hashes)),
Codes.UNAUTHORIZED,
)
message_hash_base64 = hashes[name]
try:
message_hash_bytes = decode_base64(message_hash_base64)
except Exception:
raise SynapseError(
400, "Invalid base64: %s" % (message_hash_base64,), Codes.UNAUTHORIZED
400, f"Invalid base64: {message_hash_base64}", Codes.UNAUTHORIZED
)
return message_hash_bytes == expected_hash

Expand Down
11 changes: 5 additions & 6 deletions synapse/crypto/keyring.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2017, 2018 New Vector Ltd
#
Expand Down Expand Up @@ -209,7 +208,7 @@ def process(verify_request: VerifyJsonRequest) -> defer.Deferred:
return defer.fail(
SynapseError(
400,
"Not signed by %s" % (verify_request.server_name,),
f"Not signed by {verify_request.server_name}",
Codes.UNAUTHORIZED,
)
)
Expand Down Expand Up @@ -319,7 +318,7 @@ async def wait_for_previous_lookups(self, server_names: Iterable[str]) -> None:
loop_count,
)
with PreserveLoggingContext():
await defer.DeferredList((w[1] for w in wait_on))
await defer.DeferredList(w[1] for w in wait_on)

loop_count += 1

Expand Down Expand Up @@ -369,7 +368,7 @@ async def do_iterations():
verify_request.key_ready.errback,
SynapseError(
401,
"Failed to find any key to satisfy %s" % (rq_str,),
f"Failed to find any key to satisfy {rq_str}",
Codes.UNAUTHORIZED,
),
)
Expand Down Expand Up @@ -688,7 +687,7 @@ async def get_server_verify_key_v2_indirect(
# these both have str() representations which we can't really improve upon
raise KeyLookupError(str(e))
except HttpResponseException as e:
raise KeyLookupError("Remote server returned an error: %s" % (e,))
raise KeyLookupError(f"Remote server returned an error: {e}")

keys = {} # type: Dict[str, Dict[str, FetchKeyResult]]
added_keys = [] # type: List[Tuple[str, str, FetchKeyResult]]
Expand Down Expand Up @@ -856,7 +855,7 @@ async def get_server_verify_key_v2_direct(
# upon
raise KeyLookupError(str(e))
except HttpResponseException as e:
raise KeyLookupError("Remote server returned an error: %s" % (e,))
raise KeyLookupError(f"Remote server returned an error: {e}")

assert isinstance(response, dict)
if response["server_name"] != server_name:
Expand Down
13 changes: 6 additions & 7 deletions synapse/events/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2019 New Vector Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
Expand Down Expand Up @@ -63,7 +62,7 @@ def __get__(self, instance, owner=None):
# because that would omit any *earlier* exceptions).
#
raise AttributeError(
"'%s' has no '%s' property" % (type(instance), self.key)
"'{}' has no '{}' property".format(type(instance), self.key)
) from e1.__context__

def __set__(self, instance, v):
Expand All @@ -74,7 +73,7 @@ def __delete__(self, instance):
del instance._dict[self.key]
except KeyError as e1:
raise AttributeError(
"'%s' has no '%s' property" % (type(instance), self.key)
"'{}' has no '{}' property".format(type(instance), self.key)
) from e1.__context__


Expand Down Expand Up @@ -284,7 +283,7 @@ def get_pdu_json(self, time_now=None) -> JsonDict:
return pdu_json

def __set__(self, instance, value):
raise AttributeError("Unrecognized attribute %s" % (instance,))
raise AttributeError(f"Unrecognized attribute {instance}")

def __getitem__(self, field):
return self._dict[field]
Expand Down Expand Up @@ -372,7 +371,7 @@ def __str__(self):
return self.__repr__()

def __repr__(self):
return "<FrozenEvent event_id=%r, type=%r, state_key=%r>" % (
return "<FrozenEvent event_id={!r}, type={!r}, state_key={!r}>".format(
self.get("event_id", None),
self.get("type", None),
self.get("state_key", None),
Expand Down Expand Up @@ -455,7 +454,7 @@ def __str__(self):
return self.__repr__()

def __repr__(self):
return "<%s event_id=%r, type=%r, state_key=%r>" % (
return "<{} event_id={!r}, type={!r}, state_key={!r}>".format(
self.__class__.__name__,
self.event_id,
self.get("type", None),
Expand Down Expand Up @@ -501,7 +500,7 @@ def _event_type_from_format_version(format_version: int) -> Type[EventBase]:
elif format_version == EventFormatVersions.V3:
return FrozenEventV3
else:
raise Exception("No event format %r" % (format_version,))
raise Exception(f"No event format {format_version!r}")


def make_event_from_dict(
Expand Down
3 changes: 1 addition & 2 deletions synapse/events/builder.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -245,7 +244,7 @@ def create_local_event_from_event_dict(

format_version = room_version.event_format
if format_version not in KNOWN_EVENT_FORMAT_VERSIONS:
raise Exception("No event format defined for version %r" % (format_version,))
raise Exception(f"No event format defined for version {format_version!r}")

if internal_metadata_dict is None:
internal_metadata_dict = {}
Expand Down
1 change: 0 additions & 1 deletion synapse/events/snapshot.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
1 change: 0 additions & 1 deletion synapse/events/spamcheck.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2017 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
Expand Down
1 change: 0 additions & 1 deletion synapse/events/third_party_rules.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
9 changes: 3 additions & 6 deletions synapse/events/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -453,7 +452,7 @@ def copy_power_levels_contents(
TypeError if the input does not look like a valid power levels event content
"""
if not isinstance(old_power_levels, collections.abc.Mapping):
raise TypeError("Not a valid power-levels content: %r" % (old_power_levels,))
raise TypeError(f"Not a valid power-levels content: {old_power_levels!r}")

power_levels = {}
for k, v in old_power_levels.items():
Expand All @@ -467,13 +466,11 @@ def copy_power_levels_contents(
for k1, v1 in v.items():
# we should only have one level of nesting
if not isinstance(v1, int):
raise TypeError(
"Invalid power_levels value for %s.%s: %r" % (k, k1, v1)
)
raise TypeError(f"Invalid power_levels value for {k}.{k1}: {v1!r}")
h[k1] = v1
continue

raise TypeError("Invalid power_levels value for %s: %r" % (k, v))
raise TypeError(f"Invalid power_levels value for {k}: {v!r}")

return power_levels

Expand Down
13 changes: 6 additions & 7 deletions synapse/events/validator.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -51,14 +50,14 @@ def validate_new(self, event: EventBase, config: HomeServerConfig):

for k in required:
if not hasattr(event, k):
raise SynapseError(400, "Event does not have key %s" % (k,))
raise SynapseError(400, f"Event does not have key {k}")

# Check that the following keys have string values
event_strings = ["origin"]

for s in event_strings:
if not isinstance(getattr(event, s), str):
raise SynapseError(400, "'%s' not a string type" % (s,))
raise SynapseError(400, f"'{s}' not a string type")

# Depending on the room version, ensure the data is spec compliant JSON.
if event.room_version.strict_canonicaljson:
Expand Down Expand Up @@ -141,7 +140,7 @@ def validate_builder(self, event: Union[EventBase, EventBuilder]):

for s in strings:
if not isinstance(getattr(event, s), str):
raise SynapseError(400, "Not '%s' a string type" % (s,))
raise SynapseError(400, f"Not '{s}' a string type")

RoomID.from_string(event.room_id)
UserID.from_string(event.sender)
Expand Down Expand Up @@ -179,10 +178,10 @@ def validate_builder(self, event: Union[EventBase, EventBuilder]):
def _ensure_strings(self, d, keys):
for s in keys:
if s not in d:
raise SynapseError(400, "'%s' not in content" % (s,))
raise SynapseError(400, f"'{s}' not in content")
if not isinstance(d[s], str):
raise SynapseError(400, "'%s' not a string type" % (s,))
raise SynapseError(400, f"'{s}' not a string type")

def _ensure_state_event(self, event):
if not event.is_state():
raise SynapseError(400, "'%s' must be state events" % (event.type,))
raise SynapseError(400, f"'{event.type}' must be state events")
1 change: 0 additions & 1 deletion synapse/federation/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
5 changes: 2 additions & 3 deletions synapse/federation/federation_base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
# Copyright 2020 The Matrix.org Foundation C.I.C.
#
Expand Down Expand Up @@ -209,7 +208,7 @@ def _check_sigs_on_pdus(
)

def sender_err(e, pdu_to_check):
errmsg = "event id %s: unable to verify signature for sender %s: %s" % (
errmsg = "event id {}: unable to verify signature for sender {}: {}".format(
pdu_to_check.pdu.event_id,
pdu_to_check.sender_domain,
e.getErrorMessage(),
Expand Down Expand Up @@ -298,7 +297,7 @@ def event_from_pdu_json(

depth = pdu_json["depth"]
if not isinstance(depth, int):
raise SynapseError(400, "Depth %r not an intger" % (depth,), Codes.BAD_JSON)
raise SynapseError(400, f"Depth {depth!r} not an intger", Codes.BAD_JSON)

if depth < 0:
raise SynapseError(400, "Depth too small", Codes.BAD_JSON)
Expand Down
3 changes: 1 addition & 2 deletions synapse/federation/federation_client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -530,7 +529,7 @@ async def _try_destination_list(
"Failed to %s via %s", description, destination, exc_info=True
)

raise SynapseError(502, "Failed to %s via any server" % (description,))
raise SynapseError(502, f"Failed to {description} via any server")

async def make_membership_event(
self,
Expand Down
9 changes: 4 additions & 5 deletions synapse/federation/federation_server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
# Copyright 2019 Matrix.org Federation C.I.C
Expand Down Expand Up @@ -636,7 +635,7 @@ async def on_claim_client_keys(
"Claimed one-time-keys: %s",
",".join(
(
"%s for %s:%s" % (key_id, user_id, device_id)
f"{key_id} for {user_id}:{device_id}"
for user_id, user_keys in json_result.items()
for device_id, device_keys in user_keys.items()
for key_id, _ in device_keys.items()
Expand Down Expand Up @@ -889,7 +888,7 @@ def register_edu_handler(
the EDU contents.
"""
if edu_type in self.edu_handlers:
raise KeyError("Already have an EDU handler for %s" % (edu_type,))
raise KeyError(f"Already have an EDU handler for {edu_type}")

logger.info("Registering federation EDU handler for %r", edu_type)

Expand All @@ -909,7 +908,7 @@ def register_query_handler(
on and the result used as the response to the query request.
"""
if query_type in self.query_handlers:
raise KeyError("Already have a Query handler for %s" % (query_type,))
raise KeyError(f"Already have a Query handler for {query_type}")

logger.info("Registering federation query handler for %r", query_type)

Expand Down Expand Up @@ -983,4 +982,4 @@ async def on_query(self, query_type: str, args: dict) -> JsonDict:
# Uh oh, no handler! Let's raise an exception so the request returns an
# error.
logger.warning("No handler registered for query type %s", query_type)
raise NotFoundError("No handler for Query type '%s'" % (query_type,))
raise NotFoundError(f"No handler for Query type '{query_type}'")
1 change: 0 additions & 1 deletion synapse/federation/persistence.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
3 changes: 1 addition & 2 deletions synapse/federation/send_queue.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down Expand Up @@ -110,7 +109,7 @@ def __init__(self, hs: "HomeServer"):
# changes. ARGH.
def register(name: str, queue: Sized) -> None:
LaterGauge(
"synapse_federation_send_queue_%s_size" % (queue_name,),
f"synapse_federation_send_queue_{queue_name}_size",
"",
[],
lambda: len(queue),
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/sender/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2019 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/sender/per_destination_queue.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2019 New Vector Ltd
#
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/sender/transaction_manager.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2019 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/transport/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/transport/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
#
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/transport/server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018 New Vector Ltd
# Copyright 2019 The Matrix.org Foundation C.I.C.
Expand Down
1 change: 0 additions & 1 deletion synapse/federation/units.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
1 change: 0 additions & 1 deletion synapse/groups/attestations.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2017 Vector Creations Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
Expand Down
Loading