-
Notifications
You must be signed in to change notification settings - Fork 15
/
lsr_role2collection.py
1813 lines (1678 loc) · 65.8 KB
/
lsr_role2collection.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) 2020 Matt Martz <[email protected]>
# GNU General Public License v3.0+
# (see https://www.gnu.org/licenses/gpl-3.0.txt)
# Usage:
# lsr-role2collection.py [--namespace COLLECTION_NAMESPACE]
# [--collection COLLECTION_NAME]
# --src-path COLLECTION_SRC_PATH
# --dest-path COLLECTION_DEST_PATH
# --role ROLE_NAME
# [--subrole-prefix STR]
# [--replace-dot STR]
# [-h]
# Or
#
# COLLECTION_SRC_PATH=/path/to/{src_owner} \
# COLLECTION_DEST_PATH=/path/to/collections \
# COLLECTION_NAMESPACE=mynamespace \
# COLLECTION_NAME=myname \
# lsr-role2collection.py --role ROLE_NAME
# ROLE_NAME role must exist in COLLECTION_SRC_PATH
# Converted collections are placed in COLLECTION_DEST_PATH/ansible_collections/COLLECTION_NAMESPACE/COLLECTION_NAME
import argparse
import errno
import fnmatch
import logging
import os
import re
import subprocess
import sys
import textwrap
from pathlib import Path
from ruamel.yaml import YAML
from shutil import copytree, copy2, copyfile, ignore_patterns, rmtree, which
from operator import itemgetter
ALL_ROLE_DIRS = [
"action_plugins",
"defaults",
"examples",
"files",
"filter_plugins",
"handlers",
"library",
"meta",
"module_utils",
"tasks",
"templates",
"tests",
"vars",
]
PLAY_KEYS = {
"gather_facts",
"handlers",
"hosts",
"import_playbook",
"post_tasks",
"pre_tasks",
"roles",
"tasks",
}
TASK_LIST_KWS = [
"always",
"block",
"handlers",
"post_tasks",
"pre_tasks",
"rescue",
"tasks",
]
EXTRA_SCRIPT = "lsr_role2coll_extra_script"
class LSRException(Exception):
pass
def get_role_dir(role_path, dirpath):
dir_pth = Path(dirpath)
if role_path == dir_pth:
return None, None
relpath = dir_pth.relative_to(role_path)
base_dir = relpath.parts[0]
if base_dir in ALL_ROLE_DIRS:
return base_dir, relpath
return None, None
def get_file_type(item):
if isinstance(item, dict):
if "galaxy_info" in item or "dependencies" in item:
return "meta"
return "vars"
elif isinstance(item, list):
return "tasks"
else:
raise LSRException(f"Error: unknown type of file: {item}")
def get_item_type(item):
if isinstance(item, dict):
for key in PLAY_KEYS:
if key in item:
return "play"
if "block" in item:
return "block"
return "task"
else:
raise LSRException(f"Error: unknown type of item: {item}")
class LSRFileTransformerBase(object):
# we used to try to not deindent comment lines in the Ansible yaml,
# but this changed the indentation when comments were used in
# literal strings, which caused test failures - so for now, we
# have to live with poorly indented Ansible comments . . .
# INDENT_RE = re.compile(r'^ (?! *#)', flags=re.MULTILINE)
INDENT_RE = re.compile(r"^ ", flags=re.MULTILINE)
HEADER_RE = re.compile(r"^(---\n|.*\n---\n)", flags=re.DOTALL)
FOOTER_RE = re.compile(r"\n([.][.][.]|[.][.][.]\n.*)$", flags=re.DOTALL)
def __init__(self, filepath, rolename, newrolename, args):
self.filepath = filepath
self.namespace = args["namespace"]
self.collection = args["collection"]
self.prefix = args["prefix"]
self.subrole_prefix = args["subrole_prefix"]
self.replace_dot = args["replace_dot"]
self.rolename_regex = "[{0}.]".format(self.replace_dot)
self.role_modules = args["role_modules"]
self.src_owner = args["src_owner"]
self.top_dir = args["top_dir"]
self.rolename = rolename
self.newrolename = newrolename
self.extra_mapping_src_owner = args["extra_mapping_src_owner"]
self.extra_mapping_src_role = args["extra_mapping_src_role"]
self.extra_mapping_dest_prefix = args["extra_mapping_dest_prefix"]
self.extra_mapping_dest_role = args["extra_mapping_dest_role"]
buf = open(filepath, encoding="utf-8").read()
self.ruamel_yaml = YAML(typ="rt")
match = re.search(LSRFileTransformerBase.HEADER_RE, buf)
if match:
self.header = match.group(1)
else:
self.header = ""
match = re.search(LSRFileTransformerBase.FOOTER_RE, buf)
if match:
self.footer = match.group(1) + "\n"
else:
self.footer = ""
self.ruamel_yaml.default_flow_style = False
self.ruamel_yaml.preserve_quotes = True
self.ruamel_yaml.width = 1024
self.ruamel_data = self.ruamel_yaml.load(buf)
self.ruamel_yaml.indent(mapping=2, sequence=4, offset=2)
self.file_type = get_file_type(self.ruamel_data)
self.outputfile = None
self.outputstream = sys.stdout
def run(self):
if self.file_type == "vars":
self.handle_vars(self.ruamel_data)
elif self.file_type == "meta":
self.handle_meta(self.ruamel_data)
else:
for item in self.ruamel_data:
self.handle_item(item)
def write(self):
def xform(thing):
logging.debug(f"xform thing {thing}")
if self.file_type == "tasks":
thing = re.sub(LSRFileTransformerBase.INDENT_RE, "", thing)
thing = self.header + thing
if not thing.endswith("\n"):
thing = thing + "\n"
thing = thing + self.footer
return thing
if self.outputfile:
outstrm = open(self.outputfile, "w", encoding="utf-8")
else:
outstrm = self.outputstream
self.ruamel_yaml.dump(self.ruamel_data, outstrm, transform=xform)
def task_cb(self, task):
"""subclass will override"""
pass
def other_cb(self, item):
"""subclass will override"""
pass
def vars_cb(self, item):
"""subclass will override"""
pass
def meta_cb(self, item):
"""subclass will override"""
pass
def handle_item(self, item):
"""handle any type of item - call the appropriate handlers"""
ans_type = get_item_type(item)
self.handle_vars(item)
self.handle_other(item)
if ans_type == "task":
self.handle_task(item)
self.handle_task_list(item)
def handle_other(self, item):
"""handle properties of Ansible item other than vars and tasks"""
self.other_cb(item)
def handle_vars(self, item):
"""handle vars of Ansible item"""
self.vars_cb(item)
def handle_meta(self, item):
"""handle meta/main.yml file"""
self.meta_cb(item)
def handle_task(self, task):
"""handle a single task"""
self.task_cb(task)
def handle_task_list(self, item):
"""item has one or more fields which hold a list of Task objects"""
for kw in TASK_LIST_KWS:
if kw in item:
for task in item[kw]:
self.handle_item(task)
def get_role_modules(role_path):
"""get the modules from the role
returns a set() of module names"""
role_modules = set()
library_path = Path(os.path.join(role_path, "library"))
if library_path.is_dir():
for mod_file in library_path.iterdir():
if mod_file.is_file() and mod_file.stem != "__init__":
role_modules.add(mod_file.stem)
return role_modules
class LSRTransformer(object):
"""Transform all of the .yml files in a role or role subdir"""
def __init__(
self,
role_path,
transformer_args,
is_role_dir=True,
role_name=None,
new_role_name=None,
file_xfrm_cls=LSRFileTransformerBase,
):
"""Create a role transformer. The user can specify the specific class
to use for transforming each file, and the extra arguments to pass to the
constructor of that class
is_role_dir - if True, role_path is the role directory (with all of the usual role subdirs)
if False, just operate on the .yml files found in role_path"""
self.role_name = role_name
self.new_role_name = new_role_name
self.role_path = role_path
self.is_role_dir = is_role_dir
self.transformer_args = transformer_args
self.file_xfrm_cls = file_xfrm_cls
if self.is_role_dir and not self.role_name:
self.role_name = os.path.basename(self.role_path)
def run(self):
for dirpath, _, filenames in os.walk(self.role_path):
if dirpath.endswith("/files") or dirpath.endswith("/templates"):
continue
if self.is_role_dir:
role_dir, _ = get_role_dir(self.role_path, dirpath)
if not role_dir:
continue
for filename in filenames:
if not filename.endswith(".yml"):
continue
filepath = os.path.join(dirpath, filename)
logging.debug(f"filepath {filepath}")
try:
lsrft = self.file_xfrm_cls(
filepath,
self.role_name,
self.new_role_name,
self.transformer_args,
)
lsrft.run()
lsrft.write()
except LSRException as lsrex:
logging.debug(f"Could not transform {filepath}: {lsrex}")
# ==============================================================================
ROLE_DIRS = (
"defaults",
"files",
"handlers",
"meta",
"tasks",
"templates",
"vars",
)
PLUGINS = (
"action_plugins",
"become_plugins",
"cache_plugins",
"callback_plugins",
"cliconf_plugins",
"connection_plugins",
"doc_fragments",
"filter_plugins",
"httpapi_plugins",
"inventory_plugins",
"library",
"lookup_plugins",
"module_utils",
"netconf_plugins",
"shell_plugins",
"strategy_plugins",
"terminal_plugins",
"test_plugins",
"vars_plugins",
)
TESTS = ("tests",)
DOCS = (
"docs",
"design_docs",
"examples",
"README.md",
"README.html",
"DCO",
)
TOX = (
".flake8",
".pre-commit-config.yaml",
".pydocstyle",
".travis",
".travis.yml",
".yamllint_defaults.yml",
".yamllint.yml",
".yamllint.yaml",
"ansible_pytest_extra_requirements.txt",
"custom_requirements.txt",
"molecule",
"molecule_extra_requirements.txt",
"pylintrc",
"pylint_extra_requirements.txt",
"pytest_extra_requirements.txt",
"tox.ini",
"tuned_requirements.txt",
".pandoc_template.html5", # contains smart quotes - ansible-test does not like
)
DO_NOT_COPY = (
".github",
".gitignore",
".lgtm.yml",
".tox",
".venv",
"artifacts",
"run_pylint.py",
"scripts",
"semaphore",
"standard-inventory-qcow2",
"Vagrantfile",
"CHANGELOG",
)
ALL_DIRS = ROLE_DIRS + PLUGINS + TESTS + DOCS + DO_NOT_COPY
IMPORT_RE = re.compile(
rb"(\bimport) (ansible\.module_utils\.)(\S+)(.*)(\s+#.+|.*)$", flags=re.M
)
FROM_RE = re.compile(
rb"(\bfrom) (ansible\.module_utils\.?)(\S+)? import (\(*(?:\n|\r\n)?)(\S+)(\s+#.+|.*)$",
flags=re.M,
)
if os.environ.get("LSR_DEBUG") == "true":
logging.getLogger().setLevel(logging.DEBUG)
elif os.environ.get("LSR_INFO") == "true":
logging.getLogger().setLevel(logging.INFO)
else:
logging.getLogger().setLevel(logging.ERROR)
class LSRFileTransformer(LSRFileTransformerBase):
"""Do the role file transforms - fix role names, add FQCN
to module names, etc."""
def convert_rolename(self, rolename, lsr_rolename=None):
"""convert the given rolename to the new name"""
if rolename.count(".") == 1:
_src_owner, _rolename_base = rolename.split(".")
else:
_src_owner = None
_rolename_base = rolename
if not lsr_rolename:
lsr_rolename = self.src_owner + "." + self.rolename
logging.debug(f"\ttask role {rolename}")
new_name = None
if rolename == lsr_rolename or self.comp_rolenames(rolename, self.rolename):
new_name = self.prefix + self.newrolename
elif _rolename_base and _rolename_base in self.extra_mapping_src_role:
_src_role_index = self.extra_mapping_src_role.index(_rolename_base)
# --extra-mapping "SRC_OWNER0.SRC_ROLE0:DEST_PREFIX[.]DEST_ROLE1,
# SRC_ROLE1:DEST_PREFIX[.]DEST_ROLE1"
# current _rolename_base is SRC_ROLE0 and
# _src_owner is None or _src_owner is SRC_OWNER0
# or current _rolename_base is SRC_ROLE1
if (
not _src_owner
or (_src_owner == self.extra_mapping_src_owner[_src_role_index])
or (
not self.extra_mapping_src_owner[_src_role_index]
and _src_owner == self.src_owner
)
):
new_name = "{0}{1}".format(
(
self.extra_mapping_dest_prefix[_src_role_index]
if self.extra_mapping_dest_prefix[_src_role_index]
else self.prefix
),
self.extra_mapping_dest_role[_src_role_index],
)
elif rolename.startswith("{{ role_path }}"):
match = re.match(r"{{ role_path }}/roles/([\w\d.]+)", rolename)
if match.group(1).startswith(self.subrole_prefix):
new_name = self.prefix + match.group(1).replace(".", self.replace_dot)
else:
new_name = (
self.prefix
+ self.subrole_prefix
+ match.group(1).replace(".", self.replace_dot)
)
return new_name
def task_cb(self, task):
"""do something with a task item"""
module_name = None
role_module_name = None
is_include_or_import = False
is_include_vars = False
mods = ["include_role", "import_role", "include_vars"]
# add fqcn versions
mods = mods + ["ansible.builtin." + xx for xx in mods]
for mod in mods:
if mod in task:
module_name = mod
is_include_or_import = mod.endswith("include_role") or mod.endswith(
"import_role"
)
is_include_vars = mod.endswith("include_vars")
break
if module_name is None:
for rm in self.role_modules:
if rm in task:
module_name = rm
role_module_name = rm
break
if is_include_or_import:
new_rolename = self.convert_rolename(task[module_name]["name"])
if new_rolename:
task[module_name]["name"] = new_rolename
elif is_include_vars:
"""
Convert include_vars in the test playbook.
include_vars: path/to/{src_owner}.ROLENAME/file_or_dir
or
include_vars:
file|dir: path/to/{src_owner}.ROLENAME/file_or_dir
Note: If the path is relative and not inside a role,
it will be parsed relative to the playbook.
To solve it, the relative path is converted to the absolute path.
"""
_src_owner_match = "/" + self.src_owner + "."
_src_owner_pattern = r".*/{0}[.](\w+)/([\w\d./]+)".format(self.src_owner)
if isinstance(task[module_name], dict):
_key = None
if (
"file" in task[module_name].keys()
and _src_owner_match in task[module_name]["file"]
):
_key = "file"
elif (
"dir" in task[module_name].keys()
and _src_owner_match in task[module_name]["dir"]
):
_key = "dir"
if _key:
_path = task[module_name][_key]
_match = re.match(_src_owner_pattern, _path)
task[module_name][_key] = (
"{0}/ansible_collections/{1}/{2}/roles/{3}/{4}".format(
self.top_dir,
self.namespace,
self.collection,
_match.group(1),
_match.group(2),
)
)
elif (
isinstance(task[module_name], str)
and _src_owner_match in task[module_name]
):
_path = task[module_name]
_match = re.match(_src_owner_pattern, _path)
task[module_name] = (
"{0}/ansible_collections/{1}/{2}/roles/{3}/{4}".format(
self.top_dir,
self.namespace,
self.collection,
_match.group(1),
_match.group(2),
)
)
elif role_module_name:
logging.debug(f"\ttask role module {role_module_name}")
# assumes task is an orderreddict
idx = tuple(task).index(role_module_name)
val = task[role_module_name]
task.insert(idx, self.prefix + role_module_name, val)
del task[role_module_name]
def other_cb(self, item):
"""do something with the other non-task information in an item
this is where you will get e.g. the `roles` keyword from a play"""
self.change_roles(item, "roles")
def vars_cb(self, item):
"""handle vars of Ansible item, or vars from a vars file"""
for var in item.get("vars", []):
logging.debug(f"\tvar = {var}")
if var == "roletoinclude":
lsr_rolename = self.src_owner + "." + self.rolename
if item["vars"][var] == lsr_rolename:
item["vars"][var] = self.prefix + self.newrolename
return
def meta_cb(self, item):
"""hand a meta/main.yml style file"""
self.change_roles(item, "dependencies")
def comp_rolenames(self, name0, name1):
if name0 == name1:
return True
else:
# self.rolename_regex is default to "[_.]".
core0 = re.sub(self.rolename_regex, "", name0)
core1 = re.sub(self.rolename_regex, "", name1)
return core0 == core1
def change_roles(self, item, roles_kw):
"""ru_item is an item which may contain a roles or dependencies
specifier - the roles_kw is either "roles" or "dependencies"
"""
lsr_rolename = self.src_owner + "." + self.rolename
for idx, role in enumerate(item.get(roles_kw, [])):
changed = False
# role could be
# ordereddict([('name', 'linux-system-roles.ROLENAME')])
# or
# 'linux-system-roles.ROLENAME'
if isinstance(role, dict):
if "name" in role:
key = "name"
else:
key = "role"
new_rolename = self.convert_rolename(role[key], lsr_rolename)
if new_rolename:
role[key] = new_rolename
changed = True
else:
new_rolename = self.convert_rolename(role, lsr_rolename)
if new_rolename:
role = new_rolename
changed = True
if changed:
item[roles_kw][idx] = role
def write(self):
"""assume we are operating on files already copied to the dest dir,
so write file in-place"""
self.outputfile = self.filepath
super().write()
def lsr_copyleaf(src, dest, symlinks=True, ignore=None):
if src.is_symlink() and symlinks:
# symlinks=True --> symlink in dest
copyfile(src, dest, follow_symlinks=(not symlinks))
elif src.is_dir():
# symlinks=True --> symlink in dest
# symlinks=False --> copy in dest
copytree(src, dest, symlinks=symlinks, ignore=ignore)
else:
copyfile(src, dest)
# Once python 3.8 is available in Travis CI,
# replace lsr_copytree with shutil.copytree with dirs_exist_ok=True.
def lsr_copytree(src, dest, symlinks=True, dirs_exist_ok=False, ignore=None):
if dest.exists():
if dest.is_dir():
for sr in src.iterdir():
subsrc = src / sr.name
subdest = dest / sr.name
if ignore:
if sr.name != ignore:
if subsrc.is_dir():
if subdest.exists() and dirs_exist_ok:
rmtree(subdest)
lsr_copytree(
subsrc,
subdest,
symlinks=symlinks,
ignore=ignore,
dirs_exist_ok=True,
)
else:
if subdest.exists() and dirs_exist_ok:
subdest.unlink()
lsr_copyleaf(
subsrc, subdest, symlinks=symlinks, ignore=ignore
)
else:
if subsrc.is_dir():
if subdest.exists() and dirs_exist_ok:
rmtree(subdest)
lsr_copytree(
subsrc,
subdest,
symlinks=symlinks,
dirs_exist_ok=dirs_exist_ok,
)
else:
if (subdest.exists() or subdest.is_symlink()) and dirs_exist_ok:
subdest.unlink()
# symlinks=False --> copy in dest
copy2(subsrc, subdest, follow_symlinks=(not symlinks))
else:
if dest.exists() and dirs_exist_ok:
dest.unlink()
lsr_copyleaf(src, dest, symlinks=symlinks, ignore=ignore)
else:
lsr_copyleaf(src, dest, symlinks=symlinks, ignore=ignore)
def dir_to_plugin(v):
if v[-8:] == "_plugins":
return v[:-8]
elif v == "library":
return "modules"
return v
def file_replace(path, find, replace, file_patterns):
"""
Replace a pattern `find` with `replace` in the files that match
`file_patterns` under `path`.
"""
for root, dirs, files in os.walk(os.path.abspath(path)):
for file_pattern in file_patterns:
for filename in fnmatch.filter(files, file_pattern):
filepath = os.path.join(root, filename)
with open(filepath, encoding="utf-8") as f:
s = f.read()
s = re.sub(find, replace, s)
with open(filepath, "w", encoding="utf-8") as f:
f.write(s)
def copy_tree_with_replace(
src_path,
dest_path,
role,
new_role,
TUPLE,
transformer_args,
isrole=True,
ignoreme=None,
symlinks=True,
):
"""
1. Copy files and dirs in the dir to
DEST_PATH/ansible_collections/NAMESPACE/COLLECTION/roles/ROLE/dir
or
DEST_PATH/ansible_collections/NAMESPACE/COLLECTION/dir/ROLE.
2. Parse the source tree to look for task_roles
3. Replace the task_roles with FQCN
"""
for dirname in TUPLE:
src = src_path / dirname
if src.is_dir():
if isrole:
dest = dest_path / "roles" / new_role / dirname
else:
dest = dest_path / dirname / new_role
logging.info(f"Copying role {src} to {dest}")
if ignoreme:
lsr_copytree(
src,
dest,
ignore=ignore_patterns(*ignoreme),
symlinks=symlinks,
dirs_exist_ok=True,
)
else:
lsr_copytree(src, dest, symlinks=symlinks, dirs_exist_ok=True)
lsrxfrm = LSRTransformer(
dest, transformer_args, False, role, new_role, LSRFileTransformer
)
lsrxfrm.run()
def cleanup_symlinks(path, role, rmlist):
"""
Clean up symlinks in tests/roles
"""
if path.exists():
nodes = sorted(list(path.rglob("*")), reverse=True)
for node in nodes:
for item in rmlist:
if item == node.name:
if node.is_symlink():
node.unlink()
if (
node.is_dir()
and (
r"linux-system-roles." + role == node.name
or (role == "sshd" and node.name == "ansible-sshd")
)
and not any(node.iterdir())
):
node.rmdir()
roles_dir = path / "roles"
if roles_dir.exists():
for sr in roles_dir.iterdir():
if sr.is_symlink():
sr.unlink()
if not any(roles_dir.iterdir()):
roles_dir.rmdir()
def gather_module_utils_parts(module_utils_dir):
module_utils = []
if module_utils_dir.is_dir():
for root, dirs, files in os.walk(module_utils_dir):
for filename in files:
if os.path.splitext(filename)[1] != ".py":
continue
full_path = (Path(root) / filename).relative_to(module_utils_dir)
parts = bytes(full_path)[:-3].split(b"/")
if parts[-1] == b"__init__":
del parts[-1]
module_utils.append(parts)
return module_utils
def import_replace(match):
"""
If 'import ansible.module_utils.something ...' matches,
'import ansible_collections.NAMESPACE.COLLECTION.plugins.module_utils.something ...'
is returned to replace.
"""
_src_path = config["src_path"]
_namespace = config["namespace"]
_collection = config["collection"]
_role = config["role"]
_module_utils = config["module_utils"]
_additional_rewrites = config["additional_rewrites"]
_module_utils_dir = config["module_utils_dir"]
parts = match.group(3).split(b".")
match_group3 = match.group(3)
src_module_path = _src_path / "module_utils" / match.group(3).decode("utf-8")
dest_module_path0 = _module_utils_dir / match.group(3).decode("utf-8")
dest_module_path1 = _module_utils_dir / _role
if len(parts) == 1:
if not src_module_path.is_dir() and (
dest_module_path0.is_dir() or dest_module_path1.is_dir()
):
match_group3 = (_role + "." + match.group(3).decode("utf-8")).encode()
parts = match_group3.split(b".")
if parts in _module_utils:
if match.group(1) == b"import" and match.group(4) == b"":
_additional_rewrites.append(parts)
if src_module_path.exists() or Path(str(src_module_path) + ".py").exists():
return b"import ansible_collections.%s.%s.plugins.module_utils.%s%s" % (
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match_group3,
match.group(5),
)
else:
return (
b"import ansible_collections.%s.%s.plugins.module_utils.%s as %s%s"
% (
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match_group3,
parts[-1],
match.group(5),
)
)
return b"%s ansible_collections.%s.%s.plugins.module_utils.%s%s%s" % (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match_group3,
match.group(4),
match.group(5),
)
return match.group(0)
def get_candidates(parts3, parts5):
from_file0 = config["dest_path"] / "plugins" / "module_utils"
for p3 in parts3:
from_file0 = from_file0 / p3.decode("utf-8")
from_file1 = from_file0
for p5 in parts5:
from_file1 = from_file1 / p5.decode("utf-8").strip(", ")
from_file0 = Path(str(from_file0) + ".py")
lfrom_file0 = Path(str(from_file0).lower())
from_file1 = Path(str(from_file1) + ".py")
lfrom_file1 = Path(str(from_file1).lower())
return from_file0, lfrom_file0, from_file1, lfrom_file1
def from_replace(match):
"""
case 1:
If it matches:
from ansible.module_utils.ROLE.somedir import module
and if plugins/module_utils/ROLE/somedir/module.py does not exist
in the converted tree,
'from ansible_collections.NAMESPACE.COLLECTION.plugins.module_utils.ROLE.somedir.__init__ import module'
is returned to replace.
case 2:
If it matches:
from ansible.module_utils.ROLE.subdir.something import (\n
and if plugins/module_utils/ROLE/subdir/something.py exists in the
converted tree,
'from ansible_collections.NAMESPACE.COLLECTION.plugins.module_utils.ROLE.subdir.something import (\n'
is returned to replace.
Legend:
- group1 - from
- group2 - ansible.module_utils
- group3 - name if any
- group4 - ( if any
- group5 - identifier
"""
_src_path = config["src_path"]
_namespace = config["namespace"]
_collection = config["collection"]
_role = config["role"]
_module_utils = config["module_utils"]
_module_utils_dir = config["module_utils_dir"]
try:
parts3 = match.group(3).split(b".")
except AttributeError:
parts3 = []
try:
parts5 = match.group(5).split(b".")
except AttributeError:
parts5 = []
# parts3 (e.g., [b'ROLE', b'subdir', b'module']) matches one module_utils or
# size of parts3 is 1 (e.g., [b'module']), in this case, module.py was moved
# to ROLE/module.py or module is a dir.
# If latter, match.group(3) has to be converted to b'ROLE.module'.
match_group3 = match.group(3)
if len(parts3) == 1:
src_module_path = _src_path / "module_utils" / match.group(3).decode("utf-8")
dest_module_path0 = _module_utils_dir / match.group(3).decode("utf-8")
dest_module_path1 = _module_utils_dir / _role
if not src_module_path.is_dir() and (
dest_module_path0.is_dir() or dest_module_path1.is_dir()
):
match_group3 = (_role + "." + match.group(3).decode("utf-8")).encode()
parts3 = match_group3.split(b".")
if parts3 in _module_utils:
from_file0, lfrom_file0, from_file1, lfrom_file1 = get_candidates(
parts3, parts5
)
if (
from_file0.is_file()
or from_file1.is_file()
or lfrom_file0.is_file()
or lfrom_file1.is_file()
):
return (
b"%s ansible_collections.%s.%s.plugins.module_utils.%s import %s%s%s"
% (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match_group3,
match.group(4),
match.group(5),
match.group(6),
)
)
else:
return (
b"%s ansible_collections.%s.%s.plugins.module_utils.%s.__init__ import %s%s%s"
% (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match_group3,
match.group(4),
match.group(5),
match.group(6),
)
)
if parts5 in _module_utils:
from_file0, lfrom_file0, from_file1, lfrom_file1 = get_candidates(
parts3, parts5
)
if parts3:
if (
from_file0.is_file()
or from_file1.is_file()
or lfrom_file0.is_file()
or lfrom_file1.is_file()
):
return (
b"%s ansible_collections.%s.%s.plugins.module_utils.%s import %s%s%s"
% (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match.group(3),
match.group(4),
match.group(5),
match.group(6),
)
)
else:
return (
b"%s ansible_collections.%s.%s.plugins.module_utils.%s.__init__ import %s%s%s"
% (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match.group(3),
match.group(4),
match.group(5),
match.group(6),
)
)
if (
from_file0.is_file()
or from_file1.is_file()
or lfrom_file0.is_file()
or lfrom_file1.is_file()
):
return (
b"%s ansible_collections.%s.%s.plugins.module_utils import %s%s%s"
% (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match.group(4),
match.group(5),
match.group(6),
)
)
else:
return (
b"%s ansible_collections.%s.%s.plugins.module_utils.__init__ import %s%s%s"
% (
match.group(1),
bytes(_namespace, "utf-8"),
bytes(_collection, "utf-8"),
match.group(4),
match.group(5),
match.group(6),
)