Debian Codegraph @

third_party/python/moz.l10n/moz/l10n/resource/webext/parse.py

raw
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 json import loads
18 from re import compile
19 from typing import Any
20
21 from ...message import (
22 Declaration,
23 Expression,
24 Message,
25 Pattern,
26 PatternMessage,
27 UnsupportedStatement,
28 VariableRef,
29 )
30 from ..data import Comment, Entry, Resource, Section
31 from ..format import Format
32
33 placeholder = compile(r"\$([a-zA-Z0-9_@]+)\$|(\$[1-9])|\$(\$+)")
34 pos_arg = compile(r"\$([1-9])")
35
36
37 def webext_parse(source: str | bytes) -> Resource[Message, Any]:
38 """
39 Parse a messages.json file into a message resource.
40
41 Named placeholders are represented as declarations,
42 with an attribute used for an example, if it's available.
43
44 The parsed resource will not include any metadata.
45 """
46 json: dict[str, dict[str, Any]] = loads(source)
47 entries: list[Entry[Message, Any] | Comment] = []
48 for key, msg in json.items():
49 src: str = msg["message"]
50 comment: str = msg.get("description", "")
51 ph_data: dict[str, dict[str, str]] = (
52 {k.lower(): v for k, v in msg["placeholders"].items()}
53 if "placeholders" in msg
54 else {}
55 )
56 declarations: list[Declaration | UnsupportedStatement] = []
57 pattern: Pattern = []
58 pos = 0
59 for m in placeholder.finditer(src):
60 text = src[pos : m.start()]
61 if text:
62 if pattern and isinstance(pattern[-1], str):
63 pattern[-1] += text
64 else:
65 pattern.append(text)
66 if m[1]:
67 # Named placeholder, with content & optional example in placeholders object
68 ph = ph_data[m[1].lower()]
69 if "_name" in ph:
70 ph_name = ph["_name"]
71 else:
72 decl_src = ph["content"]
73 decl_arg_match = pos_arg.fullmatch(decl_src)
74 decl_value = (
75 Expression(
76 VariableRef(f"arg{decl_arg_match[1]}"),
77 attributes={"source": decl_src},
78 )
79 if decl_arg_match
80 else Expression(decl_src)
81 )
82 if "example" in ph:
83 decl_value.attributes["example"] = ph["example"]
84 ph_name = m[1].replace("@", "_")
85 if ph_name[0].isdigit():
86 ph_name = f"_{ph_name}"
87 declarations.append(Declaration(ph_name, decl_value))
88 ph["_name"] = ph_name
89 exp = Expression(VariableRef(ph_name), attributes={"source": m[0]})
90 pattern.append(exp)
91 elif m[2]:
92 # Indexed placeholder
93 ph_src = m[2]
94 pattern.append(
95 Expression(
96 VariableRef(f"arg{ph_src[1]}"), attributes={"source": ph_src}
97 )
98 )
99 else:
100 # Escaped literal dollar sign
101 if pattern and isinstance(pattern[-1], str):
102 pattern[-1] += m[3]
103 else:
104 pattern.append(m[3])
105 pos = m.end()
106 if pos < len(src):
107 rest = src[pos:]
108 if pattern and isinstance(pattern[-1], str):
109 pattern[-1] += rest
110 else:
111 pattern.append(rest)
112 entries.append(
113 Entry((key,), PatternMessage(pattern, declarations), comment=comment)
114 )
115 return Resource(Format.webext, [Section((), entries)])