| 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 import defaultdict |
| 18 |
from typing import Any, Dict, List, Set, Tuple, TypeVar |
| 19 |
|
| 20 |
from .data import Entry, Resource, Section |
| 21 |
|
| 22 |
_T = TypeVar("_T") |
| 23 |
_L10nData = List[ |
| 24 |
Tuple[Tuple[str, ...], str, Dict[str, Set[Any]], _T] |
| 25 |
] # id, comment, value |
| 26 |
|
| 27 |
|
| 28 |
def l10n_equal(a: Resource[Any, Any], b: Resource[Any, Any]) -> bool: |
| 29 |
""" |
| 30 |
Compares the localization-relevant content |
| 31 |
(id, comment, metadata, message values) of two resources. |
| 32 |
|
| 33 |
Sections with no message entries are ignored, |
| 34 |
and the order of sections, entries, and metadata is ignored. |
| 35 |
""" |
| 36 |
return ( |
| 37 |
a.format == b.format |
| 38 |
and a.comment.strip() == b.comment.strip() |
| 39 |
and l10n_meta(a) == l10n_meta(b) |
| 40 |
and l10n_sections(a) == l10n_sections(b) |
| 41 |
) |
| 42 |
|
| 43 |
|
| 44 |
def l10n_sections(resource: Resource[Any, Any]) -> _L10nData[_L10nData[Any]]: |
| 45 |
ls = [ |
| 46 |
(section.id, section.comment.strip(), l10n_meta(section), l10n_entries(section)) |
| 47 |
for section in resource.sections |
| 48 |
if any(isinstance(entry, Entry) for entry in section.entries) |
| 49 |
] |
| 50 |
ls.sort() |
| 51 |
nonempty_idx = next( |
| 52 |
(idx for idx, (id, comment, meta, _) in enumerate(ls) if id or comment or meta), |
| 53 |
len(ls), |
| 54 |
) |
| 55 |
if nonempty_idx > 1: |
| 56 |
# Anonymous sections are considered equivalent |
| 57 |
first = ls[0] |
| 58 |
for sd in ls[1:nonempty_idx]: |
| 59 |
first[3].extend(sd[3]) |
| 60 |
first[3].sort() |
| 61 |
del ls[1:nonempty_idx] |
| 62 |
return ls |
| 63 |
|
| 64 |
|
| 65 |
def l10n_entries(section: Section[Any, Any]) -> _L10nData[Any]: |
| 66 |
le = [ |
| 67 |
(entry.id, entry.comment.strip(), l10n_meta(entry), entry.value) |
| 68 |
for entry in section.entries |
| 69 |
if isinstance(entry, Entry) |
| 70 |
] |
| 71 |
le.sort() |
| 72 |
return le |
| 73 |
|
| 74 |
|
| 75 |
def l10n_meta( |
| 76 |
x: Entry[Any, Any] | Section[Any, Any] | Resource[Any, Any], |
| 77 |
) -> dict[str, set[Any]]: |
| 78 |
md: dict[str, set[Any]] = defaultdict(set) |
| 79 |
for m in x.meta: |
| 80 |
md[m.key].add(m.value) |
| 81 |
return md |