-
Notifications
You must be signed in to change notification settings - Fork 14.1k
/
prepare_provider_packages.py
executable file
·2091 lines (1802 loc) · 77.7 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
#
# 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."""
from __future__ import annotations
import collections
import difflib
import glob
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 random import choice
from shutil import copyfile
from typing import Any, Generator, Iterable, NamedTuple
import jinja2
import jsonschema
import rich_click as click
import semver as semver
from black import Mode, TargetVersion, format_str, parse_pyproject_toml
from packaging.version import Version
from rich.console import Console
from rich.syntax import Syntax
from yaml import safe_load
ALL_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11"]
MIN_AIRFLOW_VERSION = "2.4.0"
# In case you have some providers that you want to have different min-airflow version for,
# Add them as exceptions here. Make sure to remove it once the min-airflow version is bumped
# to the same version that is required by the exceptional provider
MIN_AIRFLOW_VERSION_EXCEPTIONS = {"openlineage": "2.6.0"}
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.
.. NOTE TO CONTRIBUTORS:
Please, only add notes to the Changelog just below the "Changelog" header when there
are some breaking changes and you want to add an explanation to the users on how they are supposed
to deal with them. The changelog is updated and maintained semi-automatically by release manager.
``{{ package_name }}``
Changelog
---------
1.0.0
.....
Initial version of the provider.
"""
HTTPS_REMOTE = "apache-https-for-providers"
HEAD_OF_HTTPS_REMOTE = f"{HTTPS_REMOTE}"
MY_DIR_PATH = Path(__file__).parent
AIRFLOW_SOURCES_ROOT_PATH = MY_DIR_PATH.parents[1]
AIRFLOW_PATH = AIRFLOW_SOURCES_ROOT_PATH / "airflow"
DIST_PATH = AIRFLOW_SOURCES_ROOT_PATH / "dist"
PROVIDERS_PATH = AIRFLOW_PATH / "providers"
DOCUMENTATION_PATH = AIRFLOW_SOURCES_ROOT_PATH / "docs"
DEPENDENCIES_JSON_FILE_PATH = AIRFLOW_SOURCES_ROOT_PATH / "generated" / "provider_dependencies.json"
TARGET_PROVIDER_PACKAGES_PATH = AIRFLOW_SOURCES_ROOT_PATH / "provider_packages"
GENERATED_AIRFLOW_PATH = TARGET_PROVIDER_PACKAGES_PATH / "airflow"
GENERATED_PROVIDERS_PATH = GENERATED_AIRFLOW_PATH / "providers"
PROVIDER_RUNTIME_DATA_SCHEMA_PATH = AIRFLOW_SOURCES_ROOT_PATH / "airflow" / "provider_info.schema.json"
CROSS_PROVIDERS_DEPS = "cross-providers-deps"
DEPS = "deps"
sys.path.insert(0, str(AIRFLOW_SOURCES_ROOT_PATH))
ALL_DEPENDENCIES = json.loads(DEPENDENCIES_JSON_FILE_PATH.read_text())
# 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
from setup import PREINSTALLED_PROVIDERS, ALL_PROVIDERS # type: ignore[attr-defined] # isort:skip # noqa
# Note - we do not test protocols as they are not really part of the official API of
# Apache Airflow
logger = logging.getLogger(__name__)
PY3 = sys.version_info[0] == 3
console = Console(width=400, color_system="standard")
class PluginInfo(NamedTuple):
name: str
package_name: str
class_name: 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: Path
provider_description: str
versions: list[str]
excluded_python_versions: list[str]
plugins: list[PluginInfo]
class EntityType(Enum):
Operators = "Operators"
Transfers = "Transfers"
Sensors = "Sensors"
Hooks = "Hooks"
Secrets = "Secrets"
@click.group(context_settings={"help_option_names": ["-h", "--help"], "max_content_width": 500})
def cli():
...
option_skip_tag_check = click.option(
"--skip-tag-check/--no-skip-tag-check",
default=False,
is_flag=True,
help="Skip checking if the tag already exists in the remote repository",
)
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_package_format = click.option(
"--package-format",
type=click.Choice(["wheel", "sdist", "both"]),
help="Format of packages.",
default="wheel",
show_default=True,
envvar="PACKAGE_FORMAT",
)
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",
)
option_base_branch = click.option(
"--base-branch",
type=str,
default="main",
)
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: str) -> Generator[None, None, None]:
"""
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":
console.print("#" * 10 + " [bright_blue]" + title + "[/] " + "#" * 10)
yield
return
console.print(f"::group::[bright_blue]{title}[/]")
yield
console.print("::endgroup::")
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(AIRFLOW_SOURCES_ROOT_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("."))
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, version_suffix: str) -> str:
"""
Returns install requirements for the package.
:param provider_package_id: id of the provider package
:param version_suffix: optional version suffix for packages
:return: install requirements of the package
"""
def apply_version_suffix(install_clause: str) -> str:
if install_clause.startswith("apache-airflow") and ">=" in install_clause and version_suffix != "":
# This is workaround for `pip` way of handling `--pre` installation switch. It apparently does
# not modify the meaning of `install_requires` to include also pre-releases, so we need to
# modify our internal provider and airflow package version references to include all pre-releases
# including all development releases. When you specify dependency as >= X.Y.Z, and you
# have packages X.Y.Zdev0 or X.Y.Zrc1 in a local file, such package is not considered
# as fulfilling the requirement even if `--pre` switch is used.
return install_clause + ".dev0"
return install_clause
install_requires = [
apply_version_suffix(clause) for clause in ALL_DEPENDENCIES[provider_package_id][DEPS]
]
prefix = "\n "
return prefix + prefix.join(install_requires)
def get_setup_requirements() -> 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 {}
extras_dict: dict[str, list[str]] = {
module: [get_pip_package_name(module)]
for module in ALL_DEPENDENCIES[provider_package_id][CROSS_PROVIDERS_DEPS]
}
provider_yaml_dict = get_provider_yaml(provider_package_id)
additional_extras = provider_yaml_dict.get("additional-extras")
if additional_extras:
for entry in additional_extras:
name = entry["name"]
dependencies = entry["dependencies"]
if name in extras_dict:
# remove non-versioned dependencies if versioned ones are coming
existing_dependencies = set(extras_dict[name])
for new_dependency in dependencies:
for dependency in existing_dependencies:
# remove extra if exists as non-versioned one
if new_dependency.startswith(dependency):
extras_dict[name].remove(dependency)
break
extras_dict[name].append(new_dependency)
else:
extras_dict[name] = dependencies
return extras_dict
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 its 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".*\(#(\d+)\)")
class Change(NamedTuple):
"""Stores details about commits"""
full_hash: str
short_hash: str
date: str
version: str
message: str
message_without_backticks: str
pr: str | None
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("`", "'").replace("&39;", "'"),
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 its 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: str | None, past_releases: list[ReleaseInfo], current_release_version: str
) -> str | None:
"""Find previous release.
In case we are re-running current release, we assume that last release was
the previous one. This is needed so that we can generate list of changes
since the previous release.
:param previous_release_version: known last release version
:param past_releases: list of past releases
:param current_release_version: release that we are working on currently
"""
previous_release = None
if previous_release_version == current_release_version:
# Re-running for current release - use previous release as base for git log
if len(past_releases) > 1:
previous_release = past_releases[1].last_commit_hash
else:
previous_release = past_releases[0].last_commit_hash if past_releases else None
return previous_release
def check_if_release_version_ok(
past_releases: list[ReleaseInfo],
current_release_version: str,
) -> tuple[str, str | None]:
"""Check if the release version passed is not later than the last release version.
:param past_releases: all past releases (if there are any)
:param current_release_version: release version to check
:return: Tuple of current/previous_release (previous might be None if there are no releases)
"""
previous_release_version = past_releases[0].release_version if past_releases else None
if current_release_version == "":
if previous_release_version:
current_release_version = previous_release_version
else:
current_release_version = (datetime.today() + timedelta(days=5)).strftime("%Y.%m.%d")
if previous_release_version:
if Version(current_release_version) < Version(previous_release_version):
console.print(
f"[red]The release {current_release_version} must be not less than "
f"{previous_release_version} - last release for the package[/]"
)
raise Exception("Bad release version")
return current_release_version, previous_release_version
def get_cross_provider_dependent_packages(provider_package_id: str) -> list[str]:
"""Returns cross-provider dependencies for the package.
:param provider_package_id: package id
:return: list of cross-provider dependencies
"""
return ALL_DEPENDENCIES[provider_package_id][CROSS_PROVIDERS_DEPS]
def make_current_directory_safe(verbose: bool):
"""Makes current directory safe for Git.
New git checks if git ownership for the folder is not manipulated with. We
are running this command only inside the container where the directory is
mounted from "regular" user to "root" user which is used inside the
container, so this is quite ok to assume the directory it is used is safe.
It's also ok to leave it as safe - it is a global option inside the
container so it will disappear when we exit.
:param verbose: whether to print commands being executed
"""
safe_dir_remove_command = ["git", "config", "--global", "--unset-all", "safe.directory"]
if verbose:
console.print(f"Running command: '{' '.join(safe_dir_remove_command)}'")
# we ignore result of this call
subprocess.call(safe_dir_remove_command)
safe_dir_add_command = ["git", "config", "--global", "--add", "safe.directory", "/opt/airflow"]
if verbose:
console.print(f"Running command: '{' '.join(safe_dir_add_command)}'")
subprocess.check_call(safe_dir_add_command)
def make_sure_remote_apache_exists_and_fetch(git_update: bool, verbose: bool):
"""Make sure that apache remote exist in git.
We need to take a log from the apache repository - not locally. Also, the
local repo might be shallow, so we need to un-shallow it.
This will:
* mark current directory as safe for ownership (it is run in the container)
* check if the remote exists and add if it does not
* check if the local repo is shallow, mark it to un-shallow in this case
* fetch from the remote including all tags and overriding local tags in case
they are set differently
:param git_update: If the git remote already exists, should we try to update it
:param verbose: print verbose messages while fetching
"""
make_current_directory_safe(verbose)
try:
check_remote_command = ["git", "remote", "get-url", HTTPS_REMOTE]
if verbose:
console.print(f"Running command: '{' '.join(check_remote_command)}'")
subprocess.check_call(
check_remote_command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Remote already exists, don't update it again!
if not git_update:
return
except subprocess.CalledProcessError as ex:
if ex.returncode == 128 or ex.returncode == 2:
remote_add_command = [
"git",
"remote",
"add",
HTTPS_REMOTE,
"https://github.com/apache/airflow.git",
]
if verbose:
console.print(f"Running command: '{' '.join(remote_add_command)}'")
try:
subprocess.check_call(
remote_add_command,
)
except subprocess.CalledProcessError as ex:
console.print("[red]Error: when adding remote:[/]", ex)
sys.exit(128)
else:
raise
if verbose:
console.print("Fetching full history and tags from remote. ")
console.print("This might override your local tags!")
is_shallow_repo = (
subprocess.check_output(["git", "rev-parse", "--is-shallow-repository"], stderr=subprocess.DEVNULL)
== "true"
)
fetch_command = ["git", "fetch", "--tags", "--force", HTTPS_REMOTE]
if is_shallow_repo:
if verbose:
console.print(
"This will also un-shallow the repository, "
"making all history available and increasing storage!"
)
fetch_command.append("--unshallow")
if verbose:
console.print(f"Running command: '{' '.join(fetch_command)}'")
try:
subprocess.check_call(fetch_command)
except subprocess.CalledProcessError as e:
console.print(
"[yellow]Error when fetching tags from remote. Your tags might not be refreshed. "
f'Please refresh the tags manually via {" ".join(fetch_command)}\n'
)
console.print(f"[yellow]The error was: {e}")
def get_git_log_command(
verbose: bool, from_commit: str | None = None, to_commit: str | None = None
) -> list[str]:
"""Get git command to run for the current repo from the current folder.
The current directory should always be the package folder.
:param verbose: whether to print verbose info while getting the command
:param from_commit: if present - base commit from which to start the log from
:param to_commit: if present - final commit which should be the start of the log
:return: git command to run
"""
git_cmd = [
"git",
"log",
"--pretty=format:%H %h %cd %s",
"--date=short",
]
if from_commit and to_commit:
git_cmd.append(f"{from_commit}...{to_commit}")
elif from_commit:
git_cmd.append(from_commit)
git_cmd.extend(["--", "."])
if verbose:
console.print(f"Command to run: '{' '.join(git_cmd)}'")
return git_cmd
def get_git_tag_check_command(tag: str) -> list[str]:
"""Get git command to check if tag exits.
:param tag: Tag to check
:return: git command to run
"""
return [
"git",
"rev-parse",
tag,
]
def get_source_package_path(provider_package_id: str) -> str:
"""Retrieves source package path from package id.
:param provider_package_id: id of the package
:return: path of the providers folder
"""
return os.path.join(PROVIDERS_PATH, *provider_package_id.split("."))
def get_documentation_package_path(provider_package_id: str) -> Path:
"""Retrieves documentation package path from package id.
:param provider_package_id: id of the package
:return: path of the documentation folder
"""
return DOCUMENTATION_PATH / f"apache-airflow-providers-{provider_package_id.replace('.','-')}"
def get_generated_package_path(provider_package_id: str) -> str:
"""Retrieves generated package path from package id.
:param provider_package_id: id of the package
:return: path of the providers folder
"""
provider_package_path = os.path.join(GENERATED_PROVIDERS_PATH, *provider_package_id.split("."))
return provider_package_path
def get_additional_package_info(provider_package_path: str) -> str:
"""Returns additional info for the package.
:param provider_package_path: path for the package
:return: additional information for the path (empty string if missing)
"""
additional_info_file_path = os.path.join(provider_package_path, "ADDITIONAL_INFO.md")
if os.path.isfile(additional_info_file_path):
with open(additional_info_file_path) as additional_info_file:
additional_info = additional_info_file.read()
additional_info_lines = additional_info.splitlines(keepends=True)
result = ""
skip_comment = True
for line in additional_info_lines:
if line.startswith(" -->"):
skip_comment = False
continue
if not skip_comment:
result += line
return result
return ""
def get_package_pip_name(provider_package_id: str):
return f"apache-airflow-providers-{provider_package_id.replace('.', '-')}"
def validate_provider_info_with_runtime_schema(provider_info: dict[str, Any]) -> None:
"""Validates provider info against the runtime schema.
This way we check if the provider info in the packages is future-compatible.
The Runtime Schema should only change when there is a major version change.
:param provider_info: provider info to validate
"""
with open(PROVIDER_RUNTIME_DATA_SCHEMA_PATH) as schema_file:
schema = json.load(schema_file)
try:
jsonschema.validate(provider_info, schema=schema)
except jsonschema.ValidationError as ex:
console.print("[red]Provider info not validated against runtime schema[/]")
raise Exception(
"Error when validating schema. The schema must be compatible with "
"airflow/provider_info.schema.json.",
ex,
)
def get_provider_yaml(provider_package_id: str) -> dict[str, Any]:
"""Retrieves provider info from the provider YAML file.
The provider yaml file contains more information than provider_info that is
used at runtime. This method converts the full provider yaml file into
stripped-down provider info and validates it against deprecated 2.0.0 schema
and runtime schema.
:param provider_package_id: package id to retrieve provider.yaml from
:return: provider_info dictionary
"""
provider_yaml_file_name = os.path.join(get_source_package_path(provider_package_id), "provider.yaml")
if not os.path.exists(provider_yaml_file_name):
raise Exception(f"The provider.yaml file is missing: {provider_yaml_file_name}")
with open(provider_yaml_file_name) as provider_file:
provider_yaml_dict = safe_load(provider_file)
return provider_yaml_dict
def get_provider_info_from_provider_yaml(provider_package_id: str) -> dict[str, Any]:
"""Retrieves provider info from the provider yaml file.
:param provider_package_id: package id to retrieve provider.yaml from
:return: provider_info dictionary
"""
provider_yaml_dict = get_provider_yaml(provider_package_id=provider_package_id)
validate_provider_info_with_runtime_schema(provider_yaml_dict)
return provider_yaml_dict
def get_version_tag(version: str, provider_package_id: str, version_suffix: str = ""):
if version_suffix is None:
version_suffix = ""
return f"providers-{provider_package_id.replace('.','-')}/{version}{version_suffix}"
def print_changes_table(changes_table):
syntax = Syntax(changes_table, "rst", theme="ansi_dark")
console.print(syntax)
def get_all_changes_for_package(
provider_package_id: str,
verbose: bool,
base_branch: str,
force: bool,
) -> tuple[bool, list[list[Change]] | Change | None, str]:
"""Retrieves all changes for the package.
:param provider_package_id: provider package id
:param verbose: whether to print verbose messages
:param base_branch: base branch to check changes in apache remote for changes
:param force: whether to force the check even if the tag exists
"""
provider_details = get_provider_details(provider_package_id)
current_version = provider_details.versions[0]
current_tag_no_suffix = get_version_tag(current_version, provider_package_id)
if verbose:
console.print(f"Checking if tag '{current_tag_no_suffix}' exist.")
if not force and not subprocess.call(
get_git_tag_check_command(current_tag_no_suffix),
cwd=provider_details.source_provider_package_path,
stderr=subprocess.DEVNULL,
):
if verbose:
console.print(f"The tag {current_tag_no_suffix} exists.")
# The tag already exists
changes = subprocess.check_output(
get_git_log_command(verbose, f"{HEAD_OF_HTTPS_REMOTE}/{base_branch}", current_tag_no_suffix),
cwd=provider_details.source_provider_package_path,
text=True,
)
if changes:
provider_details = get_provider_details(provider_package_id)
doc_only_change_file = os.path.join(
provider_details.source_provider_package_path, ".latest-doc-only-change.txt"
)
if os.path.exists(doc_only_change_file):
with open(doc_only_change_file) as f:
last_doc_only_hash = f.read().strip()
try:
changes_since_last_doc_only_check = subprocess.check_output(
get_git_log_command(
verbose, f"{HEAD_OF_HTTPS_REMOTE}/{base_branch}", last_doc_only_hash
),
cwd=provider_details.source_provider_package_path,
text=True,
)
if not changes_since_last_doc_only_check:
console.print()
console.print(
"[yellow]The provider has doc-only changes since the last release. Skipping[/]"
)
# Returns 66 in case of doc-only changes