-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswitch-theme.py
executable file
·349 lines (256 loc) · 9.49 KB
/
switch-theme.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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
#!/bin/python3
import argparse
import pprint
import re
import shutil
import subprocess
import tomllib
from os import getenv, makedirs
from os.path import expanduser, isdir
from tempfile import mkstemp
"""Script to switch themes for different applications at once
The data structures are split into Themes and App.
A Theme stores the data: the used theme for each application
An App stores the action: what must be done to change the theme for this application.
"""
def print_error(*args):
print("{}error:{}".format("\033[1;91m", "\033[0m"), *args)
def sed(pattern, replace, file, count=0):
"""Replace certain pattern in a file.
In each line, replaces 'pattern' with 'replace'.
Args:
pattern (str): the pattern to match (can be re.pattern)
replace (str): the replacement string
file (str): the path to file
count (int): the number of occurrences to replace
"""
num_replaced = count
source_fd = open(file, "r")
_, temp = mkstemp()
dest_fd = open(temp, "w")
for line in source_fd:
new_line = re.sub(pattern, replace, line)
dest_fd.write(new_line)
if new_line != line:
num_replaced += 1
if count and num_replaced > count:
break
dest_fd.writelines(source_fd.readlines())
source_fd.close()
dest_fd.close()
shutil.move(temp, file)
def write(text, file):
"""Write text into a file.
If the file exists, it will be overwritten.
Args:
text (str): the text to write into the file
file (str): the path to file
"""
_, temp = mkstemp()
fd = open(temp, "w")
fd.write(text)
fd.close()
shutil.move(temp, file)
def set_state(app, theme):
"""Write the theme into the state file of the app.
Write the theme into the file "state_dir/app".
If the file exists, it will be overwritten.
Args:
app (str): the application name
theme (str): the theme to switch to
Returns True if state could be written successfully, otherwise False.
"""
home_dir = getenv("HOME")
if not home_dir:
print_error("couldn't determine home directory from $HOME. Aborting...")
return False
xdg_state_home = getenv("XDG_STATE_HOME", home_dir + "/.local/state")
state_dir = xdg_state_home + "/switch-theme"
if not isdir(state_dir):
makedirs(state_dir)
write(theme, state_dir + "/" + app)
return True
def switch_app_theme(app, theme, strategy, verbose=0, suppress_errors=False):
"""Switch the theme of an application.
Args:
app (str): the application name
theme (str): the theme to switch to
strategy (dict): the strategy how to change the theme
verbose (int): the verbosity level with 0 for no messages
suppress_errors (bool): supress error messages
"""
ret = 0
if "file" in strategy and "pattern" in strategy and "replace" in strategy:
file = expanduser(strategy["file"])
pattern = strategy["pattern"]
replace = strategy["replace"].format(theme)
if verbose >= 3:
print(" file: {}".format(file))
print(' pattern: "{}"'.format(pattern))
print(' replace: "{}"'.format(replace))
try:
sed(pattern, replace, file)
except FileNotFoundError:
if not suppress_errors:
print_error(
"couldn't set {} to {}: {} not found".format(app, theme, file)
)
ret = 1
if "command" in strategy:
command = strategy["command"].split(" ") + [theme]
error = False
try:
ps = subprocess.run(command)
if ps.returncode:
error = True
except FileNotFoundError:
error = True
if error and not suppress_errors:
print_error("couldn't successfully run: {}".format(command))
ret = 1
return ret
def switch_theme(apps, themes, verbose=0):
"""Switch the theme to input_theme.
Args:
apps (dict): the applications
themes (dict): the themes
verbose (int): the verbosity level with 0 for no messages
"""
ret = 0
if verbose >= 4:
print("used apps configuration:")
pprint.pprint(apps)
print("used themes configuration:")
pprint.pprint(themes)
for app in themes:
if verbose >= 2:
print("setting {} to {}...".format(app, themes[app]))
if not set_state(app, themes[app]):
return 1
if app in apps:
ret += switch_app_theme(app, themes[app], apps[app], verbose)
return 1 if ret > 0 else 0
def validate_config(config, verbose=0):
"""Validate if config only includes the categories as first level fields
and all fields of aliases point to an available theme.
Args:
config (dict): the config
verbose (int): the verbosity level with 0 for no messages
"""
categories = ["aliases", "apps", "themes"]
ret = True
for key in categories:
if key not in config.keys():
if verbose >= 1:
print('config invalid: "{}" not found'.format(key))
ret = False
for key in config.keys():
if not key in categories:
if verbose >= 1:
print('config invalid: unknown field "{}"'.format(key))
ret = False
if "aliases" in config.keys() and "themes" in config.keys():
for alias in config["aliases"].keys():
theme = config["aliases"][alias]
if not theme in config["themes"]:
if verbose >= 1:
print(
'config invalid: unknown theme "{}" provided by alias "{}"'.format(
theme, alias
)
)
ret = False
return ret
def validate_theme_config(config, apps, verbose=0):
"""Validate if each theme covers each application
Args:
config (dict): the config
apps (dict): the applications
verbose (int): the verbosity level with 0 for no messages
"""
ret = True
for key in apps.keys():
if not key in config.keys():
if verbose >= 1:
print('config invalid: theme for "{}" not found'.format(key))
ret = False
return ret
def get_theme_config(config, theme, verbose=0):
"""Return the theme from config as a dict.
If a field is not set, the value of the fallback theme will be taken. This behavior is not transitive.
Args:
config (dict): the config
theme: the theme name
verbose (int): the verbosity level with 0 for no messages
"""
theme_config = config["themes"][theme]
if "fallback" in theme_config.keys():
fallback_config = config["themes"][theme_config["fallback"]]
for key, value in fallback_config.items():
if not key in theme_config:
theme_config[key] = value
del theme_config["fallback"]
return theme_config
class ListChoicesHelpFormatter(argparse.HelpFormatter):
def _metavar_formatter(self, action, default_metavar):
if action.metavar is not None:
result = action.metavar
elif action.choices is not None:
choice_strs = [str(choice) for choice in action.choices]
result = '%s' % '\n '.join(choice_strs)
else:
result = default_metavar
def format(tuple_size):
if isinstance(result, tuple):
return result
else:
return (result, ) * tuple_size
return format
def main():
prog = __file__.split("/")[-1]
parser = argparse.ArgumentParser(
prog=prog,
usage="%(prog)s [options] [theme]",
description="Set the themes for generic applications and frameworks.",
formatter_class=ListChoicesHelpFormatter,
)
parser.add_argument(
"-v", "--verbose",
action="count",
default=0,
help="increase verbosity, multiple -v options increase the verbosity",
)
config = expanduser("~/.config/switch-theme/switch-theme.toml")
with open(config, "rb") as file:
config = tomllib.load(file)
# Set verbose to 1 since the arguments cannot be parsed at this point
if not validate_config(config, verbose=1):
print_error("invalid config: missing fields")
exit(1)
themes = list(config["aliases"])
[themes.append(x) for x in list(config["themes"]) if x not in themes]
themes.sort()
# This will overwrite an undocumented private API, which might break in the future
parser._positionals.title = 'themes'
parser.add_argument("theme", choices=themes)
try:
args = parser.parse_args()
except argparse.ArgumentTypeError as e:
parser.print_help()
exit(9)
if args.verbose >= 5:
print("parsed config:")
pprint.pprint(config)
theme = args.theme
if theme in config["aliases"]:
theme = config["aliases"][theme]
theme_config = get_theme_config(config, theme, args.verbose)
if not validate_theme_config(theme_config, config["apps"], verbose=args.verbose):
print_error('invalid config: missing fields for theme "{}"'.format(theme))
exit(1)
if args.verbose >= 1:
print("switching to {}...".format(theme))
ret = switch_theme(config["apps"], theme_config, verbose=args.verbose)
exit(ret)
if __name__ == "__main__":
main()