1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

locale_gen: refactor (#6903)

* locale_gen: refactor

* fix sanity

* add changelog frag
This commit is contained in:
Alexei Znamensky 2023-07-15 22:54:53 +12:00 committed by GitHub
parent ea6fb9da8f
commit 3a6955cbd7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 144 additions and 168 deletions

View file

@ -0,0 +1,2 @@
minor_changes:
- locale_gen - module has been refactored to use ``ModuleHelper`` and ``CmdRunner`` (https://github.com/ansible-collections/community.general/pull/6903).

View file

@ -49,11 +49,13 @@ EXAMPLES = '''
import os import os
import re import re
from ansible.module_utils.basic import AnsibleModule from ansible_collections.community.general.plugins.module_utils.module_helper import StateModuleHelper
from ansible.module_utils.common.text.converters import to_native from ansible_collections.community.general.plugins.module_utils.mh.deco import check_mode_skip
from ansible_collections.community.general.plugins.module_utils.locale_gen import locale_runner, locale_gen_runner from ansible_collections.community.general.plugins.module_utils.locale_gen import locale_runner, locale_gen_runner
class LocaleGen(StateModuleHelper):
LOCALE_NORMALIZATION = { LOCALE_NORMALIZATION = {
".utf8": ".UTF-8", ".utf8": ".UTF-8",
".eucjp": ".EUC-JP", ".eucjp": ".EUC-JP",
@ -66,99 +68,113 @@ LOCALE_NORMALIZATION = {
".gb18030": ".GB18030", ".gb18030": ".GB18030",
".euctw": ".EUC-TW", ".euctw": ".EUC-TW",
} }
LOCALE_GEN = "/etc/locale.gen"
LOCALE_SUPPORTED = "/var/lib/locales/supported.d/"
module = None output_params = ["name"]
module = dict(
argument_spec=dict(
name=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['absent', 'present']),
),
supports_check_mode=True,
)
def __init_module__(self):
self.vars.set("ubuntu_mode", False)
if os.path.exists(self.LOCALE_SUPPORTED):
self.vars.ubuntu_mode = True
else:
if not os.path.exists(self.LOCALE_GEN):
self.do_raise("{0} and {1} are missing. Is the package \"locales\" installed?".format(
self.LOCALE_SUPPORTED, self.LOCALE_GEN
))
# =========================================== if not self.is_available():
# location module specific support methods. self.do_raise("The locale you've entered is not available on your system.")
#
def is_available(name, ubuntuMode): self.vars.set("is_present", self.is_present(), output=False)
self.vars.set("state_tracking", self._state_name(self.vars.is_present), output=False, change=True)
def __quit_module__(self):
self.vars.state_tracking = self._state_name(self.is_present())
@staticmethod
def _state_name(present):
return "present" if present else "absent"
def is_available(self):
"""Check if the given locale is available on the system. This is done by """Check if the given locale is available on the system. This is done by
checking either : checking either :
* if the locale is present in /etc/locales.gen * if the locale is present in /etc/locales.gen
* or if the locale is present in /usr/share/i18n/SUPPORTED""" * or if the locale is present in /usr/share/i18n/SUPPORTED"""
__regexp = r'^#?\s*(?P<locale>\S+[\._\S]*) (?P<charset>\S+)\s*$' __regexp = r'^#?\s*(?P<locale>\S+[\._\S]+) (?P<charset>\S+)\s*$'
if ubuntuMode: if self.vars.ubuntu_mode:
__locales_available = '/usr/share/i18n/SUPPORTED' __locales_available = '/usr/share/i18n/SUPPORTED'
else: else:
__locales_available = '/etc/locale.gen' __locales_available = '/etc/locale.gen'
re_compiled = re.compile(__regexp) re_compiled = re.compile(__regexp)
fd = open(__locales_available, 'r') with open(__locales_available, 'r') as fd:
for line in fd: lines = fd.readlines()
result = re_compiled.match(line) res = [re_compiled.match(line) for line in lines]
if result and result.group('locale') == name: if self.verbosity >= 4:
self.vars.available_lines = lines
if any(r.group("locale") == self.vars.name for r in res if r):
return True return True
fd.close()
# locale may be installed but not listed in the file, for example C.UTF-8 in some systems # locale may be installed but not listed in the file, for example C.UTF-8 in some systems
return is_present(name) return self.is_present()
def is_present(self):
def is_present(name): runner = locale_runner(self.module)
"""Checks if the given locale is currently installed."""
runner = locale_runner(module)
with runner() as ctx: with runner() as ctx:
dummy, output, dummy = ctx.run() rc, out, err = ctx.run()
return any(fix_case(name) == fix_case(line) for line in output.splitlines()) if self.verbosity >= 4:
self.vars.locale_run_info = ctx.run_info
return any(self.fix_case(self.vars.name) == self.fix_case(line) for line in out.splitlines())
def fix_case(self, name):
def fix_case(name):
"""locale -a might return the encoding in either lower or upper case. """locale -a might return the encoding in either lower or upper case.
Passing through this function makes them uniform for comparisons.""" Passing through this function makes them uniform for comparisons."""
for s, r in LOCALE_NORMALIZATION.items(): for s, r in self.LOCALE_NORMALIZATION.items():
name = name.replace(s, r) name = name.replace(s, r)
return name return name
def set_locale(self, name, enabled=True):
def set_locale(name, enabled=True):
""" Sets the state of the locale. Defaults to enabled. """ """ Sets the state of the locale. Defaults to enabled. """
search_string = r'#{0,1}\s*%s (?P<charset>.+)' % name search_string = r'#?\s*%s (?P<charset>.+)' % re.escape(name)
if enabled: if enabled:
new_string = r'%s \g<charset>' % (name) new_string = r'%s \g<charset>' % (name)
else: else:
new_string = r'# %s \g<charset>' % (name) new_string = r'# %s \g<charset>' % (name)
try: re_search = re.compile(search_string)
f = open("/etc/locale.gen", "r") with open("/etc/locale.gen", "r") as fr:
lines = [re.sub(search_string, new_string, line) for line in f] lines = [re_search.sub(new_string, line) for line in fr]
finally: with open("/etc/locale.gen", "w") as fw:
f.close() fw.write("".join(lines))
try:
f = open("/etc/locale.gen", "w")
f.write("".join(lines))
finally:
f.close()
def apply_change(self, targetState, name):
def apply_change(targetState, name):
"""Create or remove locale. """Create or remove locale.
Keyword arguments: Keyword arguments:
targetState -- Desired state, either present or absent. targetState -- Desired state, either present or absent.
name -- Name including encoding such as de_CH.UTF-8. name -- Name including encoding such as de_CH.UTF-8.
""" """
runner = locale_gen_runner(module)
if targetState == "present": self.set_locale(name, enabled=(targetState == "present"))
# Create locale.
set_locale(name, enabled=True)
else:
# Delete locale.
set_locale(name, enabled=False)
runner = locale_gen_runner(self.module)
with runner() as ctx: with runner() as ctx:
ctx.run() ctx.run()
def apply_change_ubuntu(self, targetState, name):
def apply_change_ubuntu(targetState, name):
"""Create or remove locale. """Create or remove locale.
Keyword arguments: Keyword arguments:
targetState -- Desired state, either present or absent. targetState -- Desired state, either present or absent.
name -- Name including encoding such as de_CH.UTF-8. name -- Name including encoding such as de_CH.UTF-8.
""" """
runner = locale_gen_runner(module) runner = locale_gen_runner(self.module)
if targetState == "present": if targetState == "present":
# Create locale. # Create locale.
@ -167,72 +183,30 @@ def apply_change_ubuntu(targetState, name):
ctx.run() ctx.run()
else: else:
# Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales. # Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales.
try: with open("/var/lib/locales/supported.d/local", "r") as fr:
f = open("/var/lib/locales/supported.d/local", "r") content = fr.readlines()
content = f.readlines() with open("/var/lib/locales/supported.d/local", "w") as fw:
finally:
f.close()
try:
f = open("/var/lib/locales/supported.d/local", "w")
for line in content: for line in content:
locale, charset = line.split(' ') locale, charset = line.split(' ')
if locale != name: if locale != name:
f.write(line) fw.write(line)
finally:
f.close()
# Purge locales and regenerate. # Purge locales and regenerate.
# Please provide a patch if you know how to avoid regenerating the locales to keep! # Please provide a patch if you know how to avoid regenerating the locales to keep!
with runner("purge") as ctx: with runner("purge") as ctx:
ctx.run() ctx.run()
@check_mode_skip
def __state_fallback__(self):
if self.vars.state_tracking == self.vars.state:
return
if self.vars.ubuntu_mode:
self.apply_change_ubuntu(self.vars.state, self.vars.name)
else:
self.apply_change(self.vars.state, self.vars.name)
def main(): def main():
global module LocaleGen.execute()
module = AnsibleModule(
argument_spec=dict(
name=dict(type='str', required=True),
state=dict(type='str', default='present', choices=['absent', 'present']),
),
supports_check_mode=True,
)
name = module.params['name']
state = module.params['state']
if not os.path.exists("/var/lib/locales/supported.d/"):
if os.path.exists("/etc/locale.gen"):
# We found the common way to manage locales.
ubuntuMode = False
else:
module.fail_json(msg="/etc/locale.gen and /var/lib/locales/supported.d/local are missing. Is the package 'locales' installed?")
else:
# Ubuntu created its own system to manage locales.
ubuntuMode = True
if not is_available(name, ubuntuMode):
module.fail_json(msg="The locale you've entered is not available "
"on your system.")
if is_present(name):
prev_state = "present"
else:
prev_state = "absent"
changed = (prev_state != state)
if module.check_mode:
module.exit_json(changed=changed)
else:
if changed:
try:
if ubuntuMode is False:
apply_change(state, name)
else:
apply_change_ubuntu(state, name)
except EnvironmentError as e:
module.fail_json(msg=to_native(e), exitValue=e.errno)
module.exit_json(name=name, changed=changed, msg="OK")
if __name__ == '__main__': if __name__ == '__main__':