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

Update black, and run auto formatting over the codebase #9381

Merged
merged 7 commits into from
Feb 16, 2021
Merged
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/9381.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Update the version of black used to 20.8b1.
8 changes: 4 additions & 4 deletions contrib/cmdclient/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def _domain(self):
return self.config["user"].split(":")[1]

def do_config(self, line):
""" Show the config for this client: "config"
"""Show the config for this client: "config"
Edit a key value mapping: "config key value" e.g. "config token 1234"
Config variables:
user: The username to auth with.
Expand Down Expand Up @@ -360,7 +360,7 @@ def do_joinalias(self, line):
print(e)

def do_topic(self, line):
""""topic [set|get] <roomid> [<newtopic>]"
""" "topic [set|get] <roomid> [<newtopic>]"
Set the topic for a room: topic set <roomid> <newtopic>
Get the topic for a room: topic get <roomid>
"""
Expand Down Expand Up @@ -690,7 +690,7 @@ def do_online(self, line):
self._do_presence_state(2, line)

def _parse(self, line, keys, force_keys=False):
""" Parses the given line.
"""Parses the given line.

Args:
line : The line to parse
Expand Down Expand Up @@ -721,7 +721,7 @@ def _run_and_pprint(
query_params={"access_token": None},
alt_text=None,
):
""" Runs an HTTP request and pretty prints the output.
"""Runs an HTTP request and pretty prints the output.

Args:
method: HTTP method
Expand Down
21 changes: 8 additions & 13 deletions contrib/cmdclient/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@


class HttpClient:
""" Interface for talking json over http
"""
"""Interface for talking json over http"""

def put_json(self, url, data):
""" Sends the specifed json data using PUT
"""Sends the specifed json data using PUT

Args:
url (str): The URL to PUT data to.
Expand All @@ -41,7 +40,7 @@ def put_json(self, url, data):
pass

def get_json(self, url, args=None):
""" Gets some json from the given host homeserver and path
"""Gets some json from the given host homeserver and path

Args:
url (str): The URL to GET data from.
Expand All @@ -58,7 +57,7 @@ def get_json(self, url, args=None):


class TwistedHttpClient(HttpClient):
""" Wrapper around the twisted HTTP client api.
"""Wrapper around the twisted HTTP client api.

Attributes:
agent (twisted.web.client.Agent): The twisted Agent used to send the
Expand Down Expand Up @@ -87,8 +86,7 @@ def get_json(self, url, args=None):
defer.returnValue(json.loads(body))

def _create_put_request(self, url, json_data, headers_dict={}):
""" Wrapper of _create_request to issue a PUT request
"""
"""Wrapper of _create_request to issue a PUT request"""

if "Content-Type" not in headers_dict:
raise defer.error(RuntimeError("Must include Content-Type header for PUTs"))
Expand All @@ -98,8 +96,7 @@ def _create_put_request(self, url, json_data, headers_dict={}):
)

def _create_get_request(self, url, headers_dict={}):
""" Wrapper of _create_request to issue a GET request
"""
"""Wrapper of _create_request to issue a GET request"""
return self._create_request("GET", url, headers_dict=headers_dict)

@defer.inlineCallbacks
Expand Down Expand Up @@ -127,8 +124,7 @@ def do_request(

@defer.inlineCallbacks
def _create_request(self, method, url, producer=None, headers_dict={}):
""" Creates and sends a request to the given url
"""
"""Creates and sends a request to the given url"""
headers_dict["User-Agent"] = ["Synapse Cmd Client"]

retries_left = 5
Expand Down Expand Up @@ -185,8 +181,7 @@ def stopProducing(self):


class _JsonProducer:
""" Used by the twisted http client to create the HTTP body from json
"""
"""Used by the twisted http client to create the HTTP body from json"""

def __init__(self, jsn):
self.data = jsn
Expand Down
3 changes: 1 addition & 2 deletions contrib/experiments/cursesio.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def print_log(self, text):
self.redraw()

def redraw(self):
""" method for redisplaying lines
based on internal list of lines """
"""method for redisplaying lines based on internal list of lines"""

self.stdscr.clear()
self.paintStatus(self.statusText)
Expand Down
36 changes: 13 additions & 23 deletions contrib/experiments/test_messaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def excpetion_errback(failure):


class InputOutput:
""" This is responsible for basic I/O so that a user can interact with
"""This is responsible for basic I/O so that a user can interact with
the example app.
"""

Expand All @@ -68,8 +68,7 @@ def set_home_server(self, server):
self.server = server

def on_line(self, line):
""" This is where we process commands.
"""
"""This is where we process commands."""

try:
m = re.match(r"^join (\S+)$", line)
Expand Down Expand Up @@ -133,7 +132,7 @@ def emit(self, record):


