def flatten()

in python/moz/l10n/formats/android/parse.py [0:0]


def flatten(el: etree._Element) -> Iterator[str | Expression | Markup]:
    if el.text:
        yield el.text
    for child in el:
        if isinstance(child, etree._Entity):
            yield Expression(VariableRef(child.name), "entity")
        else:
            name = (
                f"{child.prefix}:{etree.QName(child.tag).localname}"
                if child.prefix
                else child.tag
            )
            if child.tag == xliff_g:
                body = list(flatten(child))
                if any(
                    (
                        isinstance(gc, Expression)
                        and gc.attributes.get("translate", None) == "no"
                    )
                    or isinstance(gc, Markup)
                    for gc in body
                ):
                    # Any <xliff:g> around elements needs to be rendered explicitly
                    yield Markup("open", name, dict(child.attrib), {"translate": "no"})
                    yield from body
                    yield Markup("close", name, attributes={"translate": "no"})
                else:
                    id = child.get("id", None)
                    for gc in body:
                        if isinstance(gc, str):
                            options: dict[str, str | VariableRef] = dict(child.attrib)
                            attr: dict[str, str | Literal[True]] = {"translate": "no"}
                            arg: str | VariableRef | None
                            if id:
                                arg = VariableRef(get_var_name(id))
                                attr["source"] = gc
                            elif gc.startswith(("%", "{")):
                                arg = VariableRef(get_var_name(gc))
                                attr["source"] = gc
                            else:
                                arg = gc
                            if options:
                                yield Expression(arg, name, options, attributes=attr)
                            else:
                                yield Expression(arg, attributes=attr)
                        else:
                            gc.attributes["translate"] = "no"
                            gc.options = dict(child.attrib)
                            yield gc
            else:
                yield Markup("open", name, options=dict(child.attrib))
                yield from flatten(child)
                yield Markup("close", name)
        if child.tail:
            yield child.tail