This repository has been archived by the owner on Jun 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathgsetting.py
204 lines (157 loc) · 6.05 KB
/
gsetting.py
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
#!/usr/bin/python
from os import environ
import re
import subprocess
from ansible.module_utils.basic import AnsibleModule
class Setting:
def __init__(self, schema, path, key):
if not schema:
schema, key = self.split_key(key)
if path:
if not path.endswith('/'):
path += '/'
arg1 = schema
if path:
arg1 += ':' + path
self.args = (arg1, key)
@staticmethod
def split_key(full_key):
key_array = full_key.split('.')
schema = '.'.join(key_array[0:-1])
single_key = key_array[-1]
return (schema, single_key)
def _check_output_strip(command):
return subprocess.check_output(command).decode('utf-8').strip()
def _escape_single_quotes(string):
return re.sub("'", r"'\''", string)
def _maybe_int(val):
try:
return int(val)
except ValueError:
return 0
def _get_gnome_version():
try:
return tuple(map(_maybe_int, (_check_output_strip(
['gnome-shell', '--version']).split(' ')[2].split('.'))))
except FileNotFoundError:
return None
def _get_gnome_session_pid(user):
gnome_ver = _get_gnome_version()
if gnome_ver and gnome_ver >= (42,):
# It's actually gnome-session-binary, but pgrep uses /proc/#/status,
# which truncates the process name at 15 characters.
#
# Note that this may _also_ work for GNOME 3.33.90, i.e., the code
# block below, but I'm preserving that behavior because I don't have
# earlier GNOME versions to check.
#
# Note also that the code block below won't work when the default
# session named "gnome" isn't used. For example, in recent versions of
# ubuntu the session name is "ubuntu", i.e., "session=ubuntu" rather
# than "session=gnome".
pgrep_cmd = ['pgrep', '-u', user, 'gnome-session-b']
elif gnome_ver and gnome_ver >= (3, 33, 90):
# From GNOME 3.33.90 session process has changed
# https://github.com/GNOME/gnome-session/releases/tag/3.33.90
pgrep_cmd = ['pgrep', '-u', user, '-f', 'session=gnome']
else:
pgrep_cmd = ['pgrep', '-u', user, 'gnome-session']
try:
# At least in GNOME 42, there are multiple gnome-session-binary
# processes, and we only want the first one.
lines = _check_output_strip(pgrep_cmd)
return lines.split()[0]
except subprocess.CalledProcessError:
return None
def _get_phoc_session_pid(user):
pgrep_cmd = ['pgrep', '-u', user, 'phoc']
try:
return _check_output_strip(pgrep_cmd)
except subprocess.CalledProcessError:
return None
def _get_dbus_bus_address(user):
if user is None:
if environ.get('DBUS_SESSION_BUS_ADDRESS') is None:
return None
return "DBUS_SESSION_BUS_ADDRESS={}".format(
environ['DBUS_SESSION_BUS_ADDRESS'])
pid = _get_gnome_session_pid(user) or _get_phoc_session_pid(user)
if pid:
return _check_output_strip(
['grep', '-z', '^DBUS_SESSION_BUS_ADDRESS',
'/proc/{}/environ'.format(pid)]).strip('\0')
def _run_cmd_with_dbus(user, cmd, dbus_addr):
if not dbus_addr:
command = ['dbus-run-session', '--']
else:
command = ['export', dbus_addr, ';']
command.extend(cmd)
if user is None:
return _check_output_strip(['/bin/sh', '-c', " ".join(command)])
return _check_output_strip(['su', '-', user, '-c', " ".join(command)])
def _set_value(schemadir, user, setting, value, dbus_addr):
command = ['/usr/bin/gsettings']
if schemadir:
command.extend(['--schemadir', schemadir])
command.append('set')
command.extend(setting.args)
command.append(f"'{_escape_single_quotes(value)}'")
return _run_cmd_with_dbus(user, command, dbus_addr)
def _get_value(schemadir, user, setting, dbus_addr):
command = ['/usr/bin/gsettings']
if schemadir:
command.extend(['--schemadir', schemadir])
command.append('get')
command.extend(setting.args)
return _run_cmd_with_dbus(user, command, dbus_addr)
def main():
module = AnsibleModule(
argument_spec={
'state': {'choices': ['present'], 'default': 'present'},
'user': {'default': None},
'schemadir': {'required': False},
'schema': {'required': False},
'path': {'required': False},
'key': {'required': False},
'value': {'required': False},
'settings': {'type': 'dict', "required": False, 'default': dict()},
},
supports_check_mode=True,
)
user = module.params['user']
schemadir = module.params['schemadir']
schema = module.params['schema']
path = module.params['path']
key = module.params['key']
value = module.params['value']
settings = module.params['settings']
any_changed = False
unchanged_settings = list()
changed_settings = list()
if key is None and len(settings) == 0:
module.fail_json(msg="Either a key or a settings dict is required, "
"neither was provided.")
parsed_settings = []
if key is not None:
parsed_settings.append([Setting(schema, path, key), value])
for key, value in settings.items():
parsed_settings.append([Setting(schema, path, key), value])
dbus_addr = _get_dbus_bus_address(user)
for setting, value in parsed_settings:
old_value = _get_value(schemadir, user, setting, dbus_addr)
result = {'key': '.'.join(setting.args), 'value': old_value}
changed = old_value != value
any_changed = any_changed or changed
if changed and not module.check_mode:
_set_value(schemadir, user, setting, value, dbus_addr)
result['new_value'] = value
changed_settings.append(result)
else:
unchanged_settings.append(result)
module.exit_json(**{
'changed': any_changed,
'unchanged_settings': unchanged_settings,
'changed_settings': changed_settings,
})
if __name__ == '__main__':
main()