class Room:
""" Used to store (in memory) the current membership state of a room, and
"""Used to store (in memory) the current membership state of a room, and
which home servers we should send PDUs associated with the room to.
"""

Expand All @@ -148,8 +147,7 @@ def __init__(self, room_name):
self.have_got_metadata = False

def add_participant(self, participant):
""" Someone has joined the room
"""
"""Someone has joined the room"""
self.participants.add(participant)
self.invited.discard(participant)

Expand All @@ -160,14 +158,13 @@ def add_participant(self, participant):
self.oldest_server = server

def add_invited(self, invitee):
""" Someone has been invited to the room
"""
"""Someone has been invited to the room"""
self.invited.add(invitee)
self.servers.add(origin_from_ucid(invitee))


class HomeServer(ReplicationHandler):
""" A very basic home server implentation that allows people to join a
"""A very basic home server implentation that allows people to join a
room and then invite other people.
"""

Expand All @@ -181,8 +178,7 @@ def __init__(self, server_name, replication_layer, output):
self.output = output

def on_receive_pdu(self, pdu):
""" We just received a PDU
"""
"""We just received a PDU"""
pdu_type = pdu.pdu_type

if pdu_type == "sy.room.message":
Expand All @@ -199,23 +195,20 @@ def on_receive_pdu(self, pdu):
)

def _on_message(self, pdu):
""" We received a message
"""
"""We received a message"""
self.output.print_line(
"#%s %s %s" % (pdu.context, pdu.content["sender"], pdu.content["body"])
)

def _on_join(self, context, joinee):
""" Someone has joined a room, either a remote user or a local user
"""
"""Someone has joined a room, either a remote user or a local user"""
room = self._get_or_create_room(context)
room.add_participant(joinee)

self.output.print_line("#%s %s %s" % (context, joinee, "*** JOINED"))

def _on_invite(self, origin, context, invitee):
""" Someone has been invited
"""
"""Someone has been invited"""
room = self._get_or_create_room(context)
room.add_invited(invitee)

Expand All @@ -228,8 +221,7 @@ def _on_invite(self, origin, context, invitee):

@defer.inlineCallbacks
def send_message(self, room_name, sender, body):
""" Send a message to a room!
"""
"""Send a message to a room!"""
destinations = yield self.get_servers_for_context(room_name)

try:
Expand All @@ -247,8 +239,7 @@ def send_message(self, room_name, sender, body):

@defer.inlineCallbacks
def join_room(self, room_name, sender, joinee):
""" Join a room!
"""
"""Join a room!"""
self._on_join(room_name, joinee)

destinations = yield self.get_servers_for_context(room_name)
Expand All @@ -269,8 +260,7 @@ def join_room(self, room_name, sender, joinee):

@defer.inlineCallbacks
def invite_to_room(self, room_name, sender, invitee):
""" Invite someone to a room!
"""
"""Invite someone to a room!"""
self._on_invite(self.server_name, room_name, invitee)

destinations = yield self.get_servers_for_context(room_name)
Expand Down
15 changes: 6 additions & 9 deletions contrib/jitsimeetbridge/jitsimeetbridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,12 @@ def advertiseSsrcs(self):
time.sleep(7)
print("SSRC spammer started")
while self.running:
ssrcMsg = (
"<presence to='%(tojid)s' xmlns='jabber:client'><x xmlns='http://jabber.org/protocol/muc'/><c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://jitsi.org/jitsimeet' ver='0WkSdhFnAUxrz4ImQQLdB80GFlE='/><nick xmlns='http://jabber.org/protocol/nick'>%(nick)s</nick><stats xmlns='http://jitsi.org/jitmeet/stats'><stat name='bitrate_download' value='175'/><stat name='bitrate_upload' value='176'/><stat name='packetLoss_total' value='0'/><stat name='packetLoss_download' value='0'/><stat name='packetLoss_upload' value='0'/></stats><media xmlns='http://estos.de/ns/mjs'><source type='audio' ssrc='%(assrc)s' direction='sendre'/><source type='video' ssrc='%(vssrc)s' direction='sendre'/></media></presence>"
% {
"tojid": "%s@%s/%s" % (ROOMNAME, ROOMDOMAIN, self.shortJid),
"nick": self.userId,
"assrc": self.ssrcs["audio"],
"vssrc": self.ssrcs["video"],
}
)
ssrcMsg = "<presence to='%(tojid)s' xmlns='jabber:client'><x xmlns='http://jabber.org/protocol/muc'/><c xmlns='http://jabber.org/protocol/caps' hash='sha-1' node='http://jitsi.org/jitsimeet' ver='0WkSdhFnAUxrz4ImQQLdB80GFlE='/><nick xmlns='http://jabber.org/protocol/nick'>%(nick)s</nick><stats xmlns='http://jitsi.org/jitmeet/stats'><stat name='bitrate_download' value='175'/><stat name='bitrate_upload' value='176'/><stat name='packetLoss_total' value='0'/><stat name='packetLoss_download' value='0'/><stat name='packetLoss_upload' value='0'/></stats><media xmlns='http://estos.de/ns/mjs'><source type='audio' ssrc='%(assrc)s' direction='sendre'/><source type='video' ssrc='%(vssrc)s' direction='sendre'/></media></presence>" % {
"tojid": "%s@%s/%s" % (ROOMNAME, ROOMDOMAIN, self.shortJid),
"nick": self.userId,
"assrc": self.ssrcs["audio"],
"vssrc": self.ssrcs["video"],
}
res = self.sendIq(ssrcMsg)
print("reply from ssrc announce: ", res)
time.sleep(10)
Expand Down
16 changes: 4 additions & 12 deletions docs/code_style.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ errors in code.

