-
Notifications
You must be signed in to change notification settings - Fork 14.3k
/
release_management_commands.py
3518 lines (3283 loc) · 131 KB
/
release_management_commands.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
# 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.
from __future__ import annotations
import glob
import operator
import os
import random
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
import time
from collections import defaultdict
from collections.abc import Generator, Iterable
from copy import deepcopy
from datetime import date, datetime
from functools import partial
from multiprocessing import Pool
from pathlib import Path
from subprocess import DEVNULL
from typing import IO, TYPE_CHECKING, Any, Literal, NamedTuple, Union
import click
from rich.progress import Progress
from rich.syntax import Syntax
from airflow_breeze.commands.ci_image_commands import rebuild_or_pull_ci_image_if_needed
from airflow_breeze.commands.common_options import (
argument_doc_packages,
option_airflow_extras,
option_answer,
option_clean_airflow_installation,
option_commit_sha,
option_debug_resources,
option_dry_run,
option_github_repository,
option_historical_python_version,
option_image_tag_for_running,
option_include_not_ready_providers,
option_include_removed_providers,
option_include_success_outputs,
option_installation_package_format,
option_mount_sources,
option_parallelism,
option_python,
option_python_versions,
option_run_in_parallel,
option_skip_cleanup,
option_use_airflow_version,
option_use_uv,
option_verbose,
option_version_suffix_for_pypi,
)
from airflow_breeze.commands.common_package_installation_options import (
option_airflow_constraints_location,
option_airflow_constraints_mode_ci,
option_airflow_constraints_mode_update,
option_airflow_constraints_reference,
option_airflow_skip_constraints,
option_install_airflow_with_constraints,
option_install_selected_providers,
option_providers_constraints_location,
option_providers_constraints_mode_ci,
option_providers_constraints_reference,
option_providers_skip_constraints,
option_use_packages_from_dist,
)
from airflow_breeze.commands.release_management_group import release_management
from airflow_breeze.global_constants import (
ALLOWED_DEBIAN_VERSIONS,
ALLOWED_PACKAGE_FORMATS,
ALLOWED_PLATFORMS,
ALLOWED_PYTHON_MAJOR_MINOR_VERSIONS,
APACHE_AIRFLOW_GITHUB_REPOSITORY,
CURRENT_PYTHON_MAJOR_MINOR_VERSIONS,
DEFAULT_PYTHON_MAJOR_MINOR_VERSION,
MULTI_PLATFORM,
)
from airflow_breeze.params.shell_params import ShellParams
from airflow_breeze.prepare_providers.provider_packages import (
PrepareReleasePackageErrorBuildingPackageException,
PrepareReleasePackageTagExistException,
PrepareReleasePackageWrongSetupException,
build_provider_package,
cleanup_build_remnants,
copy_provider_sources_to_target,
generate_build_files,
get_packages_list_to_act_on,
move_built_packages_and_cleanup,
should_skip_the_package,
)
from airflow_breeze.utils.add_back_references import (
start_generating_back_references,
)
from airflow_breeze.utils.ci_group import ci_group
from airflow_breeze.utils.confirm import Answer, user_confirm
from airflow_breeze.utils.console import MessageType, Output, get_console
from airflow_breeze.utils.custom_param_types import BetterChoice, NotVerifiedBetterChoice
from airflow_breeze.utils.docker_command_utils import (
check_remote_ghcr_io_commands,
execute_command_in_shell,
fix_ownership_using_docker,
perform_environment_checks,
)
from airflow_breeze.utils.docs_publisher import DocsPublisher
from airflow_breeze.utils.github import download_constraints_file, get_active_airflow_versions
from airflow_breeze.utils.packages import (
PackageSuspendedException,
expand_all_provider_packages,
find_matching_long_package_names,
get_available_packages,
get_provider_details,
get_provider_packages_metadata,
make_sure_remote_apache_exists_and_fetch,
)
from airflow_breeze.utils.parallel import (
GenericRegexpProgressMatcher,
SummarizeAfter,
check_async_run_results,
run_with_pool,
)
from airflow_breeze.utils.path_utils import (
AIRFLOW_PROVIDERS_SRC,
AIRFLOW_SOURCES_ROOT,
CONSTRAINTS_CACHE_DIR,
DIST_DIR,
GENERATED_PROVIDER_PACKAGES_DIR,
OUT_DIR,
PROVIDER_METADATA_JSON_FILE_PATH,
cleanup_python_generated_files,
)
from airflow_breeze.utils.provider_dependencies import (
DEPENDENCIES,
generate_providers_metadata_for_package,
get_related_providers,
)
from airflow_breeze.utils.python_versions import check_python_version, get_python_version_list
from airflow_breeze.utils.reproducible import get_source_date_epoch, repack_deterministically
from airflow_breeze.utils.run_utils import (
run_command,
)
from airflow_breeze.utils.shared_options import get_dry_run, get_verbose
from airflow_breeze.utils.version_utils import get_latest_airflow_version, get_latest_helm_chart_version
from airflow_breeze.utils.versions import is_pre_release
from airflow_breeze.utils.virtualenv_utils import create_pip_command, create_venv
argument_provider_packages = click.argument(
"provider_packages",
nargs=-1,
required=False,
type=NotVerifiedBetterChoice(get_available_packages(include_removed=False, include_not_ready=False)),
)
option_airflow_site_directory = click.option(
"-a",
"--airflow-site-directory",
envvar="AIRFLOW_SITE_DIRECTORY",
type=click.Path(exists=True, file_okay=False, dir_okay=True, resolve_path=True),
help="Local directory path of cloned airflow-site repo.",
required=True,
)
option_chicken_egg_providers = click.option(
"--chicken-egg-providers",
default="",
help="List of chicken-egg provider packages - "
"those that have airflow_version >= current_version and should "
"be installed in CI from locally built packages with >= current_version.dev0 ",
envvar="CHICKEN_EGG_PROVIDERS",
)
option_debug_release_management = click.option(
"--debug",
is_flag=True,
help="Drop user in shell instead of running the command. Useful for debugging.",
envvar="DEBUG",
)
option_directory = click.option(
"--directory",
type=click.Path(exists=True, file_okay=False, dir_okay=True, resolve_path=True),
required=True,
help="Directory to clean the provider artifacts from.",
)
option_package_format = click.option(
"--package-format",
type=BetterChoice(ALLOWED_PACKAGE_FORMATS),
help="Format of packages.",
default=ALLOWED_PACKAGE_FORMATS[0],
show_default=True,
envvar="PACKAGE_FORMAT",
)
option_use_local_hatch = click.option(
"--use-local-hatch",
is_flag=True,
help="Use local hatch instead of docker to build the package. You need to have hatch installed.",
)
MY_DIR_PATH = os.path.dirname(__file__)
SOURCE_DIR_PATH = os.path.abspath(
os.path.join(MY_DIR_PATH, os.pardir, os.pardir, os.pardir, os.pardir, os.pardir)
)
PR_PATTERN = re.compile(r".*\(#([0-9]+)\)")
ISSUE_MATCH_IN_BODY = re.compile(r" #([0-9]+)[^0-9]")
if TYPE_CHECKING:
from packaging.version import Version
class VersionedFile(NamedTuple):
base: str
version: str
suffix: str
type: str
comparable_version: Version
file_name: str
AIRFLOW_PIP_VERSION = "24.2"
AIRFLOW_UV_VERSION = "0.4.24"
AIRFLOW_USE_UV = False
WHEEL_VERSION = "0.36.2"
GITPYTHON_VERSION = "3.1.40"
RICH_VERSION = "13.7.0"
NODE_VERSION = "21.2.0"
PRE_COMMIT_VERSION = "3.5.0"
HATCH_VERSION = "1.9.1"
PYYAML_VERSION = "6.0.1"
AIRFLOW_BUILD_DOCKERFILE = f"""
FROM python:{DEFAULT_PYTHON_MAJOR_MINOR_VERSION}-slim-{ALLOWED_DEBIAN_VERSIONS[0]}
RUN apt-get update && apt-get install -y --no-install-recommends git
RUN pip install pip=={AIRFLOW_PIP_VERSION} hatch=={HATCH_VERSION} pyyaml=={PYYAML_VERSION}\
gitpython=={GITPYTHON_VERSION} rich=={RICH_VERSION} pre-commit=={PRE_COMMIT_VERSION}
COPY . /opt/airflow
"""
AIRFLOW_BUILD_DOCKERIGNORE = """
# Git version is dynamically generated
airflow/git_version
# Exclude mode_modules pulled by "yarn" for compilation of www files generated by NPM
airflow/www/node_modules
airflow/ui/node_modules
# Exclude link to docs
airflow/www/static/docs
# Exclude out directory
out/
# Exclude python generated files
**/__pycache__/
**/*.py[cod]
**/*$py.class
**/.pytest_cache/
**/env/
**/build/
**/develop-eggs/
/dist/
**/downloads/
**/eggs/
**/.eggs/
**/lib/
**/lib64/
**/parts/
**/sdist/
**/var/
**/wheels/
**/*.egg-info/
**/.installed.cfg
**/*.egg
# Exclude temporary vi files
**/*~
# Exclude output files
**/*.out
**/hive_scratch_dir/
# Exclude auto-generated Finder files on Mac OS
**/.DS_Store
**/Thumbs.db
# Exclude docs generated files
docs/_build/
docs/_api/
docs/_doctrees/
# files generated by memray
*.py.*.html
*.py.*.bin
"""
AIRFLOW_BUILD_IMAGE_TAG = "apache/airflow:local-build-image"
NODE_BUILD_IMAGE_TAG = f"node:{NODE_VERSION}-bookworm-slim"
AIRFLOW_BUILD_DOCKERFILE_PATH = AIRFLOW_SOURCES_ROOT / "airflow-build-dockerfile"
AIRFLOW_BUILD_DOCKERFILE_IGNORE_PATH = AIRFLOW_SOURCES_ROOT / "airflow-build-dockerfile.dockerignore"
ISSUE_MATCH_IN_BODY = re.compile(r" #([0-9]+)[^0-9]")
class DistributionPackageInfo(NamedTuple):
filepath: Path
package: str
version: Version
dist_type: Literal["sdist", "wheel"]
@classmethod
def from_sdist(cls, filepath: Path) -> DistributionPackageInfo:
from packaging.utils import parse_sdist_filename
package, version = parse_sdist_filename(filepath.name)
return cls(
filepath=filepath.resolve().absolute(), package=package, version=version, dist_type="sdist"
)
@classmethod
def from_wheel(cls, filepath: Path) -> DistributionPackageInfo:
from packaging.utils import parse_wheel_filename
package, version, *_ = parse_wheel_filename(filepath.name)
return cls(
filepath=filepath.resolve().absolute(), package=package, version=version, dist_type="wheel"
)
@classmethod
def dist_packages(
cls,
*,
package_format: str,
dist_directory: Path,
build_type: Literal["airflow", "providers", "task-sdk"],
) -> tuple[DistributionPackageInfo, ...]:
if build_type == "airflow":
default_glob_pattern = "apache[_-]airflow-[0-9]"
elif build_type == "task-sdk":
default_glob_pattern = "apache[_-]airflow[_-]task[_-]sdk"
else:
default_glob_pattern = "apache[_-]airflow[_-]providers"
dists_info = []
if package_format in ["sdist", "both"]:
for file in dist_directory.glob(f"{default_glob_pattern}*tar.gz"):
if not file.is_file() or "-source.tar.gz" in file.name:
continue
dists_info.append(cls.from_sdist(filepath=file))
if package_format in ["wheel", "both"]:
for file in dist_directory.glob(f"{default_glob_pattern}*whl"):
if not file.is_file():
continue
dists_info.append(cls.from_wheel(filepath=file))
return tuple(sorted(dists_info, key=lambda di: (di.package, di.dist_type)))
def __str__(self):
return f"{self.package} ({self.version}): {self.dist_type} - {self.filepath.name}"
def _build_local_build_image():
# This is security feature.
#
# Building the image needed to build airflow package including .git directory
# In isolated environment, to not allow the in-docker code to override local code
# The image used to build airflow package is built from scratch and contains
# Full Airflow code including Airflow repository is added to the image, but locally build node_modules
# are not added to the context of that image
AIRFLOW_BUILD_DOCKERFILE_PATH.write_text(AIRFLOW_BUILD_DOCKERFILE.strip())
AIRFLOW_BUILD_DOCKERFILE_IGNORE_PATH.write_text(AIRFLOW_BUILD_DOCKERIGNORE.strip())
run_command(
[
"docker",
"build",
".",
"-f",
"airflow-build-dockerfile",
"--tag",
AIRFLOW_BUILD_IMAGE_TAG,
],
text=True,
check=True,
cwd=AIRFLOW_SOURCES_ROOT,
env={"DOCKER_CLI_HINTS": "false"},
)
def _build_airflow_packages_with_docker(
package_format: str, source_date_epoch: int, version_suffix_for_pypi: str
):
_build_local_build_image()
container_id = f"airflow-build-{random.getrandbits(64):08x}"
result = run_command(
cmd=[
"docker",
"run",
"--name",
container_id,
"-t",
"-e",
f"VERSION_SUFFIX_FOR_PYPI={version_suffix_for_pypi}",
"-e",
f"SOURCE_DATE_EPOCH={source_date_epoch}",
"-e",
"HOME=/opt/airflow/files/home",
"-e",
"GITHUB_ACTIONS",
"-e",
f"PACKAGE_FORMAT={package_format}",
"-w",
"/opt/airflow",
AIRFLOW_BUILD_IMAGE_TAG,
"python",
"/opt/airflow/scripts/in_container/run_prepare_airflow_packages.py",
],
check=False,
)
if result.returncode != 0:
get_console().print("[error]Error preparing Airflow package[/]")
fix_ownership_using_docker()
sys.exit(result.returncode)
DIST_DIR.mkdir(parents=True, exist_ok=True)
# Copy all files in the dist directory in container to the host dist directory (note '/.' in SRC)
run_command(["docker", "cp", f"{container_id}:/opt/airflow/dist/.", "./dist"], check=True)
run_command(["docker", "rm", "--force", container_id], check=False, stderr=DEVNULL, stdout=DEVNULL)
def _build_airflow_packages_with_hatch(
package_format: str, source_date_epoch: int, version_suffix_for_pypi: str
):
hatch_build_command = ["hatch", "build", "-c", "-t", "custom"]
if package_format in ["sdist", "both"]:
hatch_build_command.extend(["-t", "sdist"])
if package_format in ["wheel", "both"]:
hatch_build_command.extend(["-t", "wheel"])
env_copy = os.environ.copy()
env_copy["SOURCE_DATE_EPOCH"] = str(source_date_epoch)
env_copy["VERSION_SUFFIX_FOR_PYPI"] = version_suffix_for_pypi
run_command(
hatch_build_command,
check=True,
env=env_copy,
)
def _check_sdist_to_wheel_dists(dists_info: tuple[DistributionPackageInfo, ...]):
venv_created = False
success_build = True
with tempfile.TemporaryDirectory() as tmp_dir_name:
for di in dists_info:
if di.dist_type != "sdist":
continue
if not venv_created:
python_path = create_venv(Path(tmp_dir_name) / ".venv", pip_version=AIRFLOW_PIP_VERSION)
pip_command = create_pip_command(python_path)
venv_created = True
returncode = _check_sdist_to_wheel(di, pip_command, str(tmp_dir_name))
if returncode != 0:
success_build = False
if not success_build:
get_console().print(
"\n[errors]Errors detected during build wheel distribution(s) from sdist. Exiting!\n"
)
sys.exit(1)
def _check_sdist_to_wheel(dist_info: DistributionPackageInfo, pip_command: list[str], cwd: str) -> int:
get_console().print(
f"[info]Validate build wheel from sdist distribution for package {dist_info.package!r}.[/]"
)
result_pip_wheel = run_command(
[
*pip_command,
"wheel",
"--wheel-dir",
cwd,
"--no-deps",
"--no-cache",
"--no-binary",
dist_info.package,
dist_info.filepath.as_posix(),
],
check=False,
# We should run `pip wheel` outside of Project directory for avoid the case
# when some files presented into the project directory, but not included in sdist.
cwd=cwd,
capture_output=True,
text=True,
)
if (returncode := result_pip_wheel.returncode) == 0:
get_console().print(
f"[success]Successfully build wheel from sdist distribution for package {dist_info.package!r}.[/]"
)
else:
get_console().print(
f"[error]Unable to build wheel from sdist distribution for package {dist_info.package!r}.[/]\n"
f"{result_pip_wheel.stdout}\n{result_pip_wheel.stderr}"
)
return returncode
@release_management.command(
name="prepare-airflow-package",
help="Prepare sdist/whl package of Airflow.",
)
@option_package_format
@option_version_suffix_for_pypi
@option_use_local_hatch
@option_verbose
@option_dry_run
def prepare_airflow_packages(
package_format: str,
version_suffix_for_pypi: str,
use_local_hatch: bool,
):
check_python_version()
perform_environment_checks()
fix_ownership_using_docker()
cleanup_python_generated_files()
source_date_epoch = get_source_date_epoch(AIRFLOW_SOURCES_ROOT / "airflow")
if use_local_hatch:
_build_airflow_packages_with_hatch(
package_format=package_format,
source_date_epoch=source_date_epoch,
version_suffix_for_pypi=version_suffix_for_pypi,
)
get_console().print("[info]Checking if sdist packages can be built into wheels[/]")
packages = DistributionPackageInfo.dist_packages(
package_format=package_format, dist_directory=DIST_DIR, build_type="airflow"
)
get_console().print()
_check_sdist_to_wheel_dists(packages)
get_console().print("\n[info]Packages available in dist:[/]\n")
for dist_info in packages:
get_console().print(str(dist_info))
get_console().print()
else:
_build_airflow_packages_with_docker(
package_format=package_format,
source_date_epoch=source_date_epoch,
version_suffix_for_pypi=version_suffix_for_pypi,
)
get_console().print("[success]Successfully prepared Airflow packages")
TASK_SDK_DIR_PATH = AIRFLOW_SOURCES_ROOT / "task_sdk"
TASK_SDK_DIST_DIR_PATH = TASK_SDK_DIR_PATH / "dist"
@release_management.command(
name="prepare-task-sdk-package",
help="Prepare sdist/whl package of Airflow Task SDK.",
)
@option_package_format
@option_use_local_hatch
@option_verbose
@option_dry_run
def prepare_airflow_task_sdk_packages(
package_format: str,
use_local_hatch: bool,
):
check_python_version()
perform_environment_checks()
fix_ownership_using_docker()
cleanup_python_generated_files()
def _build_package_with_hatch(package_format: str):
command = [
"hatch",
"build",
"-c",
]
if package_format == "sdist" or package_format == "both":
command += ["-t", "sdist"]
if package_format == "wheel" or package_format == "both":
command += ["-t", "wheel"]
env_copy = os.environ.copy()
run_command(
cmd=command,
cwd=TASK_SDK_DIR_PATH,
env=env_copy,
check=True,
)
shutil.copytree(TASK_SDK_DIST_DIR_PATH, DIST_DIR, dirs_exist_ok=True)
def _build_package_with_docker(package_format: str):
_build_local_build_image()
command = "hatch build -c "
if package_format == "sdist" or package_format == "both":
command += "-t sdist "
if package_format == "wheel" or package_format == "both":
command += "-t wheel "
container_id = f"airflow-task-sdk-build-{random.getrandbits(64):08x}"
result = run_command(
cmd=[
"docker",
"run",
"--name",
container_id,
"-t",
"-e",
"HOME=/opt/airflow/files/home",
"-e",
"GITHUB_ACTIONS",
"-w",
"/opt/airflow/task_sdk",
AIRFLOW_BUILD_IMAGE_TAG,
"bash",
"-c",
command,
],
check=False,
)
if result.returncode != 0:
get_console().print("[error]Error preparing Airflow Task SDK[/]")
fix_ownership_using_docker()
sys.exit(result.returncode)
DIST_DIR.mkdir(parents=True, exist_ok=True)
get_console().print()
# Copy all files in the dist directory in container to the host dist directory (note '/.' in SRC)
run_command(["docker", "cp", f"{container_id}:/opt/airflow/task_sdk/dist/.", "./dist"], check=True)
run_command(["docker", "rm", "--force", container_id], check=False, stdout=DEVNULL, stderr=DEVNULL)
if use_local_hatch:
_build_package_with_hatch(
package_format=package_format,
)
get_console().print("[info]Checking if sdist packages can be built into wheels[/]")
packages = DistributionPackageInfo.dist_packages(
package_format=package_format, dist_directory=DIST_DIR, build_type="task-sdk"
)
get_console().print()
_check_sdist_to_wheel_dists(packages)
get_console().print("\n[info]Packages available in dist:[/]\n")
for dist_info in packages:
get_console().print(str(dist_info))
get_console().print()
else:
_build_package_with_docker(
package_format=package_format,
)
get_console().print("[success]Successfully prepared Airflow Task SDK packages")
def provider_action_summary(description: str, message_type: MessageType, packages: list[str]):
if packages:
get_console().print(f"{description}: {len(packages)}\n")
get_console().print(f"[{message_type.value}]{' '.join(packages)}")
get_console().print()
@release_management.command(
name="prepare-provider-documentation",
help="Prepare CHANGELOG, README and COMMITS information for providers.",
)
@click.option(
"--skip-git-fetch",
is_flag=True,
help="Skips removal and recreation of `apache-https-for-providers` remote in git. By default, the "
"remote is recreated and fetched to make sure that it's up to date and that recent commits "
"are not missing",
)
@click.option(
"--base-branch",
type=str,
default="main",
help="Base branch to use as diff for documentation generation (used for releasing from old branch)",
)
@option_github_repository
@argument_provider_packages
@option_answer
@option_dry_run
@option_include_not_ready_providers
@option_include_removed_providers
@click.option(
"--non-interactive",
is_flag=True,
help="Run in non-interactive mode. Provides random answers to the type of changes and confirms release"
"for providers prepared for release - useful to test the script in non-interactive mode in CI.",
)
@click.option(
"--only-min-version-update",
is_flag=True,
help="Only update minimum version in __init__.py files and regenerate corresponding documentation",
)
@click.option(
"--reapply-templates-only",
is_flag=True,
help="Only reapply templates, do not bump version. Useful if templates were added"
" and you need to regenerate documentation.",
)
@option_verbose
def prepare_provider_documentation(
base_branch: str,
github_repository: str,
include_not_ready_providers: bool,
include_removed_providers: bool,
non_interactive: bool,
only_min_version_update: bool,
provider_packages: tuple[str],
reapply_templates_only: bool,
skip_git_fetch: bool,
):
from airflow_breeze.prepare_providers.provider_documentation import (
PrepareReleaseDocsChangesOnlyException,
PrepareReleaseDocsErrorOccurredException,
PrepareReleaseDocsNoChangesException,
PrepareReleaseDocsUserQuitException,
PrepareReleaseDocsUserSkippedException,
update_changelog,
update_min_airflow_version,
update_release_notes,
)
perform_environment_checks()
fix_ownership_using_docker()
cleanup_python_generated_files()
if not provider_packages:
provider_packages = get_available_packages(
include_removed=include_removed_providers, include_not_ready=include_not_ready_providers
)
if not skip_git_fetch:
run_command(["git", "remote", "rm", "apache-https-for-providers"], check=False, stderr=DEVNULL)
make_sure_remote_apache_exists_and_fetch(github_repository=github_repository)
no_changes_packages = []
doc_only_packages = []
error_packages = []
user_skipped_packages = []
success_packages = []
suspended_packages = []
removed_packages = []
for provider_id in provider_packages:
provider_metadata = basic_provider_checks(provider_id)
if os.environ.get("GITHUB_ACTIONS", "false") != "true":
if not only_min_version_update:
get_console().print("-" * get_console().width)
try:
with_breaking_changes = False
maybe_with_new_features = False
with ci_group(
f"Update release notes for package '{provider_id}' ",
skip_printing_title=only_min_version_update,
):
if not only_min_version_update:
get_console().print("Updating documentation for the latest release version.")
with_breaking_changes, maybe_with_new_features = update_release_notes(
provider_id,
reapply_templates_only=reapply_templates_only,
base_branch=base_branch,
regenerate_missing_docs=reapply_templates_only,
non_interactive=non_interactive,
only_min_version_update=only_min_version_update,
)
update_min_airflow_version(
provider_package_id=provider_id,
with_breaking_changes=with_breaking_changes,
maybe_with_new_features=maybe_with_new_features,
)
with ci_group(
f"Updates changelog for last release of package '{provider_id}'",
skip_printing_title=only_min_version_update,
):
update_changelog(
package_id=provider_id,
base_branch=base_branch,
reapply_templates_only=reapply_templates_only,
with_breaking_changes=with_breaking_changes,
maybe_with_new_features=maybe_with_new_features,
only_min_version_update=only_min_version_update,
)
except PrepareReleaseDocsNoChangesException:
no_changes_packages.append(provider_id)
except PrepareReleaseDocsChangesOnlyException:
doc_only_packages.append(provider_id)
except PrepareReleaseDocsErrorOccurredException:
error_packages.append(provider_id)
except PrepareReleaseDocsUserSkippedException:
user_skipped_packages.append(provider_id)
except PackageSuspendedException:
suspended_packages.append(provider_id)
except PrepareReleaseDocsUserQuitException:
break
else:
if provider_metadata["state"] == "removed":
removed_packages.append(provider_id)
else:
success_packages.append(provider_id)
get_console().print()
get_console().print("\n[info]Summary of prepared documentation:\n")
provider_action_summary(
"Success" if not only_min_version_update else "Min Version Bumped",
MessageType.SUCCESS,
success_packages,
)
provider_action_summary("Scheduled for removal", MessageType.SUCCESS, removed_packages)
provider_action_summary("Docs only", MessageType.SUCCESS, doc_only_packages)
provider_action_summary(
"Skipped on no changes" if not only_min_version_update else "Min Version Not Bumped",
MessageType.WARNING,
no_changes_packages,
)
provider_action_summary("Suspended", MessageType.WARNING, suspended_packages)
provider_action_summary("Skipped by user", MessageType.SPECIAL, user_skipped_packages)
provider_action_summary("Errors", MessageType.ERROR, error_packages)
if error_packages:
get_console().print("\n[errors]There were errors when generating packages. Exiting!\n")
sys.exit(1)
if not success_packages and not doc_only_packages and not removed_packages:
get_console().print("\n[warning]No packages prepared!\n")
sys.exit(0)
get_console().print("\n[success]Successfully prepared documentation for packages!\n\n")
get_console().print(
"\n[info]Please review the updated files, classify the changelog entries and commit the changes.\n"
)
def basic_provider_checks(provider_package_id: str) -> dict[str, Any]:
provider_packages_metadata = get_provider_packages_metadata()
provider_metadata = provider_packages_metadata.get(provider_package_id)
if not provider_metadata:
get_console().print(f"[error]The package {provider_package_id} is not a provider package. Exiting[/]")
sys.exit(1)
if provider_metadata["state"] == "removed":
get_console().print(
f"[warning]The package: {provider_package_id} is scheduled for removal, but "
f"since you asked for it, it will be built [/]\n"
)
elif provider_metadata.get("state") == "suspended":
get_console().print(f"[warning]The package: {provider_package_id} is suspended skipping it [/]\n")
raise PackageSuspendedException()
return provider_metadata
@release_management.command(
name="prepare-provider-packages",
help="Prepare sdist/whl packages of Airflow Providers.",
)
@option_package_format
@option_version_suffix_for_pypi
@click.option(
"--package-list-file",
type=click.File("rt"),
help="Read list of packages from text file (one package per line).",
)
@click.option(
"--skip-tag-check",
default=False,
is_flag=True,
help="Skip checking if the tag already exists in the remote repository",
)
@click.option(
"--skip-deleting-generated-files",
default=False,
is_flag=True,
help="Skip deleting files that were used to generate provider package. Useful for debugging and "
"developing changes to the build process.",
)
@click.option(
"--clean-dist",
default=False,
is_flag=True,
help="Clean dist directory before building packages. Useful when you want to build multiple packages "
" in a clean environment",
)
@click.option(
"--package-list",
envvar="PACKAGE_LIST",
type=str,
help="Optional, contains comma-separated list of package ids that are processed for documentation "
"building, and document publishing. It is an easier alternative to adding individual packages as"
" arguments to every command. This overrides the packages passed as arguments.",
)
@option_dry_run
@option_github_repository
@option_include_not_ready_providers
@option_include_removed_providers
@argument_provider_packages
@option_verbose
def prepare_provider_packages(
clean_dist: bool,
package_list: str,
github_repository: str,
include_not_ready_providers: bool,
include_removed_providers: bool,
package_format: str,
package_list_file: IO | None,
provider_packages: tuple[str, ...],
skip_deleting_generated_files: bool,
skip_tag_check: bool,
version_suffix_for_pypi: str,
):
check_python_version(release_provider_packages=True)
perform_environment_checks()
fix_ownership_using_docker()
cleanup_python_generated_files()
packages_list_as_tuple: tuple[str, ...] = ()
if package_list and len(package_list):
get_console().print(f"\n[info]Populating provider list from PACKAGE_LIST env as {package_list}")
# Override provider_packages with values from PACKAGE_LIST
packages_list_as_tuple = tuple(package_list.split(","))
if provider_packages and packages_list_as_tuple:
get_console().print(
f"[warning]Both package arguments and --package-list / PACKAGE_LIST passed. "
f"Overriding to {packages_list_as_tuple}"
)
provider_packages = packages_list_as_tuple or provider_packages
packages_list = get_packages_list_to_act_on(
package_list_file=package_list_file,
provider_packages=provider_packages,
include_removed=include_removed_providers,
include_not_ready=include_not_ready_providers,
)
if not skip_tag_check:
run_command(["git", "remote", "rm", "apache-https-for-providers"], check=False, stderr=DEVNULL)
make_sure_remote_apache_exists_and_fetch(github_repository=github_repository)
success_packages = []
skipped_as_already_released_packages = []
suspended_packages = []
wrong_setup_packages = []
error_packages = []
if clean_dist:
get_console().print("\n[warning]Cleaning dist directory before building packages[/]\n")
shutil.rmtree(DIST_DIR, ignore_errors=True)
DIST_DIR.mkdir(parents=True, exist_ok=True)
for provider_id in packages_list:
package_version = version_suffix_for_pypi
try:
basic_provider_checks(provider_id)
if not skip_tag_check:
should_skip, package_version = should_skip_the_package(provider_id, package_version)
if should_skip:
continue
get_console().print()
with ci_group(f"Preparing provider package [special]{provider_id}"):
get_console().print()
target_provider_root_sources_path = copy_provider_sources_to_target(provider_id)
generate_build_files(
provider_id=provider_id,
version_suffix=package_version,
target_provider_root_sources_path=target_provider_root_sources_path,
)
cleanup_build_remnants(target_provider_root_sources_path)
build_provider_package(
provider_id=provider_id,
package_format=package_format,
target_provider_root_sources_path=target_provider_root_sources_path,
)
move_built_packages_and_cleanup(
target_provider_root_sources_path, DIST_DIR, skip_cleanup=skip_deleting_generated_files
)
except PrepareReleasePackageTagExistException:
skipped_as_already_released_packages.append(provider_id)
except PrepareReleasePackageWrongSetupException:
wrong_setup_packages.append(provider_id)
except PrepareReleasePackageErrorBuildingPackageException:
error_packages.append(provider_id)
except PackageSuspendedException:
suspended_packages.append(provider_id)
else:
get_console().print(f"\n[success]Generated package [special]{provider_id}")
success_packages.append(provider_id)
if not skip_deleting_generated_files:
shutil.rmtree(GENERATED_PROVIDER_PACKAGES_DIR, ignore_errors=True)
get_console().print()
get_console().print("\n[info]Summary of prepared packages:\n")
provider_action_summary("Success", MessageType.SUCCESS, success_packages)
provider_action_summary(
"Skipped as already released", MessageType.SUCCESS, skipped_as_already_released_packages
)
provider_action_summary("Suspended", MessageType.WARNING, suspended_packages)
provider_action_summary("Wrong setup generated", MessageType.ERROR, wrong_setup_packages)
provider_action_summary("Errors", MessageType.ERROR, error_packages)
if error_packages or wrong_setup_packages:
get_console().print("\n[errors]There were errors when generating packages. Exiting!\n")
sys.exit(1)
if not success_packages and not skipped_as_already_released_packages:
get_console().print("\n[warning]No packages prepared!\n")
sys.exit(0)
get_console().print("\n[success]Successfully built packages!\n\n")
packages = DistributionPackageInfo.dist_packages(
package_format=package_format, dist_directory=DIST_DIR, build_type="providers"
)
get_console().print()
_check_sdist_to_wheel_dists(packages)
get_console().print("\n[info]Packages available in dist:\n")
for dist_info in packages: