Add types to synapse.util. (#10601)

This commit is contained in:
reivilibre 2021-09-10 17:03:18 +01:00 committed by GitHub
parent ceab5a4bfa
commit 524b8ead77
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
41 changed files with 400 additions and 253 deletions

View file

@ -13,42 +13,43 @@
# limitations under the License.
import logging
from typing import Dict
from twisted.web.resource import NoResource
from twisted.web.resource import NoResource, Resource
logger = logging.getLogger(__name__)
def create_resource_tree(desired_tree, root_resource):
def create_resource_tree(
desired_tree: Dict[str, Resource], root_resource: Resource
) -> Resource:
"""Create the resource tree for this homeserver.
This in unduly complicated because Twisted does not support putting
child resources more than 1 level deep at a time.
Args:
web_client (bool): True to enable the web client.
root_resource (twisted.web.resource.Resource): The root
resource to add the tree to.
desired_tree: Dict from desired paths to desired resources.
root_resource: The root resource to add the tree to.
Returns:
twisted.web.resource.Resource: the ``root_resource`` with a tree of
child resources added to it.
The ``root_resource`` with a tree of child resources added to it.
"""
# ideally we'd just use getChild and putChild but getChild doesn't work
# unless you give it a Request object IN ADDITION to the name :/ So
# instead, we'll store a copy of this mapping so we can actually add
# extra resources to existing nodes. See self._resource_id for the key.
resource_mappings = {}
for full_path, res in desired_tree.items():
resource_mappings: Dict[str, Resource] = {}
for full_path_str, res in desired_tree.items():
# twisted requires all resources to be bytes
full_path = full_path.encode("utf-8")
full_path = full_path_str.encode("utf-8")
logger.info("Attaching %s to path %s", res, full_path)
last_resource = root_resource
for path_seg in full_path.split(b"/")[1:-1]:
if path_seg not in last_resource.listNames():
# resource doesn't exist, so make a "dummy resource"
child_resource = NoResource()
child_resource: Resource = NoResource()
last_resource.putChild(path_seg, child_resource)
res_id = _resource_id(last_resource, path_seg)
resource_mappings[res_id] = child_resource
@ -83,7 +84,7 @@ def create_resource_tree(desired_tree, root_resource):
return root_resource
def _resource_id(resource, path_seg):
def _resource_id(resource: Resource, path_seg: bytes) -> str:
"""Construct an arbitrary resource ID so you can retrieve the mapping
later.
@ -96,4 +97,4 @@ def _resource_id(resource, path_seg):
Returns:
str: A unique string which can be a key to the child Resource.
"""
return "%s-%s" % (resource, path_seg)
return "%s-%r" % (resource, path_seg)