The necessary tools are detailed below.

First install them with:

pip install -e ".[lint,mypy]"
Copy link
Contributor Author

@MadLittleMods MadLittleMods Feb 16, 2021

Choose a reason for hiding this comment

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

Updated install instructions to use the version already specified instead of the latest.

Installing the latest version leads to mismatches between editor auto-formating and lint.sh because it has it's own version defined.


- **black**

The Synapse codebase uses [black](https://pypi.org/project/black/)
as an opinionated code formatter, ensuring all comitted code is
properly formatted.

First install `black` with:

pip install --upgrade black

Have `black` auto-format your code (it shouldn't change any
functionality) with:

Expand All @@ -28,10 +28,6 @@ The necessary tools are detailed below.
`flake8` is a code checking tool. We require code to pass `flake8`
before being merged into the codebase.

Install `flake8` with:

pip install --upgrade flake8 flake8-comprehensions

Check all application and test code with:

flake8 synapse tests
Expand All @@ -41,10 +37,6 @@ The necessary tools are detailed below.
`isort` ensures imports are nicely formatted, and can suggest and
auto-fix issues such as double-importing.

Install `isort` with:

pip install --upgrade isort

Auto-fix imports with:

isort -rc synapse tests
Expand Down
4 changes: 3 additions & 1 deletion scripts-dev/mypy_synapse_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,9 @@ def cached_function_method_signature(ctx: MethodSigContext) -> CallableType:
arg_kinds.append(ARG_NAMED_OPT) # Arg is an optional kwarg.

signature = signature.copy_modified(
arg_types=arg_types, arg_names=arg_names, arg_kinds=arg_kinds,
arg_types=arg_types,
arg_names=arg_names,
arg_kinds=arg_kinds,
)

return signature
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def exec_file(path_segments):
# We pin black so that our tests don't start failing on new releases.
CONDITIONAL_REQUIREMENTS["lint"] = [
"isort==5.7.0",
"black==19.10b0",
"black==20.8b1",
"flake8-comprehensions",
"flake8",
]
Expand Down
8 changes: 6 additions & 2 deletions stubs/sortedcontainers/sorteddict.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,16 @@ class SortedDict(Dict[_KT, _VT]):
def __reduce__(
self,
) -> Tuple[
Type[SortedDict[_KT, _VT]], Tuple[Callable[[_KT], Any], List[Tuple[_KT, _VT]]],
Type[SortedDict[_KT, _VT]],
Tuple[Callable[[_KT], Any], List[Tuple[_KT, _VT]]],
]: ...
def __repr__(self) -> str: ...
def _check(self) -> None: ...
def islice(
self, start: Optional[int] = ..., stop: Optional[int] = ..., reverse=bool,
self,
start: Optional[int] = ...,
stop: Optional[int] = ...,
reverse=bool,
) -> Iterator[_KT]: ...
def bisect_left(self, value: _KT) -> int: ...
def bisect_right(self, value: _KT) -> int: ...
Expand Down
16 changes: 13 additions & 3 deletions stubs/sortedcontainers/sortedlist.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ class SortedList(MutableSequence[_T]):

DEFAULT_LOAD_FACTOR: int = ...
def __init__(
self, iterable: Optional[Iterable[_T]] = ..., key: Optional[_Key[_T]] = ...,
self,
iterable: Optional[Iterable[_T]] = ...,
key: Optional[_Key[_T]] = ...,
): ...
# NB: currently mypy does not honour return type, see mypy #3307
@overload
Expand Down Expand Up @@ -76,10 +78,18 @@ class SortedList(MutableSequence[_T]):
def __len__(self) -> int: ...
def reverse(self) -> None: ...
def islice(
self, start: Optional[int] = ..., stop: Optional[int] = ..., reverse=bool,
self,
start: Optional[int] = ...,
stop: Optional[int] = ...,
reverse=bool,
) -> Iterator[_T]: ...
def _islice(
self, min_pos: int, min_idx: int, max_pos: int, max_idx: int, reverse: bool,
self,
min_pos: int,
min_idx: int,
max_pos: int,
max_idx: int,
reverse: bool,
) -> Iterator[_T]: ...
def irange(
self,
Expand Down
Loading