dotctl 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dotctl/dotctl.py ADDED
@@ -0,0 +1,964 @@
1
+ import os
2
+ import re
3
+ import pwd
4
+ import time
5
+ from datetime import datetime
6
+ import shutil
7
+ import getpass
8
+ import subprocess
9
+ import traceback
10
+ from random import shuffle
11
+ from zipfile import is_zipfile, ZipFile
12
+ import argparse
13
+ import pkg_resources
14
+
15
+
16
+ try:
17
+ import yaml
18
+ except ModuleNotFoundError as error:
19
+ raise ModuleNotFoundError(
20
+ "Please install the module PyYAML using pip: \n" "pip install PyYAML"
21
+ ) from error
22
+
23
+ config_dir = '.config'
24
+ share_dir = '.local/share'
25
+ root_share_dir = '/usr/share'
26
+ bin_dir = '.local/bin'
27
+ base_plasmasaver_dir = '.plasmasaver'
28
+ base_profile_dir = 'profiles'
29
+ sddm_dir = '/usr/share/sddm'
30
+ system_config_dir = '/etc'
31
+ home_path = pwd.getpwuid(os.getuid()).pw_dir
32
+ config_dir_path = os.path.join(home_path, config_dir)
33
+ share_dir_path = os.path.join(home_path, share_dir)
34
+ bin_dir_path = os.path.join(home_path, bin_dir)
35
+ base_plasmasaver_dir_path = os.path.join(home_path, base_plasmasaver_dir)
36
+ base_profile_dir_path = os.path.join(base_plasmasaver_dir_path, base_profile_dir)
37
+ plasmasaver_config_file_path = os.path.join(base_plasmasaver_dir_path, 'conf.yaml')
38
+ temp_path = os.path.join(base_plasmasaver_dir_path, 'tmp-%s' % time.time())
39
+ EXPORT_EXTENSION = ".plsv"
40
+ sudo_pass = None
41
+ skip_sudo = False
42
+
43
+ if not os.path.exists(base_profile_dir_path):
44
+ os.makedirs(base_profile_dir_path)
45
+
46
+ list_of_profiles = os.listdir(base_profile_dir_path)
47
+ length_of_lop = len(list_of_profiles)
48
+ version = pkg_resources.get_distribution('plasmasaver').version
49
+
50
+ conf_kde = {
51
+ "export": {
52
+ "home_folder": {
53
+ "entries": [
54
+ ".fonts",
55
+ ".themes",
56
+ ".icons",
57
+ ".wallpapers",
58
+ ".conky",
59
+ ".zsh",
60
+ ".bin",
61
+ "bin"
62
+ ],
63
+ "location": "$HOME/"
64
+ },
65
+ "plasma_saver": {
66
+ "entries": [
67
+ "profiles"
68
+ ],
69
+ "location": "$PLASMA_SAVER_DIR"
70
+ },
71
+ "sddm": {
72
+ "entries": [
73
+ "themes"
74
+ ],
75
+ "location": "$SDDM_DIR"
76
+ },
77
+ "root_share_folder": {
78
+ "entries": [
79
+ "plasma",
80
+ "kwin",
81
+ "konsole",
82
+ "fonts",
83
+ "kfontinst",
84
+ "color-schemes",
85
+ "aurorae",
86
+ "icons",
87
+ "wallpapers",
88
+ "Kvantum",
89
+ "themes"
90
+ ],
91
+ "location": "$ROOT_SHARE_DIR"
92
+ },
93
+ "share_folder": {
94
+ "entries": [
95
+ "plasma",
96
+ "kwin",
97
+ "konsole",
98
+ "fonts",
99
+ "kfontinst",
100
+ "color-schemes",
101
+ "aurorae",
102
+ "icons",
103
+ "wallpapers"
104
+ ],
105
+ "location": "$SHARE_DIR"
106
+ }
107
+ },
108
+ "save": {
109
+ "home_folder": {
110
+ "entries": [
111
+ ".zshrc",
112
+ ".p10k.zsh"
113
+ ],
114
+ "location": "$HOME/"
115
+ },
116
+ "app_layouts": {
117
+ "entries": [
118
+ "dolphin",
119
+ "konsole"
120
+ ],
121
+ "location": "$HOME/.local/share/kxmlgui5"
122
+ },
123
+ "configs": {
124
+ "entries": [
125
+ "gtk-2.0",
126
+ "gtk-3.0",
127
+ "gtk-4.0",
128
+ "Kvantum",
129
+ "latte",
130
+ "dolphinrc",
131
+ "konsolerc",
132
+ "kcminputrc",
133
+ "kdeglobals",
134
+ "kglobalshortcutsrc",
135
+ "klipperrc",
136
+ "krunnerrc",
137
+ "kscreenlockerrc",
138
+ "ksmserverrc",
139
+ "kwinrc",
140
+ "kwinrulesrc",
141
+ "plasma-org.kde.plasma.desktop-appletsrc",
142
+ "plasmarc",
143
+ "plasmashellrc",
144
+ "gtkrc",
145
+ "gtkrc-2.0",
146
+ "lattedockrc",
147
+ "breezerc",
148
+ "oxygenrc",
149
+ "lightlyrc",
150
+ "ksplashrc",
151
+ "khotkeysrc",
152
+ "autostart"
153
+ ],
154
+ "location": "$CONFIG_DIR"
155
+ },
156
+ "sddm_configs": {
157
+ "entries": [
158
+ "sddm.conf.d"
159
+ ],
160
+ "location": "$SYS_CONFIG_DIR"
161
+ }
162
+ }
163
+ }
164
+
165
+ conf_others = {
166
+ "save": {
167
+ "configs": {
168
+ "location": "$HOME/.config",
169
+ "entries": []
170
+ }
171
+ },
172
+ "export": {
173
+ "share_folder": {
174
+ "location": "$HOME/.local/share",
175
+ "entries": []
176
+ },
177
+ "home_folder": {
178
+ "location": "$HOME/",
179
+ "entries": []
180
+ }
181
+ }
182
+ }
183
+
184
+
185
+ def conf_initializer(env="NONE"):
186
+ if not os.path.exists(plasmasaver_config_file_path) or (env and (env != "NONE")):
187
+ if os.path.expandvars("$XDG_CURRENT_DESKTOP") == "KDE" or env.upper() == "KDE":
188
+ conf = conf_kde
189
+ with open(plasmasaver_config_file_path, 'w') as outfile:
190
+ yaml.dump(conf, outfile, default_flow_style=False)
191
+ else:
192
+ print(
193
+ f"plasmasaver: Unknown Desktop environment, please use \"-e\"/\"--env\" to specify environment with \"save\" command to initialize base config."
194
+ )
195
+ conf = conf_others
196
+ with open(plasmasaver_config_file_path, 'w') as outfile:
197
+ yaml.dump(conf, outfile, default_flow_style=False)
198
+ return plasmasaver_config_file_path
199
+
200
+
201
+ def exception_handler(func):
202
+ def inner_func(*args, **kwargs):
203
+ try:
204
+ function = func(*args, **kwargs)
205
+ except Exception as err:
206
+ dateandtime = datetime.now().strftime("[%d/%m/%Y %H:%M:%S]")
207
+ log_file = os.path.join(home_path, "plasmasaver_log.txt")
208
+
209
+ with open(log_file, "a") as file:
210
+ file.write(dateandtime + "\n")
211
+ traceback.print_exc(file=file)
212
+ file.write("\n")
213
+
214
+ print(
215
+ f"plasmasaver: {err}\nPlease check the log at {log_file} for more details."
216
+ )
217
+ return None
218
+ else:
219
+ return function
220
+
221
+ return inner_func
222
+
223
+
224
+ def ends_with(grouped_regex, path) -> str:
225
+ occurrence = re.search(grouped_regex, path).group()
226
+ dirs = os.listdir(path[0: path.find(occurrence)])
227
+ ends_with_text = re.search(grouped_regex, occurrence).group(2)
228
+ for directory in dirs:
229
+ if directory.endswith(ends_with_text):
230
+ return path.replace(occurrence, directory)
231
+ return occurrence
232
+
233
+
234
+ def begins_with(grouped_regex, path) -> str:
235
+ occurrence = re.search(grouped_regex, path).group()
236
+ dirs = os.listdir(path[0: path.find(occurrence)])
237
+ ends_with_text = re.search(grouped_regex, occurrence).group(2)
238
+ for directory in dirs:
239
+ if directory.startswith(ends_with_text):
240
+ return path.replace(occurrence, directory)
241
+ return occurrence
242
+
243
+
244
+ def parse_keywords(tokens_, token_symbol, parsed):
245
+ for item in parsed:
246
+ for name in parsed[item]:
247
+ for key, value in tokens_["keywords"]["dict"].items():
248
+ word = token_symbol + key
249
+ location = parsed[item][name]["location"]
250
+ if word in location:
251
+ parsed[item][name]["location"] = location.replace(word, value)
252
+
253
+
254
+ def parse_functions(tokens_, token_symbol, parsed):
255
+ functions = tokens_["functions"]
256
+ raw_regex = f"\\{token_symbol}{functions['raw_regex']}"
257
+ grouped_regex = f"\\{token_symbol}{functions['grouped_regex']}"
258
+
259
+ for item in parsed:
260
+ for name in parsed[item]:
261
+ location = parsed[item][name]["location"]
262
+ occurrences = re.findall(raw_regex, location)
263
+ if not occurrences:
264
+ continue
265
+ for occurrence in occurrences:
266
+ func = re.search(grouped_regex, occurrence).group(1)
267
+ if func in functions["dict"]:
268
+ parsed[item][name]["location"] = functions["dict"][func](
269
+ grouped_regex, location
270
+ )
271
+
272
+
273
+ TOKEN_SYMBOL = "$"
274
+ tokens = {
275
+ "keywords": {
276
+ "dict": {
277
+ "HOME": home_path,
278
+ "CONFIG_DIR": config_dir_path,
279
+ "SHARE_DIR": share_dir_path,
280
+ "ROOT_SHARE_DIR": root_share_dir,
281
+ "BIN_DIR": bin_dir_path,
282
+ "PLASMA_SAVER_DIR": base_plasmasaver_dir,
283
+ "SDDM_DIR": sddm_dir,
284
+ "SYS_CONFIG_DIR": system_config_dir,
285
+ }
286
+ },
287
+ "functions": {
288
+ "raw_regex": r"\{\w+\=(?:\"|')\S+(?:\"|')\}",
289
+ "grouped_regex": r"\{(\w+)\=(?:\"|')(\S+)(?:\"|')\}",
290
+ "dict": {"ENDS_WITH": ends_with, "BEGINS_WITH": begins_with},
291
+ },
292
+ }
293
+
294
+
295
+ def mkdir(path):
296
+ if not os.path.exists(path):
297
+ os.makedirs(path)
298
+ return path
299
+
300
+
301
+ def log(msg, *args, **kwargs):
302
+ print(f"PlasmaSaver: {msg.capitalize()}", *args, **kwargs)
303
+
304
+
305
+ def get_sudo_pass(file, sudo_max_attempts=3):
306
+ s_pass = None
307
+ print('Required sudo to process %s' % str(file))
308
+ print('Please select one option from list:')
309
+ print(' 1. Provide sudo Password and apply to recurrence')
310
+ print(' 2. Provide sudo Password and apply to current file')
311
+ print(' 3. Skip all')
312
+ print(' 4. Skip current file')
313
+ sudo_behaviour_status = int(input("Please provide your input [1/2/3/4]: "))
314
+ if sudo_behaviour_status == 1 or sudo_behaviour_status == 2:
315
+ s_pass = getpass.getpass("Please provide password: ")
316
+ if sudo_behaviour_status == 1:
317
+ global sudo_pass
318
+ sudo_pass = s_pass
319
+ return s_pass
320
+ elif sudo_behaviour_status == 2:
321
+ return s_pass
322
+ elif sudo_behaviour_status == 3:
323
+ global skip_sudo
324
+ skip_sudo = True
325
+ return None
326
+ elif sudo_behaviour_status == 4:
327
+ return None
328
+ else:
329
+ log('Error: bad input')
330
+ if sudo_max_attempts > 0:
331
+ log('Error: Input limit exceed')
332
+ return get_sudo_pass(file, sudo_max_attempts=sudo_max_attempts - 1)
333
+ else:
334
+ return None
335
+
336
+
337
+ @exception_handler
338
+ def copy(source, dest):
339
+ assert isinstance(source, str) and isinstance(dest, str), "Invalid path"
340
+ assert source != dest, "Source and destination can't be same"
341
+ assert os.path.exists(source), "Source path doesn't exist"
342
+
343
+ if not os.path.exists(dest):
344
+ try:
345
+ os.makedirs(dest)
346
+ except PermissionError:
347
+ command = 'mkdir -p %s' % dest
348
+ if sudo_pass:
349
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (sudo_pass, command), shell=True)
350
+ elif skip_sudo:
351
+ pass
352
+ else:
353
+ temp_pass = get_sudo_pass(dest)
354
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (temp_pass, command), shell=True)
355
+
356
+ for item in os.listdir(source):
357
+ source_path = os.path.join(source, item)
358
+ dest_path = os.path.join(dest, item)
359
+
360
+ if os.path.isdir(source_path):
361
+ copy(source_path, dest_path)
362
+ else:
363
+ if os.path.exists(dest_path):
364
+ try:
365
+ os.remove(dest_path)
366
+ except PermissionError:
367
+ command = 'rm -rf %s' % dest_path
368
+ if sudo_pass:
369
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (sudo_pass, command), shell=True)
370
+ elif skip_sudo:
371
+ pass
372
+ else:
373
+ temp_pass = get_sudo_pass(dest_path)
374
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (temp_pass, command), shell=True)
375
+
376
+ if os.path.exists(source_path):
377
+ try:
378
+ shutil.copy(source_path, dest)
379
+ except PermissionError:
380
+ command = 'cp %s %s' % (source_path, dest)
381
+ if sudo_pass:
382
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (sudo_pass, command), shell=True)
383
+ elif skip_sudo:
384
+ pass
385
+ else:
386
+ temp_pass = get_sudo_pass(dest)
387
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (temp_pass, command), shell=True)
388
+
389
+
390
+ @exception_handler
391
+ def read_plasmasaver_config(config_file=plasmasaver_config_file_path) -> dict:
392
+ with open(config_file, "r") as text:
393
+ plasmasaver = yaml.load(text.read(), Loader=yaml.SafeLoader)
394
+ parse_keywords(tokens, TOKEN_SYMBOL, plasmasaver)
395
+ parse_functions(tokens, TOKEN_SYMBOL, plasmasaver)
396
+
397
+ return plasmasaver
398
+
399
+
400
+ @exception_handler
401
+ def list_profiles(profile_list, profile_count):
402
+ # assert
403
+ assert os.path.exists(base_profile_dir_path) and profile_count != 0, "No profile found."
404
+
405
+ # run
406
+ print("Plasmasaver profiles:")
407
+ print("ID\tNAME")
408
+ for i, item in enumerate(profile_list):
409
+ print(f"{i + 1}\t{item}")
410
+
411
+
412
+ @exception_handler
413
+ def save_profile(name, profile_list, force=False, include_global=False, include_sddm=False, sddm_only=False):
414
+ # assert
415
+ assert name not in profile_list or force, "Profile with this name already exists"
416
+
417
+ # run
418
+ log("saving profile...")
419
+ profile_dir = os.path.join(base_profile_dir_path, name)
420
+ mkdir(profile_dir)
421
+ with open(plasmasaver_config_file_path, 'r') as configs:
422
+ plasmasaver_config = yaml.safe_load(configs)
423
+ if sddm_only:
424
+ plasmasaver_config['export'] = {'sddm': plasmasaver_config['export']['sddm']}
425
+ plasmasaver_config['save'] = {'sddm_configs': plasmasaver_config['save']['sddm_configs']}
426
+ else:
427
+ if not include_global:
428
+ plasmasaver_config['export'].pop('root_share_folder', None)
429
+ if not include_sddm:
430
+ plasmasaver_config['export'].pop('sddm', None)
431
+ plasmasaver_config['save'].pop('sddm_configs', None)
432
+
433
+ with open(os.path.join(profile_dir, 'conf.yaml'), 'w') as outfile:
434
+ yaml.dump(plasmasaver_config, outfile, default_flow_style=False)
435
+ plasmasaver_config = read_plasmasaver_config(os.path.join(profile_dir, 'conf.yaml'))
436
+ for section in plasmasaver_config['save']:
437
+ location = plasmasaver_config['save'][section]["location"]
438
+ folder = os.path.join(profile_dir, section)
439
+ mkdir(folder)
440
+ for entry in plasmasaver_config['save'][section]["entries"]:
441
+ source = os.path.join(location, entry)
442
+ dest = os.path.join(folder, entry)
443
+ if os.path.exists(source):
444
+ if os.path.isdir(source):
445
+ copy(source, dest)
446
+ else:
447
+ shutil.copy(source, dest)
448
+
449
+ log("Profile saved successfully!")
450
+
451
+
452
+ @exception_handler
453
+ def apply_profile(profile_name, profile_list, profile_count, skip_sddm=False, skip_global=False, sddm_only=False):
454
+ # assert
455
+ assert profile_count != 0, "No profile saved yet."
456
+ assert profile_name in profile_list, "Profile not found :("
457
+
458
+ # run
459
+ profile_dir = os.path.join(base_profile_dir_path, profile_name)
460
+
461
+ log("copying files...")
462
+
463
+ config_location = os.path.join(profile_dir, "conf.yaml")
464
+ profile_config = read_plasmasaver_config(config_location)
465
+ if sddm_only:
466
+ profile_config['export'] = {'sddm': profile_config['export']['sddm']}
467
+ profile_config['save'] = {'sddm_configs': profile_config['save']['sddm_configs']}
468
+ else:
469
+ if skip_global:
470
+ profile_config['export'].pop('root_share_folder', None)
471
+ if skip_sddm:
472
+ profile_config['export'].pop('sddm', None)
473
+ profile_config['save'].pop('sddm_configs', None)
474
+ for name in profile_config["save"]:
475
+ location = os.path.join(profile_dir, name)
476
+ copy(location, profile_config["save"][name]["location"])
477
+
478
+ log(
479
+ "Profile applied successfully! Please log-out and log-in to see the changes completely!"
480
+ )
481
+
482
+
483
+ @exception_handler
484
+ def remove_profile(profile_name, profile_list, profile_count):
485
+ # assert
486
+ assert profile_count != 0, "No profile saved yet."
487
+ assert profile_name in profile_list, "Profile not found."
488
+
489
+ # run
490
+ log("removing profile...")
491
+ shutil.rmtree(os.path.join(base_profile_dir_path, profile_name))
492
+ log("removed profile successfully")
493
+
494
+
495
+ @exception_handler
496
+ def export(profile_name, profile_list, profile_count, skip_global=False, skip_sddm=False, sddm_only=False,
497
+ config_only=False, data_only=False):
498
+ # assert
499
+ assert profile_count != 0, "No profile saved yet."
500
+ assert profile_name in profile_list, "Profile not found."
501
+
502
+ # run
503
+ profile_dir = os.path.join(base_profile_dir_path, profile_name)
504
+ export_path = os.path.join(home_path, profile_name)
505
+
506
+ if os.path.exists(export_path):
507
+ rand_str = list("abcdefg12345")
508
+ shuffle(rand_str)
509
+ export_path = export_path + "".join(rand_str)
510
+ mkdir(export_path)
511
+
512
+ # compressing the files as zip
513
+ log("Exporting profile. It might take a minute or two...")
514
+
515
+ profile_config_file = os.path.join(profile_dir, "conf.yaml")
516
+ with open(profile_config_file, 'r') as configs:
517
+ plasmasaver_config = yaml.safe_load(configs)
518
+
519
+ if skip_global:
520
+ plasmasaver_config['export'].pop('root_share_folder', None)
521
+ if data_only:
522
+ plasmasaver_config.pop('save', None)
523
+ if config_only:
524
+ plasmasaver_config.pop('export', None)
525
+ if skip_sddm:
526
+ plasmasaver_config['export'].pop('sddm', None)
527
+ plasmasaver_config['save'].pop('sddm_configs', None)
528
+ if sddm_only:
529
+ plasmasaver_config['export'] = {'sddm': plasmasaver_config['export']['sddm']}
530
+ plasmasaver_config['save'] = {'sddm_configs': plasmasaver_config['save']['sddm_configs']}
531
+
532
+ with open(os.path.join(export_path, "conf.yaml"), 'w') as outfile:
533
+ yaml.dump(plasmasaver_config, outfile, default_flow_style=False)
534
+
535
+ plasmasaver_config = read_plasmasaver_config(os.path.join(export_path, "conf.yaml"))
536
+
537
+ export_path_save = mkdir(os.path.join(export_path, "save"))
538
+ for name in plasmasaver_config["save"]:
539
+ location = os.path.join(profile_dir, name)
540
+ log(f'Exporting "{name}"...')
541
+ copy(location, os.path.join(export_path_save, name))
542
+
543
+ plasmasaver_config_export = plasmasaver_config["export"]
544
+ export_path_export = mkdir(os.path.join(export_path, "export"))
545
+ for name in plasmasaver_config_export:
546
+ location = plasmasaver_config_export[name]["location"]
547
+ path = mkdir(os.path.join(export_path_export, name))
548
+ for entry in plasmasaver_config_export[name]["entries"]:
549
+ source = os.path.join(location, entry)
550
+ dest = os.path.join(path, entry)
551
+ log(f'Exporting "{name}/{entry}"...')
552
+ if os.path.exists(source):
553
+ if os.path.isdir(source):
554
+ copy(source, dest)
555
+ else:
556
+ shutil.copy(source, dest)
557
+
558
+ log("Creating archive")
559
+ shutil.make_archive(export_path, "zip", export_path)
560
+
561
+ shutil.rmtree(export_path)
562
+ shutil.move(export_path + ".zip", export_path + EXPORT_EXTENSION)
563
+
564
+ log(f"Successfully exported to {export_path}{EXPORT_EXTENSION}")
565
+
566
+
567
+ @exception_handler
568
+ def import_profile(path, skip_global=False, skip_sddm=False, sddm_only=False, config_only=False, data_only=False):
569
+ # assert
570
+ assert (
571
+ is_zipfile(path) and path[-5:] == EXPORT_EXTENSION
572
+ ), "Not a valid plasmasaver file"
573
+ item = os.path.basename(path)[:-5]
574
+ assert not os.path.exists(
575
+ os.path.join(base_profile_dir_path, item)
576
+ ), "A profile with this name already exists"
577
+
578
+ # run
579
+ log("Importing profile. It might take a minute or two...")
580
+
581
+ item = os.path.basename(path).replace(EXPORT_EXTENSION, "")
582
+
583
+ with ZipFile(path, "r") as zip_file:
584
+ zip_file.extractall(temp_path)
585
+
586
+ config_file_location = os.path.join(temp_path, "conf.yaml")
587
+ plasmasaver_config = read_plasmasaver_config(config_file_location)
588
+
589
+ if skip_global:
590
+ plasmasaver_config['export'].pop('root_share_folder', None)
591
+ if data_only:
592
+ plasmasaver_config.pop('save', None)
593
+ if config_only:
594
+ plasmasaver_config.pop('export', None)
595
+ if skip_sddm:
596
+ plasmasaver_config['export'].pop('sddm', None)
597
+ plasmasaver_config['save'].pop('sddm_configs', None)
598
+ if sddm_only:
599
+ plasmasaver_config['export'] = {'sddm': plasmasaver_config['export']['sddm']}
600
+ plasmasaver_config['save'] = {'sddm_configs': plasmasaver_config['save']['sddm_configs']}
601
+
602
+ profile_dir = os.path.join(base_profile_dir_path, item)
603
+ copy(os.path.join(temp_path, "save"), profile_dir)
604
+ shutil.copy(os.path.join(temp_path, "conf.yaml"), profile_dir)
605
+
606
+ for section in plasmasaver_config["export"]:
607
+ location = plasmasaver_config["export"][section]["location"]
608
+ path = os.path.join(temp_path, "export", section)
609
+ mkdir(path)
610
+ for entry in plasmasaver_config["export"][section]["entries"]:
611
+ source = os.path.join(path, entry)
612
+ dest = os.path.join(location, entry)
613
+ log(f'Importing "{section}/{entry}"...')
614
+ if os.path.exists(source):
615
+ if os.path.isdir(source):
616
+ copy(source, dest)
617
+ else:
618
+ try:
619
+ shutil.copy(source, dest)
620
+ except PermissionError:
621
+ command = 'cp %s %s' % (source, dest)
622
+ if sudo_pass:
623
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (sudo_pass, command), shell=True)
624
+ elif skip_sudo:
625
+ pass
626
+ else:
627
+ temp_pass = get_sudo_pass(dest)
628
+ subprocess.check_output('echo %s|sudo -S %s; echo $? ' % (temp_pass, command), shell=True)
629
+
630
+ shutil.rmtree(temp_path)
631
+
632
+ log("Profile successfully imported!")
633
+
634
+
635
+ @exception_handler
636
+ def wipe():
637
+ """Wipes all profiles."""
638
+ confirm = input('This will wipe all your profiles. Enter "WIPE" Tto continue: ')
639
+ if confirm == "WIPE":
640
+ shutil.rmtree(base_profile_dir_path)
641
+ log("Removed all profiles!")
642
+ else:
643
+ log("Aborting...")
644
+
645
+
646
+ def _get_parser() -> argparse.ArgumentParser:
647
+ parser = argparse.ArgumentParser(
648
+ prog="plasmasaver",
649
+ epilog="Please report bugs at pankajackson@live.co.uk",
650
+ )
651
+
652
+ parser.add_argument(
653
+ "-v", "--version", required=False, action="store_true", help="Show version"
654
+ )
655
+
656
+ subparsers = parser.add_subparsers(help='Desired action to perform', dest='action')
657
+ save_parser = subparsers.add_parser("save", help="Save current config as a profile")
658
+ remove_parser = subparsers.add_parser("remove", help="Remove the specified profile")
659
+ list_parser = subparsers.add_parser("list", help="Lists created profiles")
660
+ apply_parser = subparsers.add_parser("apply", help="Apply the specified profile")
661
+ import_parser = subparsers.add_parser("import", help="Import a plasmasaver file")
662
+ export_parser = subparsers.add_parser("export", help="Export a profile and share with your friends!")
663
+ wipe_parser = subparsers.add_parser("wipe", help="Wipes all profiles.")
664
+
665
+ save_parser.add_argument(
666
+ "profile_name",
667
+ type=str,
668
+ help="Name of the profile as a identifier"
669
+ )
670
+ save_parser.add_argument(
671
+ "-f",
672
+ "--force",
673
+ required=False,
674
+ action="store_true",
675
+ help="Overwrite already saved profiles",
676
+ )
677
+ save_parser.add_argument(
678
+ "-c",
679
+ "--config-file",
680
+ required=False,
681
+ type=str,
682
+ help="Use external config file",
683
+ metavar="<path>",
684
+ )
685
+ save_parser.add_argument(
686
+ "-e",
687
+ "--env",
688
+ required=False,
689
+ type=str,
690
+ help="Desktop environment (e.g. kde)",
691
+ metavar="<env>",
692
+ )
693
+ save_parser.add_argument(
694
+ "-p",
695
+ "--password",
696
+ required=False,
697
+ type=str,
698
+ help="Sudo Password to authorize restricted data (e.g. /usr/share)",
699
+ metavar="<password>",
700
+ )
701
+ save_parser.add_argument(
702
+ "--include-global",
703
+ required=False,
704
+ action="store_true",
705
+ help="Include data from global data directory (/usr/share)",
706
+ )
707
+ save_parser.add_argument(
708
+ "--include-sddm",
709
+ required=False,
710
+ action="store_true",
711
+ help="Include sddm data/configs directory (/usr/share/sddm, /etc/sddm.conf.d)",
712
+ )
713
+ save_parser.add_argument(
714
+ "--sddm-only",
715
+ required=False,
716
+ action="store_true",
717
+ help="Perform operation only on sddm data/configurations (Note: sudo password required)",
718
+ )
719
+ save_parser.add_argument(
720
+ "--skip-sudo",
721
+ required=False,
722
+ action="store_true",
723
+ help="Skip all sudo operations",
724
+ )
725
+ remove_parser.add_argument(
726
+ "profile_name",
727
+ type=str,
728
+ help="Name of the profile as a identifier"
729
+ )
730
+ apply_parser.add_argument(
731
+ "profile_name",
732
+ type=str,
733
+ help="Name of the profile as a identifier"
734
+ )
735
+ apply_parser.add_argument(
736
+ "-p",
737
+ "--password",
738
+ required=False,
739
+ type=str,
740
+ help="Sudo Password to authorize restricted data (e.g. /usr/share)",
741
+ metavar="<password>",
742
+ )
743
+ apply_parser.add_argument(
744
+ "--sddm-only",
745
+ required=False,
746
+ action="store_true",
747
+ help="Perform operation only on sddm data/configurations (Note: sudo password required)",
748
+ )
749
+ apply_parser.add_argument(
750
+ "--skip-global",
751
+ required=False,
752
+ action="store_true",
753
+ help="Skip data from global data directory (/usr/share)",
754
+ )
755
+ apply_parser.add_argument(
756
+ "--skip-sddm",
757
+ required=False,
758
+ action="store_true",
759
+ help="Skip sddm data/configs directory (/usr/share/sddm, /etc/sddm.conf.d)",
760
+ )
761
+ apply_parser.add_argument(
762
+ "--skip-sudo",
763
+ required=False,
764
+ action="store_true",
765
+ help="Skip all sudo operations",
766
+ )
767
+ export_parser.add_argument(
768
+ "profile_name",
769
+ type=str,
770
+ help="Name of the profile as a identifier"
771
+ )
772
+ export_parser.add_argument(
773
+ "-p",
774
+ "--password",
775
+ required=False,
776
+ type=str,
777
+ help="Sudo Password to authorize restricted data (e.g. /usr/share)",
778
+ metavar="<password>",
779
+ )
780
+ export_parser.add_argument(
781
+ "--config-only",
782
+ required=False,
783
+ action="store_true",
784
+ help="Perform operation only on plasma configs (skip data, e.g. ~/.config)",
785
+ )
786
+ export_parser.add_argument(
787
+ "--data-only",
788
+ required=False,
789
+ action="store_true",
790
+ help="Perform operation only on plasma data (skip configs, e.g. ~/.local/share)",
791
+ )
792
+ export_parser.add_argument(
793
+ "--sddm-only",
794
+ required=False,
795
+ action="store_true",
796
+ help="Perform operation only on sddm data/configurations (Note: sudo password required)",
797
+ )
798
+ export_parser.add_argument(
799
+ "--skip-global",
800
+ required=False,
801
+ action="store_true",
802
+ help="Skip data from global data directory (/usr/share)",
803
+ )
804
+ export_parser.add_argument(
805
+ "--skip-sddm",
806
+ required=False,
807
+ action="store_true",
808
+ help="Skip sddm data/configs directory (/usr/share/sddm, /etc/sddm.conf.d)",
809
+ )
810
+ export_parser.add_argument(
811
+ "--skip-sudo",
812
+ required=False,
813
+ action="store_true",
814
+ help="Skip all sudo operations",
815
+ )
816
+ import_parser.add_argument(
817
+ "profile_name",
818
+ type=str,
819
+ help="Name of the profile as a identifier"
820
+ )
821
+ import_parser.add_argument(
822
+ "-p",
823
+ "--password",
824
+ required=False,
825
+ type=str,
826
+ help="Sudo Password to authorize restricted data (e.g. /usr/share)",
827
+ metavar="<password>",
828
+ )
829
+ import_parser.add_argument(
830
+ "--config-only",
831
+ required=False,
832
+ action="store_true",
833
+ help="Perform operation only on plasma configs (skip data, e.g. ~/.config)",
834
+ )
835
+ import_parser.add_argument(
836
+ "--data-only",
837
+ required=False,
838
+ action="store_true",
839
+ help="Perform operation only on plasma data (skip configs, e.g. ~/.local/share)",
840
+ )
841
+ import_parser.add_argument(
842
+ "--sddm-only",
843
+ required=False,
844
+ action="store_true",
845
+ help="Perform operation only on sddm data/configurations (Note: sudo password required)",
846
+ )
847
+ import_parser.add_argument(
848
+ "--skip-global",
849
+ required=False,
850
+ action="store_true",
851
+ help="Skip data from global data directory (/usr/share)",
852
+ )
853
+ import_parser.add_argument(
854
+ "--skip-sddm",
855
+ required=False,
856
+ action="store_true",
857
+ help="Skip sddm data/configs directory (/usr/share/sddm, /etc/sddm.conf.d)",
858
+ )
859
+ import_parser.add_argument(
860
+ "--skip-sudo",
861
+ required=False,
862
+ action="store_true",
863
+ help="Skip all sudo operations",
864
+ )
865
+
866
+ return parser
867
+
868
+
869
+ @exception_handler
870
+ def main():
871
+ """The main function that handles all the arguments and options."""
872
+
873
+ parser = _get_parser()
874
+ args = parser.parse_args()
875
+ global skip_sudo
876
+ skip_sudo = False
877
+ global sudo_pass
878
+ sudo_pass = None
879
+ conf_initializer()
880
+
881
+ if args.action == 'save':
882
+ if args.password and args.skip_sudo:
883
+ raise Exception('error: -p/--password and --skip-sudo can\'t be used at the same time')
884
+ elif args.skip_sudo:
885
+ skip_sudo = True
886
+ elif args.password:
887
+ sudo_pass = args.password
888
+ if (args.sddm_only and args.include_sddm) or (args.sddm_only and args.include_global):
889
+ raise Exception('error: --sddm-only can\'t be used with --include-sddm and --include-global')
890
+ if args.env:
891
+ conf_initializer(args.env)
892
+ if args.config_file:
893
+ if not os.path.exists(args.config_file):
894
+ raise Exception(
895
+ 'error: invalid config file path, The path given in arg doesn\'t exist or is not accessible: %s' % args.config_file)
896
+ with open(args.config_file, 'r') as configs:
897
+ e_conf = yaml.safe_load(configs)
898
+ if 'export' not in e_conf.keys() or 'save' not in e_conf.keys():
899
+ raise Exception(
900
+ 'error: missing config block(s), "save" and "export" are core blocks of plasmasaver configuration')
901
+ if e_conf:
902
+ global plasmasaver_config_file_path
903
+ plasmasaver_config_file_path = args.config_file
904
+ save_profile(args.profile_name, list_of_profiles, force=args.force, include_sddm=args.include_sddm,
905
+ include_global=args.include_global, sddm_only=args.sddm_only)
906
+ elif args.action == 'remove':
907
+ remove_profile(args.profile_name, list_of_profiles, length_of_lop)
908
+
909
+ elif args.action == 'list':
910
+ list_profiles(list_of_profiles, length_of_lop)
911
+
912
+ elif args.action == 'apply':
913
+ if args.password and args.skip_sudo:
914
+ raise Exception('error: -p/--password and --skip-sudo can\'t be used at the same time')
915
+ elif args.skip_sudo:
916
+ skip_sudo = True
917
+ elif args.password:
918
+ sudo_pass = args.password
919
+ if (args.sddm_only and args.skip_sddm) or (args.sddm_only and args.skip_global):
920
+ raise Exception('error: --sddm-only can\'t be used with --include-sddm and --include-global')
921
+ apply_profile(args.profile_name, list_of_profiles, length_of_lop, skip_sddm=args.skip_sddm,
922
+ skip_global=args.skip_global, sddm_only=args.sddm_only)
923
+
924
+ elif args.action == 'import':
925
+ if args.password and args.skip_sudo:
926
+ raise Exception('error: -p/--password and --skip-sudo can\'t be used at the same time')
927
+ elif args.skip_sudo:
928
+ skip_sudo = True
929
+ elif args.password:
930
+ sudo_pass = args.password
931
+ if (args.sddm_only and args.skip_sddm) or (args.sddm_only and args.skip_global):
932
+ raise Exception('error: --sddm-only can\'t be used with --include-sddm and --include-global')
933
+ if args.data_only and args.config_only:
934
+ raise Exception('error: --data-only and --config-only can\'t be used at the same time')
935
+ import_profile(args.profile_name, skip_global=args.skip_global, skip_sddm=args.skip_sddm,
936
+ sddm_only=args.sddm_only, config_only=args.config_only, data_only=args.data_only)
937
+
938
+ elif args.action == 'export':
939
+ if args.password and args.skip_sudo:
940
+ raise Exception('error: -p/--password and --skip-sudo can\'t be used at the same time')
941
+ elif args.skip_sudo:
942
+ skip_sudo = True
943
+ elif args.password:
944
+ sudo_pass = args.password
945
+ if (args.sddm_only and args.skip_sddm) or (args.sddm_only and args.skip_global):
946
+ raise Exception('error: --sddm-only can\'t be used with --include-sddm and --include-global')
947
+ if args.data_only and args.config_only:
948
+ raise Exception('error: --data-only and --config-only can\'t be used at the same time')
949
+ export(args.profile_name, list_of_profiles, length_of_lop, skip_global=args.skip_global,
950
+ skip_sddm=args.skip_sddm, sddm_only=args.sddm_only, config_only=args.config_only,
951
+ data_only=args.data_only)
952
+
953
+ elif args.version:
954
+ print(f"plasmasaver: {version}")
955
+
956
+ elif args.action == 'wipe':
957
+ wipe()
958
+
959
+ else:
960
+ parser.print_help()
961
+
962
+
963
+ if __name__ == "__main__":
964
+ main()