| 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 re import fullmatch |
| 18 |
|
| 19 |
ANDROID_LOCALES = {"he": "iw", "id": "in", "yi": "ji"} |
| 20 |
|
| 21 |
|
| 22 |
# https://android.googlesource.com/platform/tools/base/+/master/sdk-common/src/main/java/com/android/ide/common/resources/configuration/LocaleQualifier.java#28 |
| 23 |
def get_android_locale(locale: str) -> str: |
| 24 |
lc, *rest = locale.split("-") |
| 25 |
if lc in ANDROID_LOCALES: |
| 26 |
lc = ANDROID_LOCALES[lc] |
| 27 |
if not rest: |
| 28 |
return lc |
| 29 |
if len(rest) == 1 and fullmatch(r"[A-Z]{2}", rest[0]): |
| 30 |
return f"{lc}-r{rest[0]}" |
| 31 |
return f"b+{lc}+{'+'.join(rest)}" |
| 32 |
|
| 33 |
|
| 34 |
def parse_android_locale(alocale: str) -> str | None: |
| 35 |
if alocale.startswith("b+"): |
| 36 |
lc, *rest = alocale[2:].split("+") |
| 37 |
else: |
| 38 |
m = fullmatch(r"([a-z]{2,3})(?:-r([A-Z]{2}))?", alocale) |
| 39 |
if m is None: |
| 40 |
return None # Not a valid Android locale |
| 41 |
lc = m[1] |
| 42 |
rest = [m[2]] if m[2] else [] |
| 43 |
for current, legacy in ANDROID_LOCALES.items(): |
| 44 |
if lc == legacy: |
| 45 |
lc = current |
| 46 |
break |
| 47 |
return "-".join((lc, *rest)) |