summaryrefslogtreecommitdiff
path: root/system/locale_gen.py
blob: bd4b149dccec719c178e05639bac9260abed561c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible.  If not, see <http://www.gnu.org/licenses/>.

DOCUMENTATION = '''
---
module: locale_gen
short_description: Creates or removes locales.
description:
     - Manages locales by editing /etc/locale.gen and invoking locale-gen.
version_added: "1.6"
author: "Augustus Kling (@AugustusKling)"
options:
    name:
        description:
             - Name and encoding of the locale, such as "en_GB.UTF-8".
        required: true
        default: null
        aliases: []
    state:
      description:
           - Whether the locale shall be present.
      required: false
      choices: ["present", "absent"]
      default: "present"
'''

EXAMPLES = '''
# Ensure a locale exists.
- locale_gen:
    name: de_CH.UTF-8
    state: present
'''

import os
import os.path
from subprocess import Popen, PIPE, call
import re

from ansible.module_utils.basic import *
from ansible.module_utils.pycompat24 import get_exception

LOCALE_NORMALIZATION = {
    ".utf8": ".UTF-8",
    ".eucjp": ".EUC-JP",
    ".iso885915": ".ISO-8859-15",
    ".cp1251": ".CP1251",
    ".koi8r": ".KOI8-R",
    ".armscii8": ".ARMSCII-8",
    ".euckr": ".EUC-KR",
    ".gbk": ".GBK",
    ".gb18030": ".GB18030",
    ".euctw": ".EUC-TW",
}

# ===========================================
# location module specific support methods.
#

def is_available(name, ubuntuMode):
    """Check if the given locale is available on the system. This is done by
    checking either :
    * if the locale is present in /etc/locales.gen
    * or if the locale is present in /usr/share/i18n/SUPPORTED"""
    if ubuntuMode:
        __regexp = '^(?P<locale>\S+_\S+) (?P<charset>\S+)\s*$'
        __locales_available = '/usr/share/i18n/SUPPORTED'
    else:
        __regexp = '^#{0,1}\s*(?P<locale>\S+_\S+) (?P<charset>\S+)\s*$'
        __locales_available = '/etc/locale.gen'

    re_compiled = re.compile(__regexp)
    fd = open(__locales_available, 'r')
    for line in fd:
        result = re_compiled.match(line)
        if result and result.group('locale') == name:
            return True
    fd.close()
    return False

def is_present(name):
    """Checks if the given locale is currently installed."""
    output = Popen(["locale", "-a"], stdout=PIPE).communicate()[0]
    return any(fix_case(name) == fix_case(line) for line in output.splitlines())

def fix_case(name):
    """locale -a might return the encoding in either lower or upper case.
    Passing through this function makes them uniform for comparisons."""
    for s, r in LOCALE_NORMALIZATION.items():
        name = name.replace(s, r)
    return name

def replace_line(existing_line, new_line):
    """Replaces lines in /etc/locale.gen"""
    try:
        f = open("/etc/locale.gen", "r")
        lines = [line.replace(existing_line, new_line) for line in f]
    finally:
        f.close()
    try:
        f = open("/etc/locale.gen", "w")
        f.write("".join(lines))
    finally:
        f.close()

def set_locale(name, enabled=True):
    """ Sets the state of the locale. Defaults to enabled. """
    search_string = '#{0,1}\s*%s (?P<charset>.+)' % name
    if enabled:
        new_string = '%s \g<charset>' % (name)
    else:
        new_string = '# %s \g<charset>' % (name)
    try:
        f = open("/etc/locale.gen", "r")
        lines = [re.sub(search_string, new_string, line) for line in f]
    finally:
        f.close()
    try:
        f = open("/etc/locale.gen", "w")
        f.write("".join(lines))
    finally:
        f.close()

def apply_change(targetState, name):
    """Create or remove locale.

    Keyword arguments:
    targetState -- Desired state, either present or absent.
    name -- Name including encoding such as de_CH.UTF-8.
    """
    if targetState=="present":
        # Create locale.
        set_locale(name, enabled=True)
    else:
        # Delete locale.
        set_locale(name, enabled=False)
    
    localeGenExitValue = call("locale-gen")
    if localeGenExitValue!=0:
        raise EnvironmentError(localeGenExitValue, "locale.gen failed to execute, it returned "+str(localeGenExitValue))

def apply_change_ubuntu(targetState, name):
    """Create or remove locale.
    
    Keyword arguments:
    targetState -- Desired state, either present or absent.
    name -- Name including encoding such as de_CH.UTF-8.
    """
    if targetState=="present":
        # Create locale.
        # Ubuntu's patched locale-gen automatically adds the new locale to /var/lib/locales/supported.d/local
        localeGenExitValue = call(["locale-gen", name])
    else:
        # Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales.
        try:
            f = open("/var/lib/locales/supported.d/local", "r")
            content = f.readlines()
        finally:
            f.close()
        try:
            f = open("/var/lib/locales/supported.d/local", "w")
            for line in content:
                locale, charset = line.split(' ')
                if locale != name:
                    f.write(line)
        finally:
            f.close()
        # Purge locales and regenerate.
        # Please provide a patch if you know how to avoid regenerating the locales to keep!
        localeGenExitValue = call(["locale-gen", "--purge"])
    
    if localeGenExitValue!=0:
        raise EnvironmentError(localeGenExitValue, "locale.gen failed to execute, it returned "+str(localeGenExitValue))

# ==============================================================
# main

def main():

    module = AnsibleModule(
        argument_spec = dict(
            name = dict(required=True),
            state = dict(choices=['present','absent'], default='present'),
        ),
        supports_check_mode=True
    )

    name = module.params['name']
    state = module.params['state']

    if not os.path.exists("/etc/locale.gen"):
        if os.path.exists("/var/lib/locales/supported.d/"):
            # Ubuntu created its own system to manage locales.
            ubuntuMode = True
        else:
            module.fail_json(msg="/etc/locale.gen and /var/lib/locales/supported.d/local are missing. Is the package \"locales\" installed?")
    else:
        # We found the common way to manage locales.
        ubuntuMode = False

    if not is_available(name, ubuntuMode):
        module.fail_json(msg="The locales 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==False:
                    apply_change(state, name)
                else:
                    apply_change_ubuntu(state, name)
            except EnvironmentError:
                e = get_exception()
                module.fail_json(msg=e.strerror, exitValue=e.errno)

        module.exit_json(name=name, changed=changed, msg="OK")


if __name__ == '__main__':
    main()