This repository has been archived by the owner on Mar 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
migrate.py
executable file
·2057 lines (1655 loc) · 75.7 KB
/
migrate.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 python
# also dynamically imports ansible in code
import argparse
import configparser
import contextlib
import glob
import itertools
import logging
import os
import re
import shutil
import subprocess
import sys
import textwrap
import yaml
from collections import defaultdict
from collections.abc import Mapping
from importlib import import_module
from string import Template
from typing import Dict, Set
from ansible.parsing.yaml.dumper import AnsibleDumper
from ansible.parsing.yaml.loader import AnsibleLoader
from ansible.vars.reserved import is_reserved_name
import logzero
from logzero import logger
from baron.parser import ParsingError
import redbaron
from gh import GitHubOrgClient
from rsa_utils import RSAKey
from template_utils import render_template_into
# https://github.com/ansible/ansible/blob/100fe52860f45238ee8ca9e3019d1129ad043c68/hacking/fix_test_syntax.py#L62
FILTER_RE = re.compile(r'((.+?)\s*([\w \.\'"]+)(\s*)\|(\s*)(\w+))')
TEST_RE = re.compile(r'((.+?)\s*([\w \.\'"]+)(\s*)is(\s*)(\w+))')
DEVEL_URL = 'https://github.com/ansible/ansible.git'
DEVEL_BRANCH = 'devel'
MIGRATED_DEVEL_REPO_NAME = 'ansible-minimal'
ALL_THE_FILES = set()
VARDIR = os.environ.get('GRAVITY_VAR_DIR', '.cache')
COLLECTION_NAMESPACE = 'test_migrate_ns'
PLUGIN_EXCEPTION_PATHS = {'modules': 'lib/ansible/modules', 'module_utils': 'lib/ansible/module_utils', 'inventory_scripts': 'contrib/inventory'}
PLUGIN_DEST_EXCEPTION_PATHS = {'inventory_scripts': 'scripts/inventory'}
COLLECTION_SKIP_REWRITE = ('_core',)
RAW_STR_TMPL = "r'''{str_val}'''"
STR_TMPL = "'''{str_val}'''"
BAD_EXT = frozenset({'.pyo', '.pyc'})
VALID_PLUGIN_TYPES = frozenset({
'action',
'become',
'cache',
'callback',
'cliconf',
'connection',
'doc_fragments',
'filter',
'httpapi',
'inventory',
'lookup',
'module_utils',
'modules',
'netconf',
'shell',
'strategy',
'terminal',
'test',
'vars',
'inventory_scripts',
})
NOT_PLUGINS=frozenset(set(['inventory_scripts']))
LOGFILE = os.path.join(VARDIR, 'errors.log')
os.makedirs(VARDIR, exist_ok=True)
logzero.logfile(LOGFILE, loglevel=logging.WARNING)
core = {}
manual_check = defaultdict(list)
def add_core(ptype, name):
global core
if ptype not in core:
core[ptype] = set()
core[ptype].add(name)
def add_manual_check(key, value, filename):
global manual_check
manual_check[filename].append((key, value))
def checkout_repo(
git_url: str, checkout_path: str,
*,
refresh: bool = False,
) -> Set[str]:
"""Fetch and optionally refresh the repo."""
if not os.path.exists(checkout_path):
subprocess.check_call(('git', 'clone', git_url, checkout_path))
elif refresh:
subprocess.check_call(
('git', 'checkout', DEVEL_BRANCH),
cwd=checkout_path,
)
subprocess.check_call(('git', 'pull', '--rebase'), cwd=checkout_path)
return set(
f.strip()
for f in subprocess.check_output(
('git', '-c', 'core.quotepath=false', 'ls-tree', '--full-tree', '-r', '--name-only', 'HEAD'),
text=True, cwd=checkout_path,
).split('\n')
if f.strip()
)
# ===== FILE utils =====
REMOVE = set()
def remove(path):
global REMOVE
REMOVE.add(path)
def actually_remove(checkout_path, namespace, collection):
global REMOVE
# load sanity/ignore.txt, the files being removed below need to be removed from ignore.txt too
sanity_ignore = read_lines_from_file(os.path.join(checkout_path, 'test/sanity/ignore.txt'))
new_sanity_ignore = defaultdict(list)
for ignore in sanity_ignore:
values = ignore.split(' ', 1)
new_sanity_ignore[values[0]].append(values[1])
# actually remove files we marked for removal
init_files = set()
for path in REMOVE:
actual_devel_path = os.path.relpath(path, checkout_path)
if actual_devel_path.startswith('lib/ansible/modules') and actual_devel_path.endswith('__init__.py'):
init_files.add(path)
continue
subprocess.check_call(
('git', 'rm', actual_devel_path),
cwd=checkout_path,
)
new_sanity_ignore.pop(actual_devel_path, None)
# process the __init__.py files from module dirs now that all files are removed,
# that way we can check if there are no modules left in the dirs they are in
# so we can remove __init__.py as well
for init in sorted(init_files, key=lambda x: len(x.split('/')), reverse=True):
if os.listdir(os.path.dirname(init)) != ['__init__.py']:
continue
actual_devel_path = os.path.relpath(init, checkout_path)
subprocess.check_call(
('git', 'rm', actual_devel_path),
cwd=checkout_path,
)
new_sanity_ignore.pop(actual_devel_path, None)
# save modified sanity/ignore.txt
res = ''
for filename, values in new_sanity_ignore.items():
for value in values:
# value contains '\n' which is preserved from the original file
res += '%s %s' % (filename, value)
write_text_into_file(os.path.join(checkout_path, 'test/sanity/ignore.txt'), res)
subprocess.check_call(('git', 'add', 'test/sanity/ignore.txt'), cwd=checkout_path)
# commit the changes
subprocess.check_call(('git', 'commit', '-m', 'Migrated to %s.%s' % (namespace, collection)), cwd=checkout_path)
def read_yaml_file(path):
with open(path, 'rb') as yaml_file:
return yaml.safe_load(yaml_file)
def read_ansible_yaml_file(path):
with open(path, 'rb') as yaml_file:
return AnsibleLoader(yaml_file.read(), file_name=path).get_single_data()
def write_yaml_into_file_as_is(path, data):
yaml_text = yaml.dump(data, allow_unicode=True, default_flow_style=False, sort_keys=False)
write_text_into_file(path, yaml_text)
def write_ansible_yaml_into_file_as_is(path, data):
yaml_text = yaml.dump(data, Dumper=AnsibleDumper, allow_unicode=True, default_flow_style=False, sort_keys=False)
write_text_into_file(path, yaml_text)
def read_text_from_file(path):
with open(path, 'r') as f:
return f.read()
def read_lines_from_file(path):
with open(path, 'r') as f:
return f.readlines()
def write_text_into_file(path, text):
with open(path, 'w') as f:
return f.write(text)
@contextlib.contextmanager
def working_directory(target_dir):
"""Temporary change dir to the target and change back on exit."""
current_working_dir = os.getcwd()
os.chdir(target_dir)
try:
yield os.getcwd()
finally:
os.chdir(current_working_dir)
# ===== SPEC utils =====
def load_spec_file(spec_file):
spec = read_yaml_file(spec_file) # TODO: capture yamlerror?
if not isinstance(spec, Mapping):
sys.exit("Invalid format for spec file, expected a dictionary and got %s" % type(spec))
elif not spec:
sys.exit("Cannot use spec file, ended up with empty spec")
return spec
def resolve_spec(spec, checkoutdir):
# TODO: add negation? entry: x/* \n entry: !x/base.py
for ns in spec.keys():
for coll in spec[ns].keys():
for ptype in spec[ns][coll].keys():
if ptype not in VALID_PLUGIN_TYPES:
raise Exception('Invalid plugin type: %s, expected one of %s' % (ptype, VALID_PLUGIN_TYPES))
plugin_base = os.path.join(checkoutdir, PLUGIN_EXCEPTION_PATHS.get(ptype, os.path.join('lib', 'ansible', 'plugins', ptype)))
replace_base = '%s/' % plugin_base
for entry in spec[ns][coll][ptype]:
if r'*' in entry or r'?' in entry:
files = glob.glob(os.path.join(plugin_base, entry))
if not files:
raise Exception('No matches for plugin type: %s, entry: %s. Searched in %s.' % (ptype, entry, os.path.join(plugin_base, entry)))
for fname in files:
if ptype != 'module_utils' and fname.endswith('__init__.py') or not os.path.isfile(fname):
continue
fname = fname.replace(replace_base, '')
spec[ns][coll][ptype].insert(0, fname)
# clean out glob entry
spec[ns][coll][ptype].remove(entry)
# ===== GET_PLUGINS utils =====
def get_plugin_collection(plugin_name, plugin_type, spec):
for ns in spec.keys():
for collection in spec[ns].keys():
if spec[ns][collection]: # avoid empty collections
plugins = spec[ns][collection].get(plugin_type, [])
if plugin_name + '.py' in plugins:
return ns, collection
# keep info
plugin_name = plugin_name.replace('/', '.')
logger.debug('Assuming "%s.%s " stays in core', plugin_type, plugin_name)
add_core(plugin_type, plugin_name.replace('/', '.'))
raise LookupError('Could not find "%s" named "%s" in any collection in the spec' % (plugin_type, plugin_name))
def get_plugins_from_collection(ns, collection, plugin_type, spec):
assert ns in spec
assert collection in spec[ns]
return [plugin.rsplit('/')[-1][:-3] for plugin in spec[ns][collection].get(plugin_type, [])]
def get_plugin_fqcn(namespace, collection, plugin_name):
return '%s.%s.%s' % (namespace, collection, plugin_name)
def get_rewritable_collections(namespace, spec):
return (collection for collection in spec[namespace].keys() if collection not in COLLECTION_SKIP_REWRITE)
# ===== REWRITE FUNCTIONS =====
def rewrite_class_property(mod_fst, collection, namespace, filename):
rewrite_map = {
'BecomeModule': 'name',
'CallbackModule': 'CALLBACK_NAME',
'Connection': 'transport',
'InventoryModule': 'NAME',
}
ignored_plugins = {
'become',
'callback',
'connection',
'inventory',
}
if all(f'plugins/{p}' not in filename for p in ignored_plugins):
return
for class_name, property_name in rewrite_map.items():
try:
val = (
mod_fst.
find('class', name=class_name).
find('name', value=property_name).parent.value
)
except AttributeError:
continue
try:
val.value = "'%s'" % get_plugin_fqcn(namespace,
collection,
val.to_python())
except ValueError as e:
# so this might be something like:
# transport = CONNECTION_TRANSPORT
add_manual_check(property_name, val.value, filename)
def rewrite_unit_tests_patch(mod_fst, collection, spec, namespace, args):
# FIXME duplicate code from imports rewrite
plugins_path = ('ansible_collections', namespace, collection, 'plugins')
tests_path = ('ansible_collections', namespace, collection, 'tests')
unit_tests_path = tests_path + ('unit', )
import_map = {
('ansible', 'modules'): plugins_path + ('modules', ),
('ansible', 'module_utils'): plugins_path + ('module_utils', ),
('ansible', 'plugins'): plugins_path,
('units', ): unit_tests_path,
}
patches = (
mod_fst('string',
lambda x:
'ansible.modules' in x.dumps() or
'ansible.module_utils' in x.dumps() or
'ansible.plugins' in x.dumps() or
'units' in x.dumps()
)
)
deps = []
for el in patches:
val = el.to_python().split('.')
for old, new in import_map.items():
token_length = len(old)
if tuple(val[:token_length]) != old:
continue
if val[0] == 'units':
val[:token_length] = new
el.value = "'%s'" % '.'.join(val)
continue
elif val[1] in ('modules', 'module_utils'):
plugin_type = val[1]
# 'ansible.modules.storage.netapp.na_ontap_nvme.NetAppONTAPNVMe.create_nvme'
# look for module name
for i in (len(val), -1, -2):
plugin_name = '/'.join(val[2:i])
try:
found_ns, found_coll = get_plugin_collection(plugin_name, plugin_type, spec)
break
except LookupError:
continue
else:
continue
elif val[1] == 'plugins':
# 'ansible.plugins.lookup.manifold.open_url'
try:
plugin_type = val[2]
plugin_name = val[3]
except IndexError:
# Not enough information to search for the plugin, safe to assume it's not for the rewrite
# e.g. 'ansible.plugins.inventory'
continue
try:
found_ns, found_coll = get_plugin_collection(plugin_name, plugin_type, spec)
except LookupError:
continue
else:
continue
if found_coll in COLLECTION_SKIP_REWRITE:
continue
if args.fail_on_core_rewrite:
raise RuntimeError('Rewriting to %s' % '.'.join(val))
val[:token_length] = new
if plugin_type == 'modules' and not args.preserve_module_subdirs:
plugin_subdirs_len = len(plugin_name.split('/')[:-1])
new_len = len(new)
del val[new_len:new_len+plugin_subdirs_len]
if (found_ns, found_coll) != (namespace, collection):
val[1] = found_ns
val[2] = found_coll
deps.append((found_ns, found_coll))
el.value = "'%s'" % '.'.join(val)
return deps
def rewrite_version_added(docs):
docs.pop('version_added', None)
if not isinstance(docs['options'], dict):
# lib/ansible/plugins/doc_fragments/emc.py:
# options': ['See respective platform section for more details'],
return
for option in docs['options']:
docs['options'][option].pop('version_added', None)
def rewrite_docs_fragments(docs, collection, spec, namespace, args):
fragments = docs.get('extends_documentation_fragment', [])
if not fragments:
return []
if not isinstance(fragments, list):
fragments = [fragments]
deps = []
new_fragments = []
for fragment in fragments:
# some doc_fragments use subsections (e.g. vmware.vcenter_documentation)
fragment_name, _dot, _rest = fragment.partition('.')
try:
fragment_namespace, fragment_collection = get_plugin_collection(fragment_name, 'doc_fragments', spec)
except LookupError:
# plugin not in spec, assuming it stays in core and leaving as is
new_fragments.append(fragment)
continue
if fragment_collection in COLLECTION_SKIP_REWRITE:
# skip rewrite
new_fragments.append(fragment)
continue
if fragment_collection.startswith('_'):
fragment_collection = fragment_collection[1:]
new_fragment = get_plugin_fqcn(fragment_namespace, fragment_collection, fragment)
if args.fail_on_core_rewrite:
raise RuntimeError('Rewriting to %s' % new_fragment)
new_fragments.append(new_fragment)
if (namespace, collection) != (fragment_namespace, fragment_collection):
deps.append((fragment_namespace, fragment_collection))
docs['extends_documentation_fragment'] = new_fragments
return deps
def rewrite_plugin_documentation(mod_fst, collection, spec, namespace, args):
try:
doc_val = (
mod_fst.
find_all('assignment').
find('name', value='DOCUMENTATION').
parent.
value
)
except AttributeError:
raise LookupError('No DOCUMENTATION found')
docs_parsed = yaml.safe_load(doc_val.to_python().strip('\n'))
deps = rewrite_docs_fragments(docs_parsed, collection, spec, namespace, args)
rewrite_version_added(docs_parsed)
doc_str_tmpl = RAW_STR_TMPL if doc_val.type == 'raw_string' else STR_TMPL
# `doc_val` holds a baron representation of the string node
# of type 'string' or 'raw_string'. Updating its `.value`
# via assigning the new one replaces the node in FST.
# Also, in order to generate a string or raw-string literal,
# we need to wrap it with a corresponding pair of quotes.
# If we don't do this, we'd generate the following Python code
# ```
# DOCUMENTATION = some string value
# ```
# instead of the correct
# ```
# DOCUMENTATION = r'''some string value'''
# ```
# or
# ```
# DOCUMENTATION = '''some string value'''
# ```
doc_val.value = doc_str_tmpl.format(
str_val=yaml.dump(docs_parsed, allow_unicode=True, default_flow_style=False, sort_keys=False),
)
return deps
def rewrite_imports(mod_fst, collection, spec, namespace, args):
"""Rewrite imports map."""
plugins_path = ('ansible_collections', namespace, collection, 'plugins')
tests_path = ('ansible_collections', namespace, collection, 'tests')
unit_tests_path = tests_path + ('unit', )
import_map = {
('ansible', 'modules'): plugins_path + ('modules', ),
('ansible', 'module_utils'): plugins_path + ('module_utils', ),
('ansible', 'plugins'): plugins_path,
('units', ): unit_tests_path,
}
return rewrite_imports_in_fst(mod_fst, import_map, collection, spec, namespace, args)
def match_import_src(imp_src, import_map):
"""Find a replacement map entry matching the current import."""
try:
imp_src_tuple = tuple(t.value for t in imp_src)
except AttributeError as e:
# AttributeError("EllipsisNode instance has no attribute 'value' and 'value' is not a valid identifier of another node")
# lib/ansible/modules/system/setup.py:
# from ...module_utils.basic import AnsibleModule
logger.exception(e)
raise LookupError
for old_imp, new_imp in import_map.items():
token_length = len(old_imp)
if imp_src_tuple[:token_length] != old_imp:
continue
return token_length, new_imp
raise LookupError(f"Couldn't find a replacement for {imp_src!s}")
def rewrite_imports_in_fst(mod_fst, import_map, collection, spec, namespace, args):
"""Replace imports in the python module FST."""
deps = []
for imp in mod_fst.find_all(('import', 'from_import')):
imp_src = imp.value
if imp.type == 'import':
imp_src = imp_src[0].value
try:
token_length, exchange = match_import_src(imp_src, import_map)
except LookupError:
continue # no matching imports
if not imp.find('name', value='g:*module_utils*') and imp.find_all('name_as_name', value='g:*Base*'):
# from ansible.plugins.lookup import LookupBase
# NOT 'from ansible.module_utils.azure_rm_common import AzureRMModuleBase'
continue # Skip imports of Base classes
if imp.find('name_as_name', value='g:*loader*'):
continue
if imp.find('name_as_name', value=('AnsiblePlugin', 'PluginLoader')):
# from ansible.plugins import AnsiblePlugin
# from ansible.plugins.loader import PluginLoader
continue
if imp_src[0].value == 'units':
imp_src[:token_length] = exchange # replace the import
continue
elif imp_src[1].value == 'module_utils':
plugin_type = 'module_utils'
try:
plugin_name = '/'.join([t.value for t in imp_src[token_length:]] + [imp.targets[0].value])
except AttributeError:
plugin_name = '/'.join(t.value for t in imp_src[token_length:])
if not plugin_name:
# 'from ansible.module_utils import distro'
plugin_name = imp.targets[0].value
# NOTE multiple targets? - git grep says there is not such case now
# NOTE 'from ansible.module_utils import $module as $alias'? - git grep says there is not such case now
elif imp_src[1].value == 'plugins':
try:
plugin_type = imp_src[2].value
plugin_name = imp_src[3].value
except IndexError:
if len(getattr(imp, 'targets', [])) == 1:
# from ansible.plugins.connection import winrm
plugin_name = imp.targets[0].value
else:
logger.error('Could not get plugin type or name from ' + str(imp) + '. Is this expected?')
continue
elif imp_src[1].value == 'modules':
# in unit tests
plugin_type = 'modules'
try:
# from ansible.modules.network.nxos import nxos_bgp
plugin_name = '/'.join([t.value for t in imp_src[token_length:]] + [imp.targets[0].value])
except AttributeError:
# import ansible.modules.cloud.amazon.aws_api_gateway as agw
plugin_name = '/'.join(t.value for t in imp_src[token_length:])
else:
raise Exception('BUG: Could not process import: ' + str(imp))
try:
plugin_namespace, plugin_collection = get_plugin_collection(plugin_name, plugin_type, spec)
except LookupError:
if plugin_type not in ('modules', 'module_utils'):
# plugin not in spec, assuming it stays in core and skipping
continue
# from ansible.modules.cloud.amazon.aws_netapp_cvs_FileSystems import AwsCvsNetappFileSystem as fileSystem_module
# in this case aws_netapp_cvs_FileSystems is the module, not AwsCvsNetappFileSystem
try:
plugin_name = '/'.join(plugin_name.split('/')[:-1])
plugin_namespace, plugin_collection = get_plugin_collection(plugin_name, plugin_type, spec)
except LookupError as e:
# plugin not in spec, assuming it stays in core and skipping
continue
if plugin_collection in COLLECTION_SKIP_REWRITE:
# skip rewrite
continue
if args.fail_on_core_rewrite:
raise RuntimeError('Rewriting to %s.%s.%s' % (plugin_namespace, plugin_collection, plugin_name))
if plugin_collection.startswith('_'):
plugin_collection = plugin_collection[1:]
imp_src[:token_length] = exchange # replace the import
if plugin_type == 'modules' and not args.preserve_module_subdirs:
plugin_subdirs_len = len(plugin_name.split('/')[:-1])
exchange_len = len(exchange)
del imp_src[exchange_len:exchange_len+plugin_subdirs_len]
if (plugin_namespace, plugin_collection) != (namespace, collection):
imp_src[1] = plugin_namespace
imp_src[2] = plugin_collection
deps.append((plugin_namespace, plugin_collection))
return deps
def rewrite_py(src, dest, collection, spec, namespace, args):
mod_src_text, mod_fst = read_module_txt_n_fst(src)
import_deps = rewrite_imports(mod_fst, collection, spec, namespace, args)
try:
docs_deps = rewrite_plugin_documentation(mod_fst, collection, spec, namespace, args)
except LookupError as err:
docs_deps = []
logger.debug('%s in %s', err, src)
rewrite_class_property(mod_fst, collection, namespace, dest)
plugin_data_new = mod_fst.dumps()
if mod_src_text != plugin_data_new:
logger.info('Rewriting plugin references in %s', dest)
write_text_into_file(dest, plugin_data_new)
return (import_deps, docs_deps)
def read_module_txt_n_fst(path):
"""Parse module source code in form of Full Syntax Tree."""
mod_src_text = read_text_from_file(path)
try:
return mod_src_text, redbaron.RedBaron(mod_src_text)
except ParsingError:
logger.exception('failed parsing on %s', mod_src_text)
raise
def inject_init_into_tree(target_dir):
for initpath in (
os.path.join(dp, '__init__.py')
for dp, dn, fn in os.walk(target_dir)
if '__init__.py' not in fn
# and any(f.endwith('.py') for f in fn)
):
write_text_into_file(initpath, '')
def inject_readme_into_collection(collection_dir, *, ctx):
"""Insert a ``README.md`` file into the collection dir.
The ``README.md.tmpl`` resource template file contains a title
and a GitHub Actions Workflow badge.
"""
target_file = 'README.md'
render_template_into(
f'{target_file}.tmpl',
ctx,
os.path.join(collection_dir, target_file),
)
def inject_github_actions_workflow_into_collection(collection_dir, *, ctx):
"""Insert GitHub Actions Workflow config into collection repo."""
target_file = 'collection-continuous-integration.yml'
workflows_dir = os.path.join(collection_dir, '.github', 'workflows')
os.makedirs(workflows_dir, exist_ok=True)
render_template_into(
f'{target_file}.tmpl',
ctx,
os.path.join(workflows_dir, target_file),
)
def inject_gitignore_into_collection(collection_dir):
"""Insert a ``.gitignore`` file into the collection dir.
The ``.gitignore`` resource file has been generated
using the following command:
curl -sL https://www.gitignore.io/api/git%2Clinux%2Cpydev%2Cpython%2Cwindows%2Cpycharm%2Ball%2Cjupyternotebook%2Cvim%2Cwebstorm%2Cemacs%2Cdotenv > resources/.gitignore.tmpl
"""
gitignore_resource_path = os.path.join(
os.path.dirname(__file__),
'resources',
'.gitignore.tmpl',
)
shutil.copy(
gitignore_resource_path,
os.path.join(collection_dir, '.gitignore'),
)
def inject_gitignore_into_tests(collection_dir):
"""Generate a ``.gitignore`` file for the collection tests dir."""
os.makedirs(os.path.join(collection_dir, 'tests'), exist_ok=True)
write_text_into_file(
os.path.join(collection_dir, 'tests', '.gitignore'),
textwrap.dedent('''
output/
''').lstrip('\n'),
)
def generate_converted_ignore_contents(original_ignore_contents, file_map):
"""Emit lines for the converted sanity test ignore file."""
for line in original_ignore_contents.splitlines():
file_path, sep, ignored_rules = line.partition(' ')
with contextlib.suppress(KeyError):
yield sep.join((file_map[file_path], ignored_rules))
def inject_ignore_into_sanity_tests(
checkout_path, collection_dir, migrated_files_map,
):
"""Inject sanity test ignore lists into collection sanity tests."""
coll_sanity_tests_dir = os.path.join(collection_dir, 'tests', 'sanity')
original_ignore_contents = read_text_from_file(
os.path.join(checkout_path, 'test', 'sanity', 'ignore.txt'),
)
converted_ignore_contents = '\n'.join(
generate_converted_ignore_contents(
original_ignore_contents,
migrated_files_map,
),
)
if not converted_ignore_contents:
return
os.makedirs(coll_sanity_tests_dir, exist_ok=True)
write_text_into_file( # PyPI
os.path.join(coll_sanity_tests_dir, 'ignore-2.9.txt'),
converted_ignore_contents,
)
write_text_into_file( # devel
os.path.join(coll_sanity_tests_dir, 'ignore-2.10.txt'),
converted_ignore_contents,
)
def inject_requirements_into_unit_tests(checkout_path, collection_dir):
"""Inject unit tests dependencies into collection."""
coll_unit_tests_dir = os.path.join(collection_dir, 'tests', 'unit')
original_unit_tests_req_file = os.path.join(
checkout_path, 'test', 'units', 'requirements.txt',
)
os.makedirs(coll_unit_tests_dir, exist_ok=True)
shutil.copy(original_unit_tests_req_file, coll_unit_tests_dir)
logger.info('Unit tests deps injected into collection')
def inject_requirements_into_sanity_tests(checkout_path, collection_dir):
"""Inject sanity tests Python dependencies into collection."""
coll_sanity_tests_dir = os.path.join(
collection_dir, 'tests', 'sanity',
)
original_sanity_tests_req_file = os.path.join(
checkout_path, 'test', 'sanity', 'requirements.txt',
)
os.makedirs(coll_sanity_tests_dir, exist_ok=True)
shutil.copy(original_sanity_tests_req_file, coll_sanity_tests_dir)
logger.info('Sanity tests deps injected into collection')
def create_unit_tests_copy_map(checkout_path, collection_dir, plugin_type, plugin):
"""Find all unit tests and related artifacts for the given plugin.
Return the copy map.
"""
type_subdir = (
plugin_type
if plugin_type in ('modules', 'module_utils')
else os.path.join('plugins', plugin_type)
)
unit_tests_relative_root = os.path.join('test', 'units')
collection_unit_tests_relative_root = os.path.join('tests', 'unit')
# Narrow down the search area
type_base_subdir = os.path.join(
checkout_path, unit_tests_relative_root, type_subdir,
)
# Figure out what to copy and where
copy_map = {}
# Find all test modules with the same ending as the current plugin
plugin_dir, plugin_mod = os.path.split(plugin)
matching_test_modules = set(glob.glob(os.path.join(
type_base_subdir,
plugin_dir,
f'*{plugin_mod}',
)))
# plugin_mod might also be a directory, scan subdirs
plugin_mod = os.path.splitext(plugin_mod)[0]
matching_test_modules = matching_test_modules.union(set(glob.glob(os.path.join(
type_base_subdir,
plugin_dir,
f'*{plugin_mod}/**',
), recursive=True)))
matching_test_modules = set(f for f in matching_test_modules if not os.path.isdir(f))
# Path(matching_test_modules[0]).relative_to(Path(checkout_path))
# os.path.relpath(matching_test_modules[0], checkout_path)
if not matching_test_modules:
logger.info('No unit tests matching %s/%s found', plugin_type, plugin)
return copy_map
def find_up_the_tree(target_path):
"""Find conftest.py in the parent test dirs."""
needle_filename = 'conftest.py'
tests_root = os.path.join(checkout_path, unit_tests_relative_root)
relative_target_path = os.path.relpath(target_path, tests_root)
if relative_target_path.startswith('..'):
raise ValueError(
f'`{target_path}` is not a part of `{tests_root}`',
)
logger.info(
'Locating parent %s '
'for %s...',
needle_filename,
target_path,
)
while relative_target_path:
relative_target_path, _ = os.path.split(relative_target_path)
target_file = os.path.join(
tests_root,
relative_target_path,
needle_filename,
)
if not os.path.isfile(target_file):
continue
logger.info(
'Located %s...',
target_file
)
yield target_file
# Discover constest.py's from
# parent dirs:
conftest_modules = set(
p
for m in matching_test_modules.copy()
for p in find_up_the_tree(m)
)
def traverse_dir(path, relative_to):
rel_path = os.path.join(relative_to, path)
if not os.path.isdir(rel_path):
return {path}
matching_files = itertools.chain(
glob.iglob(
os.path.join(rel_path, '.**'),
recursive=True,
),
glob.iglob(
os.path.join(rel_path, '**'),
recursive=True,
),
)
return set(
os.path.relpath(p, relative_to)
for p in matching_files
if not os.path.isdir(p)
)
def replace_path_prefix(path):
return os.path.join(
collection_unit_tests_relative_root,
os.path.relpath(path, unit_tests_relative_root),
)
# Inject unit test helper packages
# TODO: figure out the bug with path maps
compat_mock_helpers = (
(
src_f,
replace_path_prefix(src_f),
)
for hd in {'compat', 'mock', 'modules/utils.py'}
for src_f in traverse_dir(
os.path.join(unit_tests_relative_root, hd),
checkout_path,
)
)
for src_f, dst_f in compat_mock_helpers:
copy_map[src_f] = dst_f
def discover_file_migrations(paths, *, find_related=False):
"""Generate the migration map for given paths.
Optionally, traverse siblings.
"""
nonlocal unit_tests_relative_root
for td, tm in map(os.path.split, paths):
relative_td = os.path.relpath(td, checkout_path)
test_artifact_path = os.path.join(relative_td, tm)
yield (
test_artifact_path,
replace_path_prefix(test_artifact_path),
)
if not find_related:
continue
module_type = os.path.relpath(
relative_td,
unit_tests_relative_root,
)
if module_type in {'module_utils'}:
"""Top-level dir of the module_utils unit tests."""
continue