-
Notifications
You must be signed in to change notification settings - Fork 23.7k
/
release.py
executable file
·1495 lines (1084 loc) · 50.2 KB
/
release.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
"""Manage upstream ansible-core releases."""
from __future__ import annotations
import argparse
import contextlib
import dataclasses
import datetime
import enum
import functools
import gzip
import hashlib
import http.client
import inspect
import json
import math
import os
import pathlib
import re
import secrets
import shlex
import shutil
import stat
import subprocess
import sys
import tarfile
import tempfile
import typing as t
import urllib.error
import urllib.parse
import urllib.request
import venv
import webbrowser
import zipfile
import jinja2
from packaging.version import Version, InvalidVersion
# region CLI Framework
C = t.TypeVar("C", bound=t.Callable[..., None])
def path_to_str(value: t.Any) -> str:
"""Return the given value converted to a string suitable for use as a command line argument."""
return f"{value}/" if isinstance(value, pathlib.Path) and value.is_dir() else str(value)
@t.overload
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str, capture_output: t.Literal[True]) -> CompletedProcess:
...
@t.overload
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str, capture_output: t.Literal[False]) -> None:
...
@t.overload
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str) -> None:
...
def run(
*args: t.Any,
env: dict[str, t.Any] | None,
cwd: pathlib.Path | str,
capture_output: bool = False,
) -> CompletedProcess | None:
"""Run the specified command."""
args = [arg.relative_to(cwd) if isinstance(arg, pathlib.Path) else arg for arg in args]
str_args = tuple(path_to_str(arg) for arg in args)
str_env = {key: path_to_str(value) for key, value in env.items()} if env is not None else None
display.show(f"--> {shlex.join(str_args)}", color=Display.CYAN)
try:
p = subprocess.run(str_args, check=True, text=True, env=str_env, cwd=cwd, capture_output=capture_output)
except subprocess.CalledProcessError as ex:
# improve type hinting and include stdout/stderr (if any) in the message
raise CalledProcessError(
message=str(ex),
cmd=str_args,
status=ex.returncode,
stdout=ex.stdout,
stderr=ex.stderr,
) from None
if not capture_output:
return None
# improve type hinting
return CompletedProcess(
stdout=p.stdout,
stderr=p.stderr,
)
@contextlib.contextmanager
def suppress_when(error_as_warning: bool) -> t.Generator[None, None, None]:
"""Conditionally convert an ApplicationError in the provided context to a warning."""
if error_as_warning:
try:
yield
except ApplicationError as ex:
display.warning(ex)
else:
yield
class ApplicationError(Exception):
"""A fatal application error which will be shown without a traceback."""
class CalledProcessError(Exception):
"""Results from a failed process."""
def __init__(self, message: str, cmd: tuple[str, ...], status: int, stdout: str | None, stderr: str | None) -> None:
if stdout and (stdout := stdout.strip()):
message += f"\n>>> Standard Output\n{stdout}"
if stderr and (stderr := stderr.strip()):
message += f"\n>>> Standard Error\n{stderr}"
super().__init__(message)
self.cmd = cmd
self.status = status
self.stdout = stdout
self.stderr = stderr
@dataclasses.dataclass(frozen=True)
class CompletedProcess:
"""Results from a completed process."""
stdout: str
stderr: str
class Display:
"""Display interface for sending output to the console."""
CLEAR = "\033[0m"
RED = "\033[31m"
BLUE = "\033[34m"
PURPLE = "\033[35m"
CYAN = "\033[36m"
def fatal(self, message: t.Any) -> None:
"""Print a fatal message to the console."""
self.show(f"FATAL: {message}", color=self.RED)
def warning(self, message: t.Any) -> None:
"""Print a warning message to the console."""
self.show(f"WARNING: {message}", color=self.PURPLE)
def show(self, message: t.Any, color: str | None = None) -> None:
"""Print a message to the console."""
print(f"{color or self.CLEAR}{message}{self.CLEAR}", flush=True)
class CommandFramework:
"""
Simple command line framework inspired by nox.
Argument parsing is handled by argparse. Each function annotated with an instance of this class becomes a subcommand.
Options are shared across all commands, and are defined by providing kwargs when creating an instance of this class.
Options are only defined for commands which have a matching parameter.
The name of each kwarg is the option name, which will be prefixed with `--` and with underscores converted to dashes.
The value of each kwarg is passed as kwargs to ArgumentParser.add_argument. Passing None results in an internal only parameter.
The following custom kwargs are recognized and are not passed to add_argument:
name - Override the positional argument (option) passed to add_argument.
exclusive - Put the argument in an exclusive group of the given name.
"""
def __init__(self, **kwargs: dict[str, t.Any] | None) -> None:
self.commands: list[t.Callable[..., None]] = []
self.arguments = kwargs
self.parsed_arguments: argparse.Namespace | None = None
def __call__(self, func: C) -> C:
"""Register the decorated function as a CLI command."""
self.commands.append(func)
return func
def run(self, *args: t.Callable[..., None], **kwargs) -> None:
"""Run the specified command(s), using any provided internal args."""
for arg in args:
self._run(arg, **kwargs)
def main(self) -> None:
"""Main program entry point."""
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(metavar="COMMAND", required=True)
for func in self.commands:
func_parser = subparsers.add_parser(self._format_command_name(func), description=func.__doc__, help=func.__doc__)
func_parser.set_defaults(func=func)
exclusive_groups = {}
signature = inspect.signature(func)
for name in signature.parameters:
if name not in self.arguments:
raise RuntimeError(f"The '{name}' argument, used by '{func.__name__}', has not been defined.")
if (arguments := self.arguments.get(name)) is None:
continue # internal use
arguments = arguments.copy()
exclusive = arguments.pop("exclusive", None)
# noinspection PyProtectedMember, PyUnresolvedReferences
command_parser: argparse._ActionsContainer
if exclusive:
if exclusive not in exclusive_groups:
exclusive_groups[exclusive] = func_parser.add_mutually_exclusive_group()
command_parser = exclusive_groups[exclusive]
else:
command_parser = func_parser
if option_name := arguments.pop("name", None):
arguments.update(dest=name)
else:
option_name = f"--{name.replace('_', '-')}"
command_parser.add_argument(option_name, **arguments)
try:
# noinspection PyUnresolvedReferences
import argcomplete
except ImportError:
pass
else:
argcomplete.autocomplete(parser)
self.parsed_arguments = parser.parse_args()
try:
self.run(self.parsed_arguments.func)
except ApplicationError as ex:
display.fatal(ex)
sys.exit(1)
def _run(self, func: t.Callable[..., None], **kwargs) -> None:
"""Run the specified command, using any provided internal args."""
signature = inspect.signature(func)
func_args = {name: getattr(self.parsed_arguments, name) for name in signature.parameters if hasattr(self.parsed_arguments, name)}
func_args.update({name: value for name, value in kwargs.items() if name in signature.parameters})
printable_args = ", ".join(f"{name}={repr(value)}" for name, value in func_args.items())
label = f"{self._format_command_name(func)}({printable_args})"
display.show(f"==> {label}", color=Display.BLUE)
try:
func(**func_args)
except BaseException:
display.show(f"!!! {label}", color=Display.RED)
raise
display.show(f"<== {label}", color=Display.BLUE)
@staticmethod
def _format_command_name(func: t.Callable[..., None]) -> str:
"""Return the friendly name of the given command."""
return func.__name__.replace("_", "-")
display = Display()
# endregion
# region Data Classes
@dataclasses.dataclass(frozen=True)
class GitHubRelease:
"""Details required to create a GitHub release."""
user: str
repo: str
tag: str
target: str
title: str
body: str
pre_release: bool
@dataclasses.dataclass(frozen=True)
class PullRequest:
"""Details required to create a pull request."""
upstream_user: str
upstream_repo: str
upstream_branch: str
user: str
repo: str
branch: str
title: str
body: str
@dataclasses.dataclass(frozen=True)
class Remote:
"""Details about a git remote."""
name: str
user: str
repo: str
@dataclasses.dataclass(frozen=True)
class Remotes:
"""Details about git removes."""
fork: Remote
upstream: Remote
@dataclasses.dataclass(frozen=True)
class GitState:
"""Details about the state of the git repository."""
remotes: Remotes
branch: str | None
commit: str
@dataclasses.dataclass(frozen=True)
class ReleaseArtifact:
"""Information about a release artifact on PyPI."""
package_type: str
package_label: str
url: str
size: int
digest: str
digest_algorithm: str
@dataclasses.dataclass(frozen=True)
class ReleaseAnnouncement:
"""Contents of a release announcement."""
subject: str
body: str
# endregion
# region Utilities
SCRIPT_DIR = pathlib.Path(__file__).parent.resolve()
CHECKOUT_DIR = SCRIPT_DIR.parent
ANSIBLE_LIB_DIR = CHECKOUT_DIR / "lib"
ANSIBLE_DIR = ANSIBLE_LIB_DIR / "ansible"
ANSIBLE_BIN_DIR = CHECKOUT_DIR / "bin"
ANSIBLE_RELEASE_FILE = ANSIBLE_DIR / "release.py"
ANSIBLE_REQUIREMENTS_FILE = CHECKOUT_DIR / "requirements.txt"
DIST_DIR = CHECKOUT_DIR / "dist"
VENV_DIR = DIST_DIR / ".venv" / "release"
CHANGELOGS_DIR = CHECKOUT_DIR / "changelogs"
CHANGELOGS_FRAGMENTS_DIR = CHANGELOGS_DIR / "fragments"
ANSIBLE_VERSION_PATTERN = re.compile("^__version__ = '(?P<version>.*)'$", re.MULTILINE)
ANSIBLE_VERSION_FORMAT = "__version__ = '{version}'"
DIGEST_ALGORITHM = "sha256"
# These endpoint names match those defined as defaults in twine.
# See: https://github.com/pypa/twine/blob/9c2c0a1c535155931c3d879359330cb836950c6a/twine/utils.py#L82-L85
PYPI_ENDPOINTS = dict(
pypi="https://pypi.org/pypi",
testpypi="https://test.pypi.org/pypi",
)
PIP_ENV = dict(
PIP_REQUIRE_VIRTUALENV="yes",
PIP_DISABLE_PIP_VERSION_CHECK="yes",
)
class VersionMode(enum.Enum):
"""How to handle the ansible-core version."""
DEFAULT = enum.auto()
"""Do not allow development versions. Do not allow post release versions."""
STRIP_POST = enum.auto()
"""Do not allow development versions. Strip the post release from the version if present."""
REQUIRE_POST = enum.auto()
"""Do not allow development versions. Require a post release version."""
REQUIRE_DEV_POST = enum.auto()
"""Require a development or post release version."""
ALLOW_DEV_POST = enum.auto()
"""Allow development and post release versions."""
def apply(self, version: Version) -> Version:
"""Apply the mode to the given version and return the result."""
original_version = version
release_component_count = 3
if len(version.release) != release_component_count:
raise ApplicationError(f"Version {version} contains {version.release} release components instead of {release_component_count}.")
if version.epoch:
raise ApplicationError(f"Version {version} contains an epoch component: {version.epoch}")
if version.local is not None:
raise ApplicationError(f"Version {version} contains a local component: {version.local}")
if version.is_devrelease and version.is_postrelease:
raise ApplicationError(f"Version {version} is a development and post release version.")
if self == VersionMode.ALLOW_DEV_POST:
return version
if self == VersionMode.REQUIRE_DEV_POST:
if not version.is_devrelease and not version.is_postrelease:
raise ApplicationError(f"Version {version} is not a development or post release version.")
return version
if version.is_devrelease:
raise ApplicationError(f"Version {version} is a development release: {version.dev}")
if self == VersionMode.STRIP_POST:
if version.is_postrelease:
version = Version(str(version).removesuffix(f".post{version.post}"))
display.warning(f"Using version {version} by stripping the post release suffix from version {original_version}.")
return version
if self == VersionMode.REQUIRE_POST:
if not version.is_postrelease:
raise ApplicationError(f"Version {version} is not a post release version.")
return version
if version.is_postrelease:
raise ApplicationError(f"Version {version} is a post release.")
if self == VersionMode.DEFAULT:
return version
raise NotImplementedError(self)
@t.overload
def git(*args: t.Any, capture_output: t.Literal[True]) -> CompletedProcess:
...
@t.overload
def git(*args: t.Any, capture_output: t.Literal[False]) -> None:
...
@t.overload
def git(*args: t.Any) -> None:
...
def git(*args: t.Any, capture_output: t.Literal[True] | t.Literal[False] = False) -> CompletedProcess | None:
"""Run the specified git command."""
return run("git", *args, env=None, cwd=CHECKOUT_DIR, capture_output=capture_output)
def get_commit(rev: str | None = None) -> str:
"""Return the commit associated with the given rev, or HEAD if no rev is given."""
try:
return git("rev-parse", "--quiet", "--verify", "--end-of-options", f"{rev or 'HEAD'}^{{commit}}", capture_output=True).stdout.strip()
except CalledProcessError as ex:
if ex.status == 1 and not ex.stdout and not ex.stderr:
raise ApplicationError(f"Could not find commit: {rev}") from None
raise
def prepare_pull_request(version: Version, branch: str, title: str, add: t.Iterable[pathlib.Path | str], allow_stale: bool) -> PullRequest:
"""Return pull request parameters using the provided details."""
git_state = get_git_state(version, allow_stale)
if not git("status", "--porcelain", "--untracked-files=no", capture_output=True).stdout.strip():
raise ApplicationError("There are no changes to commit. Did you skip a step?")
upstream_branch = get_upstream_branch(version)
body = create_pull_request_body(title)
git("checkout", "-b", branch)
git("add", *add)
git("commit", "-m", title)
git("push", "--set-upstream", git_state.remotes.fork.name, branch)
git("checkout", git_state.branch or git_state.commit)
git("branch", "-d", branch)
pr = PullRequest(
upstream_user=git_state.remotes.upstream.user,
upstream_repo=git_state.remotes.upstream.repo,
upstream_branch=upstream_branch,
user=git_state.remotes.fork.user,
repo=git_state.remotes.fork.repo,
branch=branch,
title=title,
body=body,
)
return pr
def create_github_release(release: GitHubRelease) -> None:
"""Open a browser tab for creating the given GitHub release."""
# See: https://docs.github.com/en/repositories/releasing-projects-on-github/automation-for-release-forms-with-query-parameters
params = dict(
tag=release.tag,
target=release.target,
title=release.title,
body=release.body,
prerelease=1 if release.pre_release else 0,
)
query_string = urllib.parse.urlencode(params)
url = f"https://github.com/{release.user}/{release.repo}/releases/new?{query_string}"
display.show("Opening release creation page in new tab using default browser ...")
webbrowser.open_new_tab(url)
def create_pull_request(pr: PullRequest) -> None:
"""Open a browser tab for creating the given pull request."""
# See: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/using-query-parameters-to-create-a-pull-request # noqa
params = dict(
quick_pull=1,
title=pr.title,
body=pr.body,
)
query_string = urllib.parse.urlencode(params)
url = f"https://github.com/{pr.upstream_user}/{pr.upstream_repo}/compare/{pr.upstream_branch}...{pr.user}:{pr.repo}:{pr.branch}?{query_string}"
display.show("Opening pull request in new tab using default browser ...")
webbrowser.open_new_tab(url)
def create_pull_request_body(title: str) -> str:
"""Return a simple pull request body created from the given title."""
body = f"""
##### SUMMARY
{title}
##### ISSUE TYPE
Feature Pull Request
"""
return body.lstrip()
def get_remote(name: str, push: bool) -> Remote:
"""Return details about the specified remote."""
remote_url = git("remote", "get-url", *(["--push"] if push else []), name, capture_output=True).stdout.strip()
remote_match = re.search(r"[@/]github[.]com[:/](?P<user>[^/]+)/(?P<repo>[^.]+)(?:[.]git)?$", remote_url)
if not remote_match:
raise RuntimeError(f"Unable to identify the user and repo in the '{name}' remote: {remote_url}")
remote = Remote(
name=name,
user=remote_match.group("user"),
repo=remote_match.group("repo"),
)
return remote
@functools.cache
def get_remotes() -> Remotes:
"""Return details about the remotes we need to use."""
# assume the devel branch has its upstream remote pointing to the user's fork
fork_remote_name = git("branch", "--list", "devel", "--format=%(upstream:remotename)", capture_output=True).stdout.strip()
if not fork_remote_name:
raise ApplicationError("Could not determine the remote for your fork of Ansible.")
display.show(f"Detected '{fork_remote_name}' as the remote for your fork of Ansible.")
# assume there is only one ansible org remote, which would allow release testing using another repo in the same org without special configuration
all_remotes = git("remote", "-v", capture_output=True).stdout.strip().splitlines()
ansible_remote_names = set(line.split()[0] for line in all_remotes if re.search(r"[@/]github[.]com[:/]ansible/", line))
if not ansible_remote_names:
raise ApplicationError(f"Could not determine the remote which '{fork_remote_name}' was forked from.")
if len(ansible_remote_names) > 1:
raise ApplicationError(f"Found multiple candidates for the remote from which '{fork_remote_name}' was forked from: {', '.join(ansible_remote_names)}")
upstream_remote_name = ansible_remote_names.pop()
display.show(f"Detected '{upstream_remote_name}' as the remote from which '{fork_remote_name}' was forked from.")
if fork_remote_name == upstream_remote_name:
raise ApplicationError("The remote for your fork of Ansible cannot be the same as the remote from which it was forked.")
remotes = Remotes(
fork=get_remote(fork_remote_name, push=True),
upstream=get_remote(upstream_remote_name, push=False),
)
return remotes
def get_upstream_branch(version: Version) -> str:
"""Return the upstream branch name for the given version."""
return f"stable-{version.major}.{version.minor}"
def get_git_state(version: Version, allow_stale: bool) -> GitState:
"""Return information about the current state of the git repository."""
remotes = get_remotes()
upstream_branch = get_upstream_branch(version)
git("fetch", remotes.upstream.name, upstream_branch)
upstream_ref = f"{remotes.upstream.name}/{upstream_branch}"
upstream_commit = get_commit(upstream_ref)
commit = get_commit()
if commit != upstream_commit:
with suppress_when(allow_stale):
raise ApplicationError(f"The current commit ({commit}) does not match {upstream_ref} ({upstream_commit}).")
branch = git("branch", "--show-current", capture_output=True).stdout.strip() or None
state = GitState(
remotes=remotes,
branch=branch,
commit=commit,
)
return state
@functools.cache
def ensure_venv() -> dict[str, t.Any]:
"""Ensure the release venv is ready and return the env vars needed to use it."""
# TODO: consider freezing the ansible and release requirements along with their dependencies
ansible_requirements = ANSIBLE_REQUIREMENTS_FILE.read_text()
release_requirements = """
build
twine
"""
requirements_file = CHECKOUT_DIR / "test/sanity/code-smell/package-data.requirements.txt"
requirements_content = requirements_file.read_text()
requirements_content += ansible_requirements
requirements_content += release_requirements
requirements_hash = hashlib.sha256(requirements_content.encode()).hexdigest()[:8]
python_version = ".".join(map(str, sys.version_info[:2]))
venv_dir = VENV_DIR / python_version / requirements_hash
venv_bin_dir = venv_dir / "bin"
venv_requirements_file = venv_dir / "requirements.txt"
venv_marker_file = venv_dir / "marker.txt"
env = os.environ.copy()
env.pop("PYTHONPATH", None) # avoid interference from ansible being injected into the environment
env.update(
PATH=os.pathsep.join((str(venv_bin_dir), env["PATH"])),
)
if not venv_marker_file.exists():
display.show(f"Creating a Python {python_version} virtual environment ({requirements_hash}) ...")
if venv_dir.exists():
shutil.rmtree(venv_dir)
venv.create(venv_dir, with_pip=True)
venv_requirements_file.write_text(requirements_content)
run("pip", "install", "-r", venv_requirements_file, env=env | PIP_ENV, cwd=CHECKOUT_DIR)
venv_marker_file.touch()
return env
def get_ansible_version(version: str | None = None, /, commit: str | None = None, mode: VersionMode = VersionMode.DEFAULT) -> Version:
"""Parse and return the current ansible-core version, the provided version or the version from the provided commit."""
if version and commit:
raise ValueError("Specify only one of: version, commit")
if version:
source = ""
else:
if commit:
current = git("show", f"{commit}:{ANSIBLE_RELEASE_FILE.relative_to(CHECKOUT_DIR)}", capture_output=True).stdout
else:
current = ANSIBLE_RELEASE_FILE.read_text()
if not (match := ANSIBLE_VERSION_PATTERN.search(current)):
raise RuntimeError("Failed to get the ansible-core version.")
version = match.group("version")
source = f" in '{ANSIBLE_RELEASE_FILE}'"
try:
parsed_version = Version(version)
except InvalidVersion:
raise ApplicationError(f"Invalid version{source}: {version}") from None
parsed_version = mode.apply(parsed_version)
return parsed_version
def get_next_version(version: Version, /, final: bool = False, pre: str | None = None, mode: VersionMode = VersionMode.DEFAULT) -> Version:
"""Return the next version after the specified version."""
# TODO: consider using development versions instead of post versions after a release is published
pre = pre or ""
micro = version.micro
if version.is_devrelease:
# The next version of a development release is the same version without the development component.
if final:
pre = ""
elif not pre and version.pre is not None:
pre = f"{version.pre[0]}{version.pre[1]}"
elif version.is_postrelease:
# The next version of a post release is the next pre-release *or* micro release component.
if final:
pre = ""
elif not pre and version.pre is not None:
pre = f"{version.pre[0]}{version.pre[1] + 1}"
if version.pre is None:
micro = version.micro + 1
else:
raise ApplicationError(f"Version {version} is not a development or post release version.")
version = f"{version.major}.{version.minor}.{micro}{pre}"
return get_ansible_version(version, mode=mode)
def check_ansible_version(current_version: Version, requested_version: Version) -> None:
"""Verify the requested version is valid for the current version."""
if requested_version.release[:2] != current_version.release[:2]:
raise ApplicationError(f"Version {requested_version} does not match the major and minor portion of the current version: {current_version}")
if requested_version < current_version:
raise ApplicationError(f"Version {requested_version} is older than the current version: {current_version}")
# TODO: consider additional checks to avoid mistakes when incrementing the release version
def set_ansible_version(current_version: Version, requested_version: Version) -> None:
"""Set the current ansible-core version."""
check_ansible_version(current_version, requested_version)
if requested_version == current_version:
return
display.show(f"Updating version {current_version} to {requested_version} ...")
current = ANSIBLE_RELEASE_FILE.read_text()
updated = ANSIBLE_VERSION_PATTERN.sub(ANSIBLE_VERSION_FORMAT.format(version=requested_version), current)
if current == updated:
raise RuntimeError("Failed to set the ansible-core version.")
ANSIBLE_RELEASE_FILE.write_text(updated)
def create_reproducible_sdist(original_path: pathlib.Path, output_path: pathlib.Path, mtime: int) -> None:
"""Read the specified sdist and write out a new copy with uniform file metadata at the specified location."""
with tarfile.open(original_path) as original_archive:
with tempfile.TemporaryDirectory() as temp_dir:
tar_file = pathlib.Path(temp_dir) / "sdist.tar"
with tarfile.open(tar_file, mode="w") as tar_archive:
for original_info in original_archive.getmembers(): # type: tarfile.TarInfo
tar_archive.addfile(create_reproducible_tar_info(original_info, mtime), original_archive.extractfile(original_info))
with tar_file.open("rb") as tar_archive:
with gzip.GzipFile(output_path, "wb", mtime=mtime) as output_archive:
shutil.copyfileobj(tar_archive, output_archive)
def create_reproducible_tar_info(original: tarfile.TarInfo, mtime: int) -> tarfile.TarInfo:
"""Return a copy of the given TarInfo with uniform file metadata."""
sanitized = tarfile.TarInfo()
sanitized.name = original.name
sanitized.size = original.size
sanitized.mtime = mtime
sanitized.mode = (original.mode & ~(stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)) | stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR
sanitized.type = original.type
sanitized.linkname = original.linkname
sanitized.uid = 0
sanitized.gid = 0
sanitized.uname = "root"
sanitized.gname = "root"
if original.mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH):
sanitized.mode |= stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
return sanitized
def test_built_artifact(path: pathlib.Path) -> None:
"""Test the specified built artifact by installing it in a venv and running some basic commands."""
with tempfile.TemporaryDirectory() as temp_dir_name:
temp_dir = pathlib.Path(temp_dir_name)
venv_dir = temp_dir / "venv"
venv_bin_dir = venv_dir / "bin"
venv.create(venv_dir, with_pip=True)
env = os.environ.copy()
env.pop("PYTHONPATH", None) # avoid interference from ansible being injected into the environment
env.update(
PATH=os.pathsep.join((str(venv_bin_dir), env["PATH"])),
)
run("pip", "install", path, env=env | PIP_ENV, cwd=CHECKOUT_DIR)
run("ansible", "--version", env=env, cwd=CHECKOUT_DIR)
run("ansible-test", "--version", env=env, cwd=CHECKOUT_DIR)
def get_sdist_path(version: Version, dist_dir: pathlib.Path = DIST_DIR) -> pathlib.Path:
"""Return the path to the sdist file."""
return dist_dir / f"ansible_core-{version}.tar.gz"
def get_wheel_path(version: Version, dist_dir: pathlib.Path = DIST_DIR) -> pathlib.Path:
"""Return the path to the wheel file."""
return dist_dir / f"ansible_core-{version}-py3-none-any.whl"
def calculate_digest(path: pathlib.Path) -> str:
"""Return the digest for the specified file."""
# TODO: use hashlib.file_digest once Python 3.11 is the minimum supported version
return hashlib.new(DIGEST_ALGORITHM, path.read_bytes()).hexdigest()
@functools.cache
def get_release_artifact_details(repository: str, version: Version, validate: bool) -> list[ReleaseArtifact]:
"""Return information about the release artifacts hosted on PyPI."""
endpoint = PYPI_ENDPOINTS[repository]
url = f"{endpoint}/ansible-core/{version}/json"
opener = urllib.request.build_opener()
response: http.client.HTTPResponse
try:
with opener.open(url) as response:
data = json.load(response)
except urllib.error.HTTPError as ex:
if ex.status == http.HTTPStatus.NOT_FOUND:
raise ApplicationError(f"Version {version} not found on PyPI.") from None
raise RuntimeError(f"Failed to get {version} from PyPI: {ex}") from ex
artifacts = [describe_release_artifact(version, item, validate) for item in data["urls"]]
expected_artifact_types = {"bdist_wheel", "sdist"}
found_artifact_types = set(artifact.package_type for artifact in artifacts)
if found_artifact_types != expected_artifact_types:
raise RuntimeError(f"Expected {expected_artifact_types} artifact types, but found {found_artifact_types} instead.")
return artifacts
def describe_release_artifact(version: Version, item: dict[str, t.Any], validate: bool) -> ReleaseArtifact:
"""Return release artifact details extracted from the given PyPI data."""
package_type = item["packagetype"]
# The artifact URL is documented as stable, so is safe to put in release notes and announcements.
# See: https://github.com/pypi/warehouse/blame/c95be4a1055f4b36a8852715eb80318c81fc00ca/docs/api-reference/integration-guide.rst#L86-L90
url = item["url"]
pypi_size = item["size"]
pypi_digest = item["digests"][DIGEST_ALGORITHM]
if package_type == "bdist_wheel":
local_artifact_file = get_wheel_path(version)
package_label = "Built Distribution"
elif package_type == "sdist":
local_artifact_file = get_sdist_path(version)
package_label = "Source Distribution"
else:
raise NotImplementedError(f"Package type '{package_type}' is not supported.")
if validate:
try:
local_size = local_artifact_file.stat().st_size
local_digest = calculate_digest(local_artifact_file)
except FileNotFoundError:
raise ApplicationError(f"Missing local artifact: {local_artifact_file.relative_to(CHECKOUT_DIR)}") from None
if local_size != pypi_size:
raise ApplicationError(f"The {version} local {package_type} size {local_size} does not match the PyPI size {pypi_size}.")
if local_digest != pypi_digest:
raise ApplicationError(f"The {version} local {package_type} digest '{local_digest}' does not match the PyPI digest '{pypi_digest}'.")
return ReleaseArtifact(
package_type=package_type,
package_label=package_label,
url=url,
size=pypi_size,
digest=pypi_digest,
digest_algorithm=DIGEST_ALGORITHM.upper(),
)
def get_next_release_date(start: datetime.date, step: int, after: datetime.date) -> datetime.date:
"""Return the next release date."""
if start > after:
raise ValueError(f"{start=} is greater than {after=}")
current_delta = after - start
release_delta = datetime.timedelta(days=(math.floor(current_delta.days / step) + 1) * step)
release = start + release_delta
return release
def create_template_environment() -> jinja2.Environment:
"""Create and return a jinja2 environment."""
env = jinja2.Environment()
env.filters.update(
basename=os.path.basename,
)
return env
def create_github_release_notes(upstream: Remote, repository: str, version: Version, validate: bool) -> str:
"""Create and return GitHub release notes."""
env = create_template_environment()
template = env.from_string(GITHUB_RELEASE_NOTES_TEMPLATE)
variables = dict(
version=version,
releases=get_release_artifact_details(repository, version, validate),
changelog=f"https://github.com/{upstream.user}/{upstream.repo}/blob/v{version}/changelogs/CHANGELOG-v{version.major}.{version.minor}.rst",
)
release_notes = template.render(**variables).strip()
return release_notes
def create_release_announcement(upstream: Remote, repository: str, version: Version, validate: bool) -> ReleaseAnnouncement:
"""Create and return a release announcement message."""
env = create_template_environment()
subject_template = env.from_string(RELEASE_ANNOUNCEMENT_SUBJECT_TEMPLATE)
body_template = env.from_string(RELEASE_ANNOUNCEMENT_BODY_TEMPLATE)
today = datetime.datetime.now(tz=datetime.timezone.utc).date()
variables = dict(
version=version,
info=dict(
name="ansible-core",
short=f"{version.major}.{version.minor}",
releases=get_release_artifact_details(repository, version, validate),
),
next_rc=get_next_release_date(datetime.date(2021, 8, 9), 28, today),
next_ga=get_next_release_date(datetime.date(2021, 8, 16), 28, today),