| 1 |
# Copyright Mozilla Foundation |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
from collections.abc import Iterator |
| 18 |
from json import dumps |
| 19 |
from re import sub |
| 20 |
from typing import Any |
| 21 |
|
| 22 |
from ...message import Declaration, Expression, Message, PatternMessage, VariableRef |
| 23 |
from ..data import Entry, Resource |
| 24 |
|
| 25 |
|
| 26 |
def webext_serialize( |
| 27 |
resource: Resource[str, Any] | Resource[Message, Any], |
| 28 |
trim_comments: bool = False, |
| 29 |
) -> Iterator[str]: |
| 30 |
""" |
| 31 |
Serialize a resource as the contents of a messages.json file. |
| 32 |
|
| 33 |
Section identifiers and multi-part message identifiers are not supported. |
| 34 |
Resource and section comments are not supported. |
| 35 |
Metadata is not supported. |
| 36 |
|
| 37 |
Yields the entire JSON result as a single string. |
| 38 |
""" |
| 39 |
|
| 40 |
def check(comment: str | None, meta: Any) -> None: |
| 41 |
if trim_comments: |
| 42 |
return |
| 43 |
if comment: |
| 44 |
raise ValueError("Resource and section comments are not supported") |
| 45 |
if meta: |
| 46 |
raise ValueError("Metadata is not supported") |
| 47 |
|
| 48 |
check(resource.comment, resource.meta) |
| 49 |
res: dict[str, Any] = {} |
| 50 |
for section in resource.sections: |
| 51 |
if section.id: |
| 52 |
raise ValueError(f"Section identifiers not supported: {section.id}") |
| 53 |
check(section.comment, section.meta) |
| 54 |
for entry in section.entries: |
| 55 |
if isinstance(entry, Entry): |
| 56 |
check(None, entry.meta) |
| 57 |
if len(entry.id) != 1: |
| 58 |
raise ValueError(f"Unsupported entry identifier: {entry.id}") |
| 59 |
name = entry.id[0] |
| 60 |
if isinstance(entry.value, str): |
| 61 |
res[name] = {"message": sub(r"\$+", r"$\g<0>", entry.value)} |
| 62 |
if not trim_comments and entry.comment: |
| 63 |
res[name]["description"] = entry.comment |
| 64 |
elif isinstance(entry.value, PatternMessage): |
| 65 |
res[name] = webext_message(name, entry, trim_comments) # type: ignore[arg-type] |
| 66 |
else: |
| 67 |
raise ValueError(f"Unsupported entry for {name}: {entry.value}") |
| 68 |
else: |
| 69 |
check(entry.comment, None) |
| 70 |
yield dumps(res, indent=2) |
| 71 |
yield "\n" |
| 72 |
|
| 73 |
|
| 74 |
def webext_message( |
| 75 |
name: str, entry: Entry[PatternMessage, Any], trim_comments: bool |
| 76 |
) -> dict[str, Any]: |
| 77 |
msg = "" |
| 78 |
placeholders: dict[str, Any] = {} |
| 79 |
for part in entry.value.pattern: |
| 80 |
if isinstance(part, str): |
| 81 |
msg += sub(r"\$+", r"$\g<0>", part) |
| 82 |
elif ( |
| 83 |
isinstance(part, Expression) |
| 84 |
and isinstance(part.arg, VariableRef) |
| 85 |
and part.annotation is None |
| 86 |
): |
| 87 |
ph_name = part.arg.name |
| 88 |
source = part.attributes.get("source", None) |
| 89 |
local = next( |
| 90 |
( |
| 91 |
d.value |
| 92 |
for d in entry.value.declarations |
| 93 |
if isinstance(d, Declaration) and d.name == ph_name |
| 94 |
), |
| 95 |
None, |
| 96 |
) |
| 97 |
if local: |
| 98 |
local_source = local.attributes.get("source", None) |
| 99 |
if isinstance(local_source, str): |
| 100 |
content = local_source |
| 101 |
elif isinstance(local.arg, VariableRef): |
| 102 |
content = local.arg.name |
| 103 |
if not content.startswith("$"): |
| 104 |
content = f"${content}" |
| 105 |
elif isinstance(local.arg, str): |
| 106 |
content = local.arg |
| 107 |
else: |
| 108 |
raise ValueError( |
| 109 |
f"Unsupported placeholder for {ph_name} in {name}: {local}" |
| 110 |
) |
| 111 |
if local.annotation: |
| 112 |
raise ValueError( |
| 113 |
f"Unsupported annotation for {ph_name} in {name}: {local}" |
| 114 |
) |
| 115 |
if ( |
| 116 |
isinstance(source, str) |
| 117 |
and len(source) >= 3 |
| 118 |
and source.startswith("$") |
| 119 |
and source.endswith("$") |
| 120 |
): |
| 121 |
ph_name = source[1:-1] |
| 122 |
else: |
| 123 |
source = None |
| 124 |
if not any(key.lower() == ph_name.lower() for key in placeholders): |
| 125 |
placeholders[ph_name] = {"content": content} |
| 126 |
example = ( |
| 127 |
None if trim_comments else local.attributes.get("example", None) |
| 128 |
) |
| 129 |
if isinstance(example, str): |
| 130 |
placeholders[ph_name]["example"] = example |
| 131 |
elif example: |
| 132 |
raise ValueError( |
| 133 |
f"Unsupported placeholder example for {ph_name} in {name}: {example}" |
| 134 |
) |
| 135 |
msg += source or f"${ph_name}$" |
| 136 |
else: |
| 137 |
arg_name = source if isinstance(source, str) else ph_name |
| 138 |
msg += arg_name if arg_name.startswith("$") else f"${arg_name}" |
| 139 |
else: |
| 140 |
raise ValueError(f"Unsupported message part for {name}: {part}") |
| 141 |
res: dict[str, Any] = {"message": msg} |
| 142 |
if not trim_comments and entry.comment: |
| 143 |
res["description"] = entry.comment |
| 144 |
if placeholders: |
| 145 |
res["placeholders"] = placeholders |
| 146 |
return res |