-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathcfg_yaml.py
1892 lines (1680 loc) · 68.1 KB
/
cfg_yaml.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
author: deadc0de6 (/~https://github.com/deadc0de6)
Copyright (c) 2019, deadc0de6
handle lower level of the config file
will provide the following dictionaries to
the upper layer:
* self.settings
* self.dotfiles
* self.profiles
* self.actions
* self.trans_install
* self.trans_update
* self.variables
Additionally a few methods are exported.
"""
# pylint: disable=C0302
import os
import glob
import io
from copy import deepcopy
from itertools import chain
from ruamel.yaml import YAML as yaml
try:
import tomllib
except ImportError:
import tomli as tomllib
import tomli_w
# local imports
from dotdrop.version import __version__ as VERSION
from dotdrop.settings import Settings
from dotdrop.logger import Logger
from dotdrop.templategen import Templategen
from dotdrop.linktypes import LinkTypes
from dotdrop.utils import shellrun, uniq_list, userinput
from dotdrop.exceptions import YamlException, UndefinedException
class CfgYaml:
"""yaml config file parser"""
# global entries
key_settings = Settings.key_yaml
key_dotfiles = 'dotfiles'
key_profiles = 'profiles'
key_actions = 'actions'
old_key_trans = 'trans'
old_key_trans_r = 'trans_read'
old_key_trans_w = 'trans_write'
key_trans_install = 'trans_install'
key_trans_update = 'trans_update'
key_variables = 'variables'
key_dvariables = 'dynvariables'
key_uvariables = 'uservariables'
action_pre = 'pre'
action_post = 'post'
save_uservariables_name = 'uservariables{}.yaml'
# profiles/dotfiles entries
key_dotfile_src = 'src'
key_dotfile_dst = 'dst'
key_dotfile_link = 'link'
key_dotfile_actions = 'actions'
key_dotfile_noempty = 'ignoreempty'
key_dotfile_template = 'template'
key_dotfile_chmod = 'chmod'
# chmod value
chmod_ignore = 'preserve'
# profile
key_profile_dotfiles = 'dotfiles'
key_profile_include = 'include'
key_profile_variables = 'variables'
key_profile_dvariables = 'dynvariables'
key_profile_actions = 'actions'
key_all = 'ALL'
# import entries
key_import_actions = 'import_actions'
key_import_configs = 'import_configs'
key_import_variables = 'import_variables'
key_import_profile_dfs = 'import'
key_import_sep = ':'
key_import_ignore_key = 'optional'
key_import_fatal_not_found = True
# settings
key_settings_dotpath = Settings.key_dotpath
key_settings_workdir = Settings.key_workdir
key_settings_link_dotfile_default = Settings.key_link_dotfile_default
key_settings_noempty = Settings.key_ignoreempty
key_settings_minversion = Settings.key_minversion
key_imp_link = Settings.key_link_on_import
key_settings_template = Settings.key_template_dotfile_default
# link values
lnk_nolink = LinkTypes.NOLINK.name.lower()
lnk_link = LinkTypes.LINK.name.lower()
lnk_children = LinkTypes.LINK_CHILDREN.name.lower()
lnk_absolute = LinkTypes.ABSOLUTE.name.lower()
lnk_relative = LinkTypes.RELATIVE.name.lower()
# checks
allowed_link_val = [lnk_nolink, lnk_link, lnk_children,
lnk_absolute, lnk_relative]
top_entries = [key_dotfiles, key_settings, key_profiles]
def __init__(self, path, profile=None, addprofiles=None,
reloading=False, debug=False, imported_configs=None,
fail_on_error=True):
"""
config parser
@path: config file path
@profile: the selected profile names
@addprofiles: included profiles names (list)
@reloading: true when reloading
@imported_configs: paths of config files that have been imported so far
@debug: debug flag
"""
self._path = os.path.abspath(path)
self._profile = profile
self._reloading = reloading
self._debug = debug
self._log = Logger(debug=self._debug)
# config format
self._config_format = 'yaml'
# config needs to be written
self._dirty = False
# indicates the config has been updated
self._dirty_deprecated = False
# profile variables
self._profilevarskeys = []
# included profiles
self._inc_profiles = addprofiles or []
# imported configs
self.imported_configs = imported_configs or []
# init the dictionaries
self.settings = {}
self.dotfiles = {}
self.profiles = {}
self.actions = {}
self.trans_install = {}
self.trans_update = {}
self.variables = {}
if not os.path.exists(self._path):
err = f'invalid config path: \"{path}\"'
if self._debug:
self._dbg(err)
raise YamlException(err)
self._dbg('START of config parsing')
self._dbg(f'reloading: {reloading}')
self._dbg(f'profile: {profile}')
pfs = ','.join(self._inc_profiles)
self._dbg(f'included profiles: {pfs}')
self._yaml_dict = self._load_yaml(self._path)
# live patch deprecated entries
self._fix_deprecated(self._yaml_dict)
# validate content
self._validate(self._yaml_dict, fail_on_error)
##################################################
# parse the config and variables
##################################################
# parse the "config" block
self.settings = self._parse_blk_settings(self._yaml_dict)
# base templater (when no vars/dvars exist)
self.variables = self._enrich_vars(self.variables, self._profile)
self._redefine_templater()
# variables and dynvariables need to be first merged
# before being templated in order to allow cyclic
# references between them
# parse the "variables" block
var = self._parse_blk_variables(self._yaml_dict)
self._add_variables(var, template=False)
# parse the "dynvariables" block
dvariables = self._parse_blk_dynvariables(self._yaml_dict)
self._add_variables(dvariables, template=False)
# now template variables and dynvariables from the same pool
self.variables = self._rec_resolve_variables(self.variables)
# and execute dvariables
# since this is done after recursively resolving variables
# and dynvariables this means that variables referencing
# dynvariables will result with the not executed value
if dvariables.keys():
self._shell_exec_dvars(self.variables, keys=dvariables.keys())
# finally redefine the template
self._redefine_templater()
if self._debug:
title = 'current variables defined'
self._debug_dict(title, self.variables)
# parse the "profiles" block
self.profiles = self._parse_blk_profiles(self._yaml_dict)
# include the profile's variables/dynvariables last
# as it overwrites existing ones
incpro, pvar, pdvar = self._get_profile_included_vars()
self._inc_profiles = uniq_list(self._inc_profiles + incpro)
self._add_variables(pvar, prio=True)
self._add_variables(pdvar, shell=True, prio=True)
self._profilevarskeys.extend(pvar.keys())
self._profilevarskeys.extend(pdvar.keys())
# template variables
self.variables = self._template_dict(self.variables)
if self._debug:
title = 'variables defined (after template dict)'
self._debug_dict(title, self.variables)
##################################################
# template the "include" entries
##################################################
self._template_include_entry()
if self._debug:
title = 'variables defined (after template include)'
self._debug_dict(title, self.variables)
##################################################
# template config entries
##################################################
entry = self.settings[self.key_settings_dotpath]
val = self._template_item(entry)
self.settings[self.key_settings_dotpath] = val
##################################################
# parse the other blocks
##################################################
# parse the "dotfiles" block
self.dotfiles = self._parse_blk_dotfiles(self._yaml_dict)
# parse the "actions" block
self.actions = self._parse_blk_actions(self._yaml_dict)
# parse the "trans_install" block
self.trans_install = self._parse_blk_trans_install(self._yaml_dict)
# parse the "trans_update" block
self.trans_update = self._parse_blk_trans_update(self._yaml_dict)
##################################################
# import elements
##################################################
# process imported variables (import_variables)
newvars = self._import_variables()
self._clear_profile_vars(newvars)
self._add_variables(newvars, prio=True)
# process imported actions (import_actions)
self._import_actions()
# process imported profile dotfiles (import)
self._import_profiles_dotfiles()
# process imported configs (import_configs)
self._import_configs()
# process profile include items (actions, dotfiles, ...)
self._resolve_profile_includes()
# add the current profile variables
_, pvar, pdvar = self._get_profile_included_vars()
self._add_variables(pvar, prio=False)
self._add_variables(pdvar, shell=True, prio=False)
self._profilevarskeys.extend(pvar.keys())
self._profilevarskeys.extend(pdvar.keys())
# resolve variables
self._clear_profile_vars(newvars)
self._add_variables(newvars)
# process profile ALL
self._resolve_profile_all()
# template dotfiles entries
self._template_dotfiles_entries()
# parse the "uservariables" block
uvariables = self._parse_blk_uservariables(self._yaml_dict,
self.variables)
self._add_variables(uvariables, template=False, prio=False)
# end of parsing
if self._debug:
self._dbg('########### final config ###########')
self._debug_entries()
self._dbg('END of config parsing')
########################################################
# public methods
########################################################
def _resolve_dotfile_link(self, link):
"""resolve dotfile link entry"""
newlink = self._template_item(link)
# check link value
if newlink not in self.allowed_link_val:
err = f'bad link value: {newlink}'
self._log.err(err)
self._log.err(f'allowed: {self.allowed_link_val}')
raise YamlException(f'config content error: {err}')
return newlink
def resolve_dotfile_src(self, src, templater=None):
"""
get abs src file from a relative path
in dotpath
"""
newsrc = ''
if src:
new = src
if templater:
new = templater.generate_string(src)
if new != src and self._debug:
msg = f'dotfile src: \"{src}\" -> \"{new}\"'
self._dbg(msg)
src = new
src = os.path.join(self.settings[self.key_settings_dotpath],
src)
newsrc = self._norm_path(src)
return newsrc
def resolve_dotfile_dst(self, dst, templater=None):
"""resolve dotfile dst path"""
newdst = ''
if dst:
new = dst
if templater:
new = templater.generate_string(dst)
if new != dst and self._debug:
msg = f'dotfile dst: \"{dst}\" -> \"{new}\"'
self._dbg(msg)
dst = new
newdst = self._norm_path(dst)
return newdst
def add_dotfile_to_profile(self, dotfile_key, profile_key):
"""
add an existing dotfile key to a profile_key
if profile_key doesn't exist, the profile is created
we test using profiles variable since it merges
imported ones (include, etc) but insert in main
yaml only
return True if was added
"""
# create the profile if it doesn't exist
self._new_profile(profile_key)
if profile_key not in self.profiles:
return False
profile = self.profiles[profile_key]
# ensure profile dotfiles list is not None in local object
if self.key_profile_dotfiles not in profile or \
profile[self.key_profile_dotfiles] is None:
profile[self.key_profile_dotfiles] = []
# ensure profile dotfiles list is not None in yaml dict
dict_pro = self._yaml_dict[self.key_profiles][profile_key]
if self.key_profile_dotfiles not in dict_pro or \
dict_pro[self.key_profile_dotfiles] is None:
dict_pro[self.key_profile_dotfiles] = []
# add to the profile
pdfs = profile[self.key_profile_dotfiles]
if self.key_all not in pdfs and \
dotfile_key not in pdfs:
# append dotfile
pro = self._yaml_dict[self.key_profiles][profile_key]
pro[self.key_profile_dotfiles].append(dotfile_key)
if self._debug:
msg = f'add \"{dotfile_key}\" to profile \"{profile_key}\"'
self._dbg(msg)
self._dirty = True
return self._dirty
def get_all_dotfile_keys(self):
"""return all existing dotfile keys"""
return self.dotfiles.keys()
def _update_dotfile_chmod(self, key, dotfile, chmod):
old = None
if self.key_dotfile_chmod in dotfile:
old = dotfile[self.key_dotfile_chmod]
if old == self.chmod_ignore:
msg = (
'ignore chmod change since '
f'{self.chmod_ignore}'
)
self._dbg(msg)
return False
if old == chmod:
return False
if self._debug:
self._dbg(f'update dotfile: {key}')
self._dbg(f'old chmod value: {old}')
self._dbg(f'new chmod value: {chmod}')
dotfile = self._yaml_dict[self.key_dotfiles][key]
if not chmod:
del dotfile[self.key_dotfile_chmod]
else:
dotfile[self.key_dotfile_chmod] = str(format(chmod, 'o'))
return True
def update_dotfile(self, key, chmod):
"""
update an existing dotfile
return true if updated
"""
if key not in self.dotfiles.keys():
return False
dotfile = self._yaml_dict[self.key_dotfiles][key]
if not self._update_dotfile_chmod(key, dotfile, chmod):
return False
self._dirty = True
return True
def add_dotfile(self, key, src, dst, link, chmod=None,
trans_install_key=None, trans_update_key=None):
"""add a new dotfile"""
if key in self.dotfiles.keys():
return False
if self._debug:
self._dbg(f'adding new dotfile: {key}')
self._dbg(f'new dotfile src: {src}')
self._dbg(f'new dotfile dst: {dst}')
self._dbg(f'new dotfile link: {link}')
if chmod:
self._dbg(f'new dotfile chmod: {chmod:o}')
self._dbg(f'new dotfile trans_install: {trans_install_key}')
self._dbg(f'new dotfile trans_update: {trans_update_key}')
# create the dotfile dict
df_dict = {
self.key_dotfile_src: src,
self.key_dotfile_dst: dst,
}
# link
dfl = self.settings[self.key_settings_link_dotfile_default]
if str(link) != dfl:
df_dict[self.key_dotfile_link] = str(link)
# chmod
if chmod:
df_dict[self.key_dotfile_chmod] = str(format(chmod, 'o'))
# trans_install/trans_update
if trans_install_key:
df_dict[self.key_trans_install] = str(trans_install_key)
if trans_update_key:
df_dict[self.key_trans_update] = str(trans_update_key)
if self._debug:
self._dbg(f'dotfile dict: {df_dict}')
# add to global dict
self._yaml_dict[self.key_dotfiles][key] = df_dict
self._dirty = True
return True
def del_dotfile(self, key):
"""remove this dotfile from config"""
if key not in self._yaml_dict[self.key_dotfiles]:
self._log.err(f'key not in dotfiles: {key}')
return False
if self._debug:
self._dbg(f'remove dotfile: {key}')
del self._yaml_dict[self.key_dotfiles][key]
if self._debug:
dfs = self._yaml_dict[self.key_dotfiles]
self._dbg(f'new dotfiles: {dfs}')
self._dirty = True
return True
def del_dotfile_from_profile(self, df_key, pro_key):
"""remove this dotfile from that profile"""
if self._debug:
self._dbg(f'removing \"{df_key}\" from \"{pro_key}\"')
if df_key not in self.dotfiles.keys():
self._log.err(f'key not in dotfiles: {df_key}')
return False
if pro_key not in self.profiles.keys():
self._log.err(f'key not in profile: {pro_key}')
return False
# get the profile dictionary
profile = self._yaml_dict[self.key_profiles][pro_key]
if self.key_profile_dotfiles not in profile:
# profile does not contain any dotfiles
return True
if df_key not in profile[self.key_profile_dotfiles]:
return True
if self._debug:
dfs = profile[self.key_profile_dotfiles]
self._dbg(f'{pro_key} profile dotfiles: {dfs}')
self._dbg(f'remove {df_key} from profile {pro_key}')
profile[self.key_profile_dotfiles].remove(df_key)
if self._debug:
dfs = profile[self.key_profile_dotfiles]
self._dbg(f'{pro_key} profile dotfiles: {dfs}')
self._dirty = True
return True
def save(self):
"""save this instance and return True if saved"""
if not self._dirty:
return False
content = self._prepare_to_save(self._yaml_dict)
if self._dirty_deprecated:
# add minversion
settings = content[self.key_settings]
settings[self.key_settings_minversion] = VERSION
# save to file
if self._debug:
self._dbg(f'saving to {self._path}')
try:
with open(self._path, 'w', encoding='utf8') as file:
self._yaml_dump(content, file, fmt=self._config_format)
except Exception as exc:
self._log.err(exc)
err = f'error saving config: {self._path}'
raise YamlException(err) from exc
if self._dirty_deprecated:
warn = 'your config contained deprecated entries'
warn += ' and was updated'
self._log.warn(warn)
self._dirty = False
return True
def dump(self):
"""dump the config dictionary"""
output = io.StringIO()
content = self._prepare_to_save(self._yaml_dict.copy())
self._yaml_dump(content, output, fmt=self._config_format)
return output.getvalue()
########################################################
# block parsing
########################################################
def _parse_blk_settings(self, dic):
"""parse the "config" block"""
block = self._get_entry(dic, self.key_settings).copy()
# set defaults
settings = Settings(None).serialize().get(self.key_settings)
settings.update(block)
# resolve minimum version
if self.key_settings_minversion in settings:
minversion = settings[self.key_settings_minversion]
self._check_minversion(minversion)
# normalize paths
paths = self._norm_path(settings[self.key_settings_dotpath])
settings[self.key_settings_dotpath] = paths
paths = self._norm_path(settings[self.key_settings_workdir])
settings[self.key_settings_workdir] = paths
paths = [
self._norm_path(path)
for path in settings[Settings.key_filter_file]
]
settings[Settings.key_filter_file] = paths
paths = [
self._norm_path(path)
for path in settings[Settings.key_func_file]
]
settings[Settings.key_func_file] = paths
if self._debug:
self._debug_dict('settings block:', settings)
return settings
def _parse_blk_dotfiles(self, dic):
"""parse the "dotfiles" block"""
dotfiles = self._get_entry(dic, self.key_dotfiles).copy()
keys = dotfiles.keys()
if len(keys) != len(list(set(keys))):
dups = [x for x in keys if x not in list(set(keys))]
err = f'duplicate dotfile keys found: {dups}'
raise YamlException(err)
dotfiles = self._norm_dotfiles(dotfiles)
if self._debug:
self._debug_dict('dotfiles block', dotfiles)
return dotfiles
def _parse_blk_profiles(self, dic):
"""parse the "profiles" block"""
profiles = self._get_entry(dic, self.key_profiles).copy()
profiles = self._norm_profiles(profiles)
if self._debug:
self._debug_dict('profiles block', profiles)
return profiles
def _parse_blk_actions(self, dic):
"""parse the "actions" block"""
actions = self._get_entry(dic, self.key_actions,
mandatory=False)
if actions:
actions = actions.copy()
actions = self._norm_actions(actions)
if self._debug:
self._debug_dict('actions block', actions)
return actions
def _parse_blk_trans_install(self, dic):
"""parse the "trans_install" block"""
trans_install = self._get_entry(dic, self.key_trans_install,
mandatory=False)
if trans_install:
trans_install = trans_install.copy()
if self._debug:
self._debug_dict('trans_install block', trans_install)
return trans_install
def _parse_blk_trans_update(self, dic):
"""parse the "trans_update" block"""
trans_update = self._get_entry(dic, self.key_trans_update,
mandatory=False)
if trans_update:
trans_update = trans_update.copy()
if self._debug:
self._debug_dict('trans_update block', trans_update)
return trans_update
def _parse_blk_variables(self, dic):
"""parse the "variables" block"""
variables = self._get_entry(dic,
self.key_variables,
mandatory=False)
if variables:
variables = variables.copy()
if self._debug:
self._debug_dict('variables block', variables)
return variables
def _parse_blk_dynvariables(self, dic):
"""parse the "dynvariables" block"""
dvariables = self._get_entry(dic,
self.key_dvariables,
mandatory=False)
if dvariables:
dvariables = dvariables.copy()
if self._debug:
self._debug_dict('dynvariables block', dvariables)
return dvariables
def _parse_blk_uservariables(self, dic, current):
"""parse the "uservariables" block"""
uvariables = self._get_entry(dic,
self.key_uvariables,
mandatory=False)
uvars = {}
if not self._reloading and uvariables:
try:
for name, prompt in uvariables.items():
if name in current:
# ignore if already defined
if self._debug:
self._dbg(f'ignore uservariables {name}')
continue
content = userinput(prompt, debug=self._debug)
uvars[name] = content
except KeyboardInterrupt as exc:
raise YamlException('interrupted') from exc
if uvars:
uvars = uvars.copy()
if self._debug:
self._debug_dict('uservariables block', uvars)
# save uservariables
if uvars:
try:
self._save_uservariables(uvars)
except YamlException:
# ignore
pass
return uvars
########################################################
# parsing helpers
########################################################
def _template_include_entry(self):
"""template all "include" entries"""
# import_actions
new = []
entries = self.settings.get(self.key_import_actions, [])
new = self._template_list(entries)
if new:
self.settings[self.key_import_actions] = new
# import_configs
entries = self.settings.get(self.key_import_configs, [])
new = self._template_list(entries)
if new:
self.settings[self.key_import_configs] = new
# import_variables
entries = self.settings.get(self.key_import_variables, [])
new = self._template_list(entries)
if new:
self.settings[self.key_import_variables] = new
# profile's import
for _, val in self.profiles.items():
entries = val.get(self.key_import_profile_dfs, [])
new = self._template_list(entries)
if new:
val[self.key_import_profile_dfs] = new
def _norm_actions(self, actions):
"""
ensure each action is either pre or post explicitely
action entry of the form {action_key: (pre|post, action)}
"""
if not actions:
return actions
new = {}
for k, val in actions.items():
if k in (self.action_pre, self.action_post):
for key, action in val.items():
new[key] = (k, action)
else:
new[k] = (self.action_post, val)
return new
def _norm_profiles(self, profiles):
"""normalize profiles entries"""
if not profiles:
return profiles
new = {}
# loop through each profile
for pro, entries in profiles.items():
if pro == self.key_all:
msg = f'\"{self.key_all}\" is a special profile name, '
msg += 'consider renaming to avoid any issue.'
self._log.warn(msg)
if not pro:
msg = 'empty profile name'
self._log.warn(msg)
continue
if not entries:
# no entries in profile dict
continue
# add "dotfiles:" entry if not present in local object
if self.key_profile_dotfiles not in entries or \
entries[self.key_profile_dotfiles] is None:
entries[self.key_profile_dotfiles] = []
# add "dotfiles:" entry if not present in yaml dict
dict_pro = self._yaml_dict[self.key_profiles][pro]
if self.key_profile_dotfiles not in dict_pro or \
dict_pro[self.key_profile_dotfiles] is None:
dict_pro[self.key_profile_dotfiles] = []
new[pro] = entries
return new
def _norm_dotfile_chmod(self, entry):
value = str(entry[self.key_dotfile_chmod])
if value == self.chmod_ignore:
# is preserve
return
if len(value) < 3:
# bad format
err = f'bad format for chmod: {value}'
self._log.err(err)
raise YamlException(f'config content error: {err}')
# check is valid value
try:
int(value)
except Exception as exc:
err = f'bad format for chmod: {value}'
self._log.err(err)
err = f'config content error: {err}'
raise YamlException(err) from exc
# normalize chmod value
for chmodv in list(value):
chmodint = int(chmodv)
if chmodint < 0 or chmodint > 7:
err = f'bad format for chmod: {value}'
self._log.err(err)
raise YamlException(
f'config content error: {err}'
)
# octal
entry[self.key_dotfile_chmod] = int(value, 8)
def _norm_dotfiles(self, dotfiles):
"""normalize and check dotfiles entries"""
if not dotfiles:
return dotfiles
new = {}
for k, val in dotfiles.items():
if self.key_dotfile_src not in val:
# add 'src' as key' if not present
val[self.key_dotfile_src] = k
new[k] = val
else:
new[k] = val
if self.key_dotfile_link not in val:
# apply link value if undefined
value = self.settings[self.key_settings_link_dotfile_default]
val[self.key_dotfile_link] = value
if self.key_dotfile_noempty not in val:
# apply noempty if undefined
value = self.settings.get(self.key_settings_noempty, False)
val[self.key_dotfile_noempty] = value
if self.key_dotfile_template not in val:
# apply template if undefined
value = self.settings.get(self.key_settings_template, True)
val[self.key_dotfile_template] = value
if self.key_dotfile_chmod in val:
# validate value of chmod if defined
self._norm_dotfile_chmod(val)
return new
def _add_variables(self, new, shell=False, template=True, prio=False):
"""
add new variables
@shell: execute the variable through the shell
@template: template the variable
@prio: new takes priority over existing variables
"""
if not new:
return
# merge
if prio:
self.variables = self._merge_dict(new, self.variables)
else:
# clear existing variable
for k in list(new.keys()):
if k in self.variables.keys():
del new[k]
# merge
self.variables = self._merge_dict(self.variables, new)
# ensure enriched variables are relative to this config
self.variables = self._enrich_vars(self.variables, self._profile)
# re-create the templater
self._redefine_templater()
if template:
# rec resolve variables with new ones
self.variables = self._rec_resolve_variables(self.variables)
if shell and new:
# shell exec
self._shell_exec_dvars(self.variables, keys=new.keys())
# re-create the templater
self._redefine_templater()
def _enrich_vars(self, variables, profile):
"""return enriched variables"""
# add profile variable
if profile:
variables['profile'] = profile
# add some more variables
path = self.settings.get(self.key_settings_dotpath)
path = self._norm_path(path)
variables['_dotdrop_dotpath'] = path
variables['_dotdrop_cfgpath'] = self._norm_path(self._path)
path = self.settings.get(self.key_settings_workdir)
path = self._norm_path(path)
variables['_dotdrop_workdir'] = path
return variables
def _get_profile_included_item(self, keyitem):
"""recursively get included <keyitem> in profile"""
profiles = [self._profile] + self._inc_profiles
items = {}
for profile in profiles:
seen = [self._profile]
i = self.__get_profile_included_item(profile, keyitem, seen)
items = self._merge_dict(i, items)
return items
def __get_profile_included_item(self, profile, keyitem, seen):
"""recursively get included <keyitem> from profile"""
items = {}
if not profile or profile not in self.profiles.keys():
return items
# considered profile entry
pentry = self.profiles.get(profile)
# recursively get <keyitem> from inherited profile
for inherited_profile in pentry.get(self.key_profile_include, []):
if inherited_profile == profile or inherited_profile in seen:
raise YamlException('\"include\" loop')
seen.append(inherited_profile)
new = self.__get_profile_included_item(inherited_profile,
keyitem, seen)
if self._debug:
msg = f'included {keyitem} from {inherited_profile}: {new}'
self._dbg(msg)
items.update(new)
cur = pentry.get(keyitem, {})
return self._merge_dict(cur, items)
def _resolve_profile_all(self):
"""resolve some other parts of the config"""
# profile -> ALL
for k, val in self.profiles.items():
dfs = val.get(self.key_profile_dotfiles, None)
if not dfs:
continue
if self.key_all in dfs:
if self._debug:
self._dbg(f'add ALL to profile \"{k}\"')
val[self.key_profile_dotfiles] = self.dotfiles.keys()
def _resolve_profile_includes(self):
"""resolve elements included through other profiles"""
for k, _ in self.profiles.items():
self._rec_resolve_profile_include(k)
def _rec_resolve_profile_include(self, profile):
"""
recursively resolve include of other profiles's:
* dotfiles
* actions
returns dotfiles, actions
"""
this_profile = self.profiles[profile]
# considered profile content
dotfiles = this_profile.get(self.key_profile_dotfiles, []) or []
actions = this_profile.get(self.key_profile_actions, []) or []
includes = this_profile.get(self.key_profile_include, []) or []
if not includes:
# nothing to include
return dotfiles, actions
if self._debug:
incs = ','.join(includes)
self._dbg(f'{profile} includes {incs}')
self._dbg(f'{profile} dotfiles before include: {dotfiles}')
self._dbg(f'{profile} actions before include: {actions}')
seen = []
for i in uniq_list(includes):
if self._debug:
self._dbg(f'resolving includes "{profile}" <- "{i}"')
# ensure no include loop occurs
if i in seen:
raise YamlException('\"include loop\"')
seen.append(i)
# included profile even exists
if i not in self.profiles.keys():
self._log.warn(f'include unknown profile: {i}')
continue
# recursive resolve
if self._debug:
self._dbg(f'recursively resolving includes for profile "{i}"')
o_dfs, o_actions = self._rec_resolve_profile_include(i)
# merge dotfile keys
if self._debug:
msg = f'Merging dotfiles {profile}'
msg += f' <- {i}: {dotfiles} <- {o_dfs}'
self._dbg(msg)
dotfiles.extend(o_dfs)
this_profile[self.key_profile_dotfiles] = uniq_list(dotfiles)
# merge actions keys
if self._debug:
msg = f'Merging actions {profile} '
msg += f'<- {i}: {actions} <- {o_actions}'
self._dbg(msg)
actions.extend(o_actions)