Debian Codegraph @

test/lib/ansible_test/_internal/locale_util.py

raw
1 """Initialize locale settings. This must be imported very early in ansible-test startup."""
2
3 from __future__ import annotations
4
5 import locale
6 import sys
7 import typing as t
8
9 STANDARD_LOCALE = 'en_US.UTF-8'
10 """
11 The standard locale used by ansible-test and its subprocesses and delegated instances.
12 """
13
14 FALLBACK_LOCALE = 'C.UTF-8'
15 """
16 The fallback locale to use when the standard locale is not available.
17 This was added in ansible-core 2.14 to allow testing in environments without the standard locale.
18 It was not needed in previous ansible-core releases since they do not verify the locale during startup.
19 """
20
21
22 class LocaleError(SystemExit):
23 """Exception to raise when locale related errors occur."""
24
25 def __init__(self, message: str) -> None:
26 super().__init__(f'ERROR: {message}')
27
28
29 def configure_locale() -> tuple[str, t.Optional[str]]:
30 """Configure the locale, returning the selected locale and an optional warning."""
31
32 if (fs_encoding := sys.getfilesystemencoding()).lower() != 'utf-8':
33 raise LocaleError(f'ansible-test requires the filesystem encoding to be UTF-8, but "{fs_encoding}" was detected.')
34
35 candidate_locales = STANDARD_LOCALE, FALLBACK_LOCALE
36
37 errors: dict[str, str] = {}
38 warning: t.Optional[str] = None
39 configured_locale: t.Optional[str] = None
40
41 for candidate_locale in candidate_locales:
42 try:
43 locale.setlocale(locale.LC_ALL, candidate_locale)
44 locale.getlocale()
45 except (locale.Error, ValueError) as ex:
46 errors[candidate_locale] = str(ex)
47 else:
48 configured_locale = candidate_locale
49 break
50
51 if not configured_locale:
52 raise LocaleError('ansible-test could not initialize a supported locale:\n' +
53 '\n'.join(f'{key}: {value}' for key, value in errors.items()))
54
55 if configured_locale != STANDARD_LOCALE:
56 warning = (f'Using locale "{configured_locale}" instead of "{STANDARD_LOCALE}". '
57 'Tests which depend on the locale may behave unexpectedly.')
58
59 return configured_locale, warning
60
61
62 CONFIGURED_LOCALE, LOCALE_WARNING = configure_locale()