Debian Codegraph @

lib/ansible/module_utils/common/locale.py

raw
1 # Copyright (c), Ansible Project
2 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
3
4 from __future__ import annotations
5
6 from ansible.module_utils.common.text.converters import to_native
7
8
9 def get_best_parsable_locale(module, preferences=None, raise_on_locale=False):
10 """
11 Attempts to return the best possible locale for parsing output in English
12 useful for scraping output with i18n tools. When this raises an exception
13 and the caller wants to continue, it should use the 'C' locale.
14
15 :param module: an AnsibleModule instance
16 :param preferences: A list of preferred locales, in order of preference
17 :param raise_on_locale: boolean that determines if we raise exception or not
18 due to locale CLI issues
19 :returns: The first matched preferred locale or 'C' which is the default
20 """
21
22 found = 'C' # default posix, its ascii but always there
23 try:
24 locale = module.get_bin_path("locale")
25 if not locale:
26 # not using required=true as that forces fail_json
27 raise RuntimeWarning("Could not find 'locale' tool")
28
29 available = []
30
31 if preferences is None:
32 # new POSIX standard or English cause those are messages core team expects
33 # yes, the last 2 are the same but some systems are weird
34 preferences = ['C.utf8', 'C.UTF-8', 'en_US.utf8', 'en_US.UTF-8', 'C', 'POSIX']
35
36 rc, out, err = module.run_command([locale, '-a'])
37
38 if rc == 0:
39 if out:
40 available = out.strip().splitlines()
41 else:
42 raise RuntimeWarning("No output from locale, rc=%s: %s" % (rc, to_native(err)))
43 else:
44 raise RuntimeWarning("Unable to get locale information, rc=%s: %s" % (rc, to_native(err)))
45
46 if available:
47 for pref in preferences:
48 if pref in available:
49 found = pref
50 break
51
52 except RuntimeWarning as e:
53 if raise_on_locale:
54 raise
55 else:
56 module.debug('Failed to get locale information: %s' % to_native(e))
57
58 module.debug('Matched preferred locale to: %s' % found)
59
60 return found