forked from apache/airflow
-
Notifications
You must be signed in to change notification settings - Fork 15
/
prepare_provider_packages.py
executable file
·2400 lines (2086 loc) · 88.9 KB
/
prepare_provider_packages.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
# pylint: disable=wrong-import-order
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Setup.py for the Provider packages of Airflow project."""
import collections
import difflib
import glob
import importlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
from contextlib import contextmanager
from copy import deepcopy
from datetime import datetime, timedelta
from enum import Enum
from functools import lru_cache
from os.path import dirname, relpath
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Set, Tuple, Type
import click
import jsonschema
import yaml
from github import Github, PullRequest, UnknownObjectException
from packaging.version import Version
from rich import print
from rich.console import Console
from rich.progress import Progress
from rich.syntax import Syntax
ALL_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"]
try:
from yaml import CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader # noqa
INITIAL_CHANGELOG_CONTENT = """
.. Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
.. http://www.apache.org/licenses/LICENSE-2.0
.. Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
Changelog
---------
1.0.0
.....
Initial version of the provider.
"""
HTTPS_REMOTE = "apache-https-for-providers"
HEAD_OF_HTTPS_REMOTE = f"{HTTPS_REMOTE}/main"
MY_DIR_PATH = os.path.dirname(__file__)
SOURCE_DIR_PATH = os.path.abspath(os.path.join(MY_DIR_PATH, os.pardir, os.pardir))
AIRFLOW_PATH = os.path.join(SOURCE_DIR_PATH, "airflow")
PROVIDERS_PATH = os.path.join(AIRFLOW_PATH, "providers")
DOCUMENTATION_PATH = os.path.join(SOURCE_DIR_PATH, "docs")
TARGET_PROVIDER_PACKAGES_PATH = os.path.join(SOURCE_DIR_PATH, "provider_packages")
GENERATED_AIRFLOW_PATH = os.path.join(TARGET_PROVIDER_PACKAGES_PATH, "airflow")
GENERATED_PROVIDERS_PATH = os.path.join(GENERATED_AIRFLOW_PATH, "providers")
PROVIDER_RUNTIME_DATA_SCHEMA_PATH = os.path.join(SOURCE_DIR_PATH, "airflow", "provider_info.schema.json")
sys.path.insert(0, SOURCE_DIR_PATH)
# those imports need to come after the above sys.path.insert to make sure that Airflow
# sources are importable without having to add the airflow sources to the PYTHONPATH before
# running the script
import tests.deprecated_classes # noqa # isort:skip
from dev.import_all_classes import import_all_classes # noqa # isort:skip
from setup import PROVIDERS_REQUIREMENTS, PREINSTALLED_PROVIDERS # noqa # isort:skip
# Note - we do not test protocols as they are not really part of the official API of
# Apache Airflow
logger = logging.getLogger(__name__) # noqa
PY3 = sys.version_info[0] == 3
@click.group(context_settings={'help_option_names': ['-h', '--help'], 'max_content_width': 500})
def cli():
...
option_git_update = click.option(
'--git-update/--no-git-update',
default=True,
is_flag=True,
help=f"If the git remote {HTTPS_REMOTE} already exists, don't try to update it",
)
option_interactive = click.option(
'--interactive/--non-interactive',
default=True,
is_flag=True,
help="If the script should interactively ask the user what to do in case of doubt",
)
option_version_suffix = click.option(
"--version-suffix",
metavar="suffix",
help=textwrap.dedent(
"""
adds version suffix to version of the packages.
only useful when generating rc candidates for pypi."""
),
)
option_verbose = click.option(
"--verbose",
is_flag=True,
help="Print verbose information about performed steps",
)
option_force = click.option(
"--force",
is_flag=True,
help="Forces regeneration of already generated documentation",
)
argument_package_id = click.argument('package_id')
argument_changelog_files = click.argument('changelog_files', nargs=-1)
argument_package_ids = click.argument('package_ids', nargs=-1)
@contextmanager
def with_group(title):
"""
If used in GitHub Action, creates an expandable group in the GitHub Action log.
Otherwise, display simple text groups.
For more information, see:
https://docs.github.com/en/free-pro-team@latest/actions/reference/workflow-commands-for-github-actions#grouping-log-lines
"""
if os.environ.get('GITHUB_ACTIONS', 'false') != "true":
print("[blue]" + "#" * 10 + ' ' + title + ' ' + "#" * 10 + "[/]")
yield
return
print(f"::group::{title}")
yield
print("::endgroup::")
class EntityType(Enum):
Operators = "Operators"
Transfers = "Transfers"
Sensors = "Sensors"
Hooks = "Hooks"
Secrets = "Secrets"
class EntityTypeSummary(NamedTuple):
entities: Set[str]
new_entities: List[str]
moved_entities: Dict[str, str]
new_entities_table: str
moved_entities_table: str
wrong_entities: List[Tuple[type, str]]
class VerifiedEntities(NamedTuple):
all_entities: Set[str]
wrong_entities: List[Tuple[type, str]]
class ProviderPackageDetails(NamedTuple):
provider_package_id: str
full_package_name: str
pypi_package_name: str
source_provider_package_path: str
documentation_provider_package_path: str
provider_description: str
versions: List[str]
excluded_python_versions: List[str]
ENTITY_NAMES = {
EntityType.Operators: "Operators",
EntityType.Transfers: "Transfer Operators",
EntityType.Sensors: "Sensors",
EntityType.Hooks: "Hooks",
EntityType.Secrets: "Secrets",
}
TOTALS: Dict[EntityType, List[int]] = {
EntityType.Operators: [0, 0],
EntityType.Hooks: [0, 0],
EntityType.Sensors: [0, 0],
EntityType.Transfers: [0, 0],
EntityType.Secrets: [0, 0],
}
OPERATORS_PATTERN = r".*Operator$"
SENSORS_PATTERN = r".*Sensor$"
HOOKS_PATTERN = r".*Hook$"
SECRETS_PATTERN = r".*Backend$"
TRANSFERS_PATTERN = r".*To[A-Z0-9].*Operator$"
WRONG_TRANSFERS_PATTERN = r".*Transfer$|.*TransferOperator$"
ALL_PATTERNS = {
OPERATORS_PATTERN,
SENSORS_PATTERN,
HOOKS_PATTERN,
SECRETS_PATTERN,
TRANSFERS_PATTERN,
WRONG_TRANSFERS_PATTERN,
}
EXPECTED_SUFFIXES: Dict[EntityType, str] = {
EntityType.Operators: "Operator",
EntityType.Hooks: "Hook",
EntityType.Sensors: "Sensor",
EntityType.Secrets: "Backend",
EntityType.Transfers: "Operator",
}
def get_source_airflow_folder() -> str:
"""
Returns source directory for whole airflow (from the main airflow project).
:return: the folder path
"""
return os.path.abspath(SOURCE_DIR_PATH)
def get_source_providers_folder() -> str:
"""
Returns source directory for providers (from the main airflow project).
:return: the folder path
"""
return os.path.join(get_source_airflow_folder(), "airflow", "providers")
def get_target_folder() -> str:
"""
Returns target directory for providers (in the provider_packages folder)
:return: the folder path
"""
return os.path.abspath(os.path.join(dirname(__file__), os.pardir, os.pardir, "provider_packages"))
def get_target_providers_folder() -> str:
"""
Returns target directory for providers (in the provider_packages folder)
:return: the folder path
"""
return os.path.abspath(os.path.join(get_target_folder(), "airflow", "providers"))
def get_target_providers_package_folder(provider_package_id: str) -> str:
"""
Returns target package folder based on package_id
:return: the folder path
"""
return os.path.join(get_target_providers_folder(), *provider_package_id.split("."))
DEPENDENCIES_JSON_FILE = os.path.join(PROVIDERS_PATH, "dependencies.json")
MOVED_ENTITIES: Dict[EntityType, Dict[str, str]] = {
EntityType.Operators: {value[0]: value[1] for value in tests.deprecated_classes.OPERATORS},
EntityType.Sensors: {value[0]: value[1] for value in tests.deprecated_classes.SENSORS},
EntityType.Hooks: {value[0]: value[1] for value in tests.deprecated_classes.HOOKS},
EntityType.Secrets: {value[0]: value[1] for value in tests.deprecated_classes.SECRETS},
EntityType.Transfers: {value[0]: value[1] for value in tests.deprecated_classes.TRANSFERS},
}
def get_pip_package_name(provider_package_id: str) -> str:
"""
Returns PIP package name for the package id.
:param provider_package_id: id of the package
:return: the name of pip package
"""
return "apache-airflow-providers-" + provider_package_id.replace(".", "-")
def get_wheel_package_name(provider_package_id: str) -> str:
"""
Returns PIP package name for the package id.
:param provider_package_id: id of the package
:return: the name of pip package
"""
return "apache_airflow_providers_" + provider_package_id.replace(".", "_")
def get_long_description(provider_package_id: str) -> str:
"""
Gets long description of the package.
:param provider_package_id: package id
:return: content of the description: README file
"""
package_folder = get_target_providers_package_folder(provider_package_id)
readme_file = os.path.join(package_folder, "README.md")
if not os.path.exists(readme_file):
return ""
with open(readme_file, encoding='utf-8') as file:
readme_contents = file.read()
copying = True
long_description = ""
for line in readme_contents.splitlines(keepends=True):
if line.startswith("**Table of contents**"):
copying = False
continue
header_line = "## Provider package"
if line.startswith(header_line):
copying = True
if copying:
long_description += line
return long_description
def get_install_requirements(provider_package_id: str) -> List[str]:
"""
Returns install requirements for the package.
:param provider_package_id: id of the provider package
:return: install requirements of the package
"""
dependencies = PROVIDERS_REQUIREMENTS[provider_package_id]
provider_yaml = get_provider_yaml(provider_package_id)
install_requires = []
if "additional-dependencies" in provider_yaml:
install_requires = provider_yaml['additional-dependencies']
install_requires.extend(dependencies)
return install_requires
def get_setup_requirements() -> List[str]:
"""
Returns setup requirements (common for all package for now).
:return: setup requirements
"""
return ['setuptools', 'wheel']
def get_package_extras(provider_package_id: str) -> Dict[str, List[str]]:
"""
Finds extras for the package specified.
:param provider_package_id: id of the package
"""
if provider_package_id == 'providers':
return {}
with open(DEPENDENCIES_JSON_FILE) as dependencies_file:
cross_provider_dependencies: Dict[str, List[str]] = json.load(dependencies_file)
extras_dict = (
{
module: [get_pip_package_name(module)]
for module in cross_provider_dependencies[provider_package_id]
}
if cross_provider_dependencies.get(provider_package_id)
else {}
)
provider_yaml_dict = get_provider_yaml(provider_package_id)
additional_extras = provider_yaml_dict.get('additional-extras')
if additional_extras:
for key in additional_extras:
if key in extras_dict:
extras_dict[key].append(additional_extras[key])
else:
extras_dict[key] = additional_extras[key]
return extras_dict
def get_provider_packages() -> List[str]:
"""
Returns all provider packages.
"""
return list(PROVIDERS_REQUIREMENTS.keys())
def is_imported_from_same_module(the_class: str, imported_name: str) -> bool:
"""
Is the class imported from another module?
:param the_class: the class object itself
:param imported_name: name of the imported class
:return: true if the class was imported from another module
"""
return ".".join(imported_name.split(".")[:-1]) == the_class.__module__
def is_example_dag(imported_name: str) -> bool:
"""
Is the class an example_dag class?
:param imported_name: name where the class is imported from
:return: true if it is an example_dags class
"""
return ".example_dags." in imported_name
def is_from_the_expected_base_package(the_class: Type, expected_package: str) -> bool:
"""
Returns true if the class is from the package expected.
:param the_class: the class object
:param expected_package: package expected for the class
:return:
"""
return the_class.__module__.startswith(expected_package)
def inherits_from(the_class: Type, expected_ancestor: Optional[Type] = None) -> bool:
"""
Returns true if the class inherits (directly or indirectly) from the class specified.
:param the_class: The class to check
:param expected_ancestor: expected class to inherit from
:return: true is the class inherits from the class expected
"""
if expected_ancestor is None:
return False
import inspect
mro = inspect.getmro(the_class)
return the_class is not expected_ancestor and expected_ancestor in mro
def is_class(the_class: Type) -> bool:
"""
Returns true if the object passed is a class
:param the_class: the class to pass
:return: true if it is a class
"""
import inspect
return inspect.isclass(the_class)
def package_name_matches(the_class: Type, expected_pattern: Optional[str] = None) -> bool:
"""
In case expected_pattern is set, it checks if the package name matches the pattern.
.
:param the_class: imported class
:param expected_pattern: the pattern that should match the package
:return: true if the expected_pattern is None or the pattern matches the package
"""
return expected_pattern is None or re.match(expected_pattern, the_class.__module__) is not None
def find_all_entities(
imported_classes: List[str],
base_package: str,
ancestor_match: Type,
sub_package_pattern_match: str,
expected_class_name_pattern: str,
unexpected_class_name_patterns: Set[str],
exclude_class_type: Optional[Type] = None,
false_positive_class_names: Optional[Set[str]] = None,
) -> VerifiedEntities:
"""
Returns set of entities containing all subclasses in package specified.
:param imported_classes: entities imported from providers
:param base_package: base package name where to start looking for the entities
:param sub_package_pattern_match: this string is expected to appear in the sub-package name
:param ancestor_match: type of the object the method looks for
:param expected_class_name_pattern: regexp of class name pattern to expect
:param unexpected_class_name_patterns: set of regexp of class name pattern that are not expected
:param exclude_class_type: exclude class of this type (Sensor are also Operators so
they should be excluded from the list)
:param false_positive_class_names: set of class names that are wrongly recognised as badly named
"""
found_entities: Set[str] = set()
wrong_entities: List[Tuple[type, str]] = []
for imported_name in imported_classes:
module, class_name = imported_name.rsplit(".", maxsplit=1)
the_class = getattr(importlib.import_module(module), class_name)
if (
is_class(the_class=the_class)
and not is_example_dag(imported_name=imported_name)
and is_from_the_expected_base_package(the_class=the_class, expected_package=base_package)
and is_imported_from_same_module(the_class=the_class, imported_name=imported_name)
and inherits_from(the_class=the_class, expected_ancestor=ancestor_match)
and not inherits_from(the_class=the_class, expected_ancestor=exclude_class_type)
and package_name_matches(the_class=the_class, expected_pattern=sub_package_pattern_match)
):
if not false_positive_class_names or class_name not in false_positive_class_names:
if not re.match(expected_class_name_pattern, class_name):
wrong_entities.append(
(
the_class,
f"The class name {class_name} is wrong. "
f"It should match {expected_class_name_pattern}",
)
)
continue
if unexpected_class_name_patterns:
for unexpected_class_name_pattern in unexpected_class_name_patterns:
if re.match(unexpected_class_name_pattern, class_name):
wrong_entities.append(
(
the_class,
f"The class name {class_name} is wrong. "
f"It should not match {unexpected_class_name_pattern}",
)
)
continue
found_entities.add(imported_name)
return VerifiedEntities(all_entities=found_entities, wrong_entities=wrong_entities)
def convert_new_classes_to_table(
entity_type: EntityType, new_entities: List[str], full_package_name: str
) -> str:
"""
Converts new entities tp a markdown table.
:param entity_type: list of entities to convert to markup
:param new_entities: list of new entities
:param full_package_name: name of the provider package
:return: table of new classes
"""
from tabulate import tabulate
headers = [f"New Airflow 2.0 {entity_type.value.lower()}: `{full_package_name}` package"]
table = [(get_class_code_link(full_package_name, class_name, "main"),) for class_name in new_entities]
return tabulate(table, headers=headers, tablefmt="pipe")
def convert_moved_classes_to_table(
entity_type: EntityType,
moved_entities: Dict[str, str],
full_package_name: str,
) -> str:
"""
Converts moved entities to a markdown table
:param entity_type: type of entities -> operators, sensors etc.
:param moved_entities: dictionary of moved entities `to -> from`
:param full_package_name: name of the provider package
:return: table of moved classes
"""
from tabulate import tabulate
headers = [
f"Airflow 2.0 {entity_type.value.lower()}: `{full_package_name}` package",
"Airflow 1.10.* previous location (usually `airflow.contrib`)",
]
table = [
(
get_class_code_link(full_package_name, to_class, "main"),
get_class_code_link("airflow", moved_entities[to_class], "v1-10-stable"),
)
for to_class in sorted(moved_entities.keys())
]
return tabulate(table, headers=headers, tablefmt="pipe")
def get_details_about_classes(
entity_type: EntityType,
entities: Set[str],
wrong_entities: List[Tuple[type, str]],
full_package_name: str,
) -> EntityTypeSummary:
"""
Splits the set of entities into new and moved, depending on their presence in the dict of objects
retrieved from the test_contrib_to_core. Updates all_entities with the split class.
:param entity_type: type of entity (Operators, Hooks etc.)
:param entities: set of entities found
:param wrong_entities: wrong entities found for that type
:param full_package_name: full package name
:return:
"""
dict_of_moved_classes = MOVED_ENTITIES[entity_type]
new_entities = []
moved_entities = {}
for obj in entities:
if obj in dict_of_moved_classes:
moved_entities[obj] = dict_of_moved_classes[obj]
del dict_of_moved_classes[obj]
else:
new_entities.append(obj)
new_entities.sort()
TOTALS[entity_type][0] += len(new_entities)
TOTALS[entity_type][1] += len(moved_entities)
return EntityTypeSummary(
entities=entities,
new_entities=new_entities,
moved_entities=moved_entities,
new_entities_table=convert_new_classes_to_table(
entity_type=entity_type,
new_entities=new_entities,
full_package_name=full_package_name,
),
moved_entities_table=convert_moved_classes_to_table(
entity_type=entity_type,
moved_entities=moved_entities,
full_package_name=full_package_name,
),
wrong_entities=wrong_entities,
)
def strip_package_from_class(base_package: str, class_name: str) -> str:
"""
Strips base package name from the class (if it starts with the package name).
"""
if class_name.startswith(base_package):
return class_name[len(base_package) + 1 :]
else:
return class_name
def convert_class_name_to_url(base_url: str, class_name) -> str:
"""
Converts the class name to URL that the class can be reached
:param base_url: base URL to use
:param class_name: name of the class
:return: URL to the class
"""
return base_url + os.path.sep.join(class_name.split(".")[:-1]) + ".py"
def get_class_code_link(base_package: str, class_name: str, git_tag: str) -> str:
"""
Provides markdown link for the class passed as parameter.
:param base_package: base package to strip from most names
:param class_name: name of the class
:param git_tag: tag to use for the URL link
:return: URL to the class
"""
url_prefix = f'https://github.com/apache/airflow/blob/{git_tag}/'
return (
f'[{strip_package_from_class(base_package, class_name)}]'
f'({convert_class_name_to_url(url_prefix, class_name)})'
)
def print_wrong_naming(entity_type: EntityType, wrong_classes: List[Tuple[type, str]]):
"""
Prints wrong entities of a given entity type if there are any
:param entity_type: type of the class to print
:param wrong_classes: list of wrong entities
"""
if wrong_classes:
print(f"\n[red]There are wrongly named entities of type {entity_type}:[/]\n", file=sys.stderr)
for wrong_entity_type, message in wrong_classes:
print(f"{wrong_entity_type}: {message}", file=sys.stderr)
def get_package_class_summary(
full_package_name: str, imported_classes: List[str]
) -> Dict[EntityType, EntityTypeSummary]:
"""
Gets summary of the package in the form of dictionary containing all types of entities
:param full_package_name: full package name
:param imported_classes: entities imported_from providers
:return: dictionary of objects usable as context for JINJA2 templates - or None if there are some errors
"""
from airflow.hooks.base import BaseHook
from airflow.models.baseoperator import BaseOperator
from airflow.secrets import BaseSecretsBackend
from airflow.sensors.base import BaseSensorOperator
all_verified_entities: Dict[EntityType, VerifiedEntities] = {
EntityType.Operators: find_all_entities(
imported_classes=imported_classes,
base_package=full_package_name,
sub_package_pattern_match=r".*\.operators\..*",
ancestor_match=BaseOperator,
expected_class_name_pattern=OPERATORS_PATTERN,
unexpected_class_name_patterns=ALL_PATTERNS - {OPERATORS_PATTERN},
exclude_class_type=BaseSensorOperator,
false_positive_class_names={
'CloudVisionAddProductToProductSetOperator',
'CloudDataTransferServiceGCSToGCSOperator',
'CloudDataTransferServiceS3ToGCSOperator',
'BigQueryCreateDataTransferOperator',
'CloudTextToSpeechSynthesizeOperator',
'CloudSpeechToTextRecognizeSpeechOperator',
},
),
EntityType.Sensors: find_all_entities(
imported_classes=imported_classes,
base_package=full_package_name,
sub_package_pattern_match=r".*\.sensors\..*",
ancestor_match=BaseSensorOperator,
expected_class_name_pattern=SENSORS_PATTERN,
unexpected_class_name_patterns=ALL_PATTERNS - {OPERATORS_PATTERN, SENSORS_PATTERN},
),
EntityType.Hooks: find_all_entities(
imported_classes=imported_classes,
base_package=full_package_name,
sub_package_pattern_match=r".*\.hooks\..*",
ancestor_match=BaseHook,
expected_class_name_pattern=HOOKS_PATTERN,
unexpected_class_name_patterns=ALL_PATTERNS - {HOOKS_PATTERN},
),
EntityType.Secrets: find_all_entities(
imported_classes=imported_classes,
sub_package_pattern_match=r".*\.secrets\..*",
base_package=full_package_name,
ancestor_match=BaseSecretsBackend,
expected_class_name_pattern=SECRETS_PATTERN,
unexpected_class_name_patterns=ALL_PATTERNS - {SECRETS_PATTERN},
),
EntityType.Transfers: find_all_entities(
imported_classes=imported_classes,
base_package=full_package_name,
sub_package_pattern_match=r".*\.transfers\..*",
ancestor_match=BaseOperator,
expected_class_name_pattern=TRANSFERS_PATTERN,
unexpected_class_name_patterns=ALL_PATTERNS - {OPERATORS_PATTERN, TRANSFERS_PATTERN},
),
}
for entity in EntityType:
print_wrong_naming(entity, all_verified_entities[entity].wrong_entities)
entities_summary: Dict[EntityType, EntityTypeSummary] = {} # noqa
for entity_type in EntityType:
entities_summary[entity_type] = get_details_about_classes(
entity_type,
all_verified_entities[entity_type].all_entities,
all_verified_entities[entity_type].wrong_entities,
full_package_name,
)
return entities_summary
def render_template(
template_name: str,
context: Dict[str, Any],
extension: str,
autoescape: bool = True,
keep_trailing_newline: bool = False,
) -> str:
"""
Renders template based on it's name. Reads the template from <name>_TEMPLATE.md.jinja2 in current dir.
:param template_name: name of the template to use
:param context: Jinja2 context
:param extension: Target file extension
:param autoescape: Whether to autoescape HTML
:param keep_trailing_newline: Whether to keep the newline in rendered output
:return: rendered template
"""
import jinja2
template_loader = jinja2.FileSystemLoader(searchpath=MY_DIR_PATH)
template_env = jinja2.Environment(
loader=template_loader,
undefined=jinja2.StrictUndefined,
autoescape=autoescape,
keep_trailing_newline=keep_trailing_newline,
)
template = template_env.get_template(f"{template_name}_TEMPLATE{extension}.jinja2")
content: str = template.render(context)
return content
PR_PATTERN = re.compile(r".*\(#([0-9]+)\)")
class Change(NamedTuple):
"""Stores details about commits"""
full_hash: str
short_hash: str
date: str
version: str
message: str
message_without_backticks: str
pr: Optional[str]
def get_change_from_line(line: str, version: str):
split_line = line.split(" ", maxsplit=3)
message = split_line[3]
pr = None
pr_match = PR_PATTERN.match(message)
if pr_match:
pr = pr_match.group(1)
return Change(
full_hash=split_line[0],
short_hash=split_line[1],
date=split_line[2],
version=version,
message=message,
message_without_backticks=message.replace("`", "'"),
pr=pr,
)
def convert_git_changes_to_table(
version: str, changes: str, base_url: str, markdown: bool = True
) -> Tuple[str, List[Change]]:
"""
Converts list of changes from it's string form to markdown/RST table and array of change information
The changes are in the form of multiple lines where each line consists of:
FULL_COMMIT_HASH SHORT_COMMIT_HASH COMMIT_DATE COMMIT_SUBJECT
The subject can contain spaces but one of the preceding values can, so we can make split
3 times on spaces to break it up.
:param version: Version from which the changes are
:param changes: list of changes in a form of multiple-line string
:param base_url: base url for the commit URL
:param markdown: if True, markdown format is used else rst
:return: formatted table + list of changes (starting from the latest)
"""
from tabulate import tabulate
lines = changes.split("\n")
headers = ["Commit", "Committed", "Subject"]
table_data = []
changes_list: List[Change] = []
for line in lines:
if line == "":
continue
change = get_change_from_line(line, version)
table_data.append(
(
f"[{change.short_hash}]({base_url}{change.full_hash})"
if markdown
else f"`{change.short_hash} <{base_url}{change.full_hash}>`_",
change.date,
f"`{change.message_without_backticks}`"
if markdown
else f"``{change.message_without_backticks}``",
)
)
changes_list.append(change)
header = ""
if not table_data:
return header, []
table = tabulate(table_data, headers=headers, tablefmt="pipe" if markdown else "rst")
if not markdown:
header += f"\n\n{version}\n" + "." * len(version) + "\n\n"
release_date = table_data[0][1]
header += f"Latest change: {release_date}\n\n"
return header + table, changes_list
def convert_pip_requirements_to_table(requirements: Iterable[str], markdown: bool = True) -> str:
"""
Converts PIP requirement list to a markdown table.
:param requirements: requirements list
:param markdown: if True, markdown format is used else rst
:return: formatted table
"""
from tabulate import tabulate
headers = ["PIP package", "Version required"]
table_data = []
for dependency in requirements:
found = re.match(r"(^[^<=>~]*)([^<=>~]?.*)$", dependency)
if found:
package = found.group(1)
version_required = found.group(2)
if version_required != "":
version_required = f"`{version_required}`" if markdown else f'``{version_required}``'
table_data.append((f"`{package}`" if markdown else f"``{package}``", version_required))
else:
table_data.append((dependency, ""))
return tabulate(table_data, headers=headers, tablefmt="pipe" if markdown else "rst")
def convert_cross_package_dependencies_to_table(
cross_package_dependencies: List[str],
markdown: bool = True,
) -> str:
"""
Converts cross-package dependencies to a markdown table
:param cross_package_dependencies: list of cross-package dependencies
:param markdown: if True, markdown format is used else rst
:return: formatted table
"""
from tabulate import tabulate
headers = ["Dependent package", "Extra"]
table_data = []
prefix = "apache-airflow-providers-"
base_url = "https://airflow.apache.org/docs/"
for dependency in cross_package_dependencies:
pip_package_name = f"{prefix}{dependency.replace('.','-')}"
url_suffix = f"{dependency.replace('.','-')}"
if markdown:
url = f"[{pip_package_name}]({base_url}{url_suffix})"
else:
url = f"`{pip_package_name} <{base_url}{prefix}{url_suffix}>`_"
table_data.append((url, f"`{dependency}`" if markdown else f"``{dependency}``"))
return tabulate(table_data, headers=headers, tablefmt="pipe" if markdown else "rst")
LICENCE = """<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
"""
LICENCE_RST = """
.. Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
.. http://www.apache.org/licenses/LICENSE-2.0
.. Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
"""
"""
Keeps information about historical releases.
"""
ReleaseInfo = collections.namedtuple(
"ReleaseInfo", "release_version release_version_no_leading_zeros last_commit_hash content file_name"
)
def strip_leading_zeros(version: str) -> str:
"""
Strips leading zeros from version number.
This converts 1974.04.03 to 1974.4.3 as the format with leading month and day zeros is not accepted
by PIP versioning.
:param version: version number in CALVER format (potentially with leading 0s in date and month)
:return: string with leading 0s after dot replaced.
"""
return ".".join(str(int(i)) for i in version.split("."))
def get_previous_release_info(
previous_release_version: Optional[str], past_releases: List[ReleaseInfo], current_release_version: str