in python/moz/l10n/formats/android/serialize.py [0:0]
def set_pattern(el: etree._Element, pattern: Pattern) -> None:
node: etree._Element | None
if len(pattern) == 1 and isinstance(part0 := pattern[0], Expression):
if part0.function == "reference":
# A "string" could be an Android resource reference,
# which should not have its @ or ? sigil escaped.
arg = part0.arg
if isinstance(arg, str) and resource_ref.fullmatch(arg):
el.text = arg
return
else:
raise ValueError(f"Invalid reference value: {arg}")
parent = el
node = None
for part in pattern:
if isinstance(part, str):
esc = escape_part(part)
if node is None:
parent.text = parent.text + esc if parent.text else esc
else:
node.tail = node.tail + esc if node.tail else esc
elif isinstance(part, Expression):
ent_name = entity_name(part)
if part.attributes.get("translate", None) == "no":
# <xliff:g>
attrib = cast(Dict[str, str], part.options) if part.function else None
nsmap = {"xliff": xliff_ns} if not el.nsmap.get("xliff", None) else None
node = etree.SubElement(parent, xliff_g, attrib=attrib, nsmap=nsmap)
if ent_name:
node.append(etree.Entity(ent_name))
elif "source" in part.attributes:
source = part.attributes["source"]
if source:
node.text = str(source)
else:
if isinstance(part.arg, str):
node.text = escape_part(part.arg)
elif isinstance(part.arg, VariableRef):
node.text = part.arg.name
elif ent_name:
node = etree.Entity(ent_name)
parent.append(node)
elif "source" in part.attributes:
source = part.attributes["source"]
if not isinstance(source, str):
raise ValueError(f"Unsupported expression source: {part}")
if node is None:
parent.text = parent.text + source if parent.text else source
else:
node.tail = node.tail + source if node.tail else source
else:
source = None
if isinstance(part.arg, str):
source = escape_part(part.arg)
elif isinstance(part.arg, VariableRef):
source = part.arg.name
if source is not None:
if node is None:
parent.text = parent.text + source if parent.text else source
else:
node.tail = node.tail + source if node.tail else source
else:
raise ValueError(f"Unsupported expression: {part}")
elif any(isinstance(value, VariableRef) for value in part.options.values()):
raise ValueError(f"Unsupported markup with variable option: {part}")
else:
if part.attributes.get("translate", None) == "no":
name = f"{{{xliff_ns}}}g"
elif ":" in part.name:
ns, local = part.name.split(":", 1)
xmlns = el.nsmap.get(ns, xliff_ns if ns == "xliff" else ns)
name = f"{{{xmlns}}}{local}"
else:
name = part.name
attrib = cast(Dict[str, str], part.options)
if part.kind == "standalone":
node = etree.SubElement(parent, name, attrib=attrib)
elif part.kind == "open":
parent = etree.SubElement(parent, name, attrib=attrib)
node = None
elif parent != el and name == parent.tag: # kind == 'close'
node = parent
parent = cast(etree._Element, parent.getparent())
else:
raise ValueError(f"Improper element nesting for {part} in {parent}")
escape_pattern(el)