Convert a list of s3 ObjectSummaries into a directory tree.

    :param objects: The list of objects, e.g. the result of calling
                    `.objects.all()` on a bucket.
    :return: The tree structure, contained within a root node.

def objects_to_root(objects: List) -> Root:
    """
    Convert a list of s3 ObjectSummaries into a directory tree.

    :param objects: The list of objects, e.g. the result of calling
                    `.objects.all()` on a bucket.
    :return: The tree structure, contained within a root node.
    """

    def _to_tree(objs: Iterable) -> Dict:
        """
        Build a tree structure from a flat list of objects.

        :param objs: The raw iterable of S3 `ObjectSummary`s, as returned by a
                     bucket listing.
        :return: The listing as a nested dictionary where keys are directory
                 and file names. The values of directories will in turn be a
                 dict. The values of keys representing files will be the
                 `ObjectSummary` instance.
        """
        path_tree = {}
        for obj in objs:
            is_dir = obj.key.endswith('/')
            chunks = [chunk for chunk in obj.key.split('/') if chunk]
            chunk_count = len(chunks)
            tmp = path_tree
            for i, chunk in enumerate(chunks):
                is_last_chunk = i == chunk_count - 1

                if is_last_chunk and not is_dir:
                    tmp[chunk] = obj
                else:
                    # must be a directory
                    if chunk not in tmp:
                        # it doesn't exist - create it
                        tmp[chunk] = {}
                    tmp = tmp[chunk]
        return path_tree

    def _to_entity(key: str, value: Union[Dict, Any]) -> Entity:
        """
        Turn a nested dictionary representing an S3 bucket into the correct
        `Entity` object.

        :param key: The name of the entity.
        :param value: If the entity is a directory, the nested dict
                      representing its contents. Otherwise, the `ObjectSummary`
                      instance representing the file.
        :return: The entity representing the entity name and value pair.
        """
        if isinstance(value, dict):
            return Directory(
                key,
                {key_: _to_entity(key_, value_)
                 for key_, value_ in value.items()})

        return File(pathlib.PurePath(value.key).name, value.size,
                    value.e_tag.strip('"'))

    tree = _to_tree(objects)
    return Root({pathlib.PurePath(key).name: _to_entity(key, value)
                 for key, value in tree.items()})