| •1 |
#!/usr/bin/env python3 |
| 2 |
# PYTHON_ARGCOMPLETE_OK |
| 3 |
"""Manage upstream ansible-core releases.""" |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
import argparse |
| 8 |
import contextlib |
| 9 |
import dataclasses |
| 10 |
import datetime |
| 11 |
import enum |
| 12 |
import functools |
| 13 |
import gzip |
| 14 |
import hashlib |
| 15 |
import http.client |
| 16 |
import inspect |
| 17 |
import json |
| 18 |
import math |
| 19 |
import os |
| 20 |
import pathlib |
| 21 |
import re |
| 22 |
import secrets |
| 23 |
import shlex |
| 24 |
import shutil |
| 25 |
import stat |
| 26 |
import subprocess |
| 27 |
import sys |
| 28 |
import tarfile |
| 29 |
import tempfile |
| 30 |
import typing as t |
| 31 |
import urllib.error |
| 32 |
import urllib.parse |
| 33 |
import urllib.request |
| 34 |
import venv |
| 35 |
import webbrowser |
| 36 |
import zipfile |
| 37 |
|
| 38 |
import jinja2 |
| 39 |
|
| 40 |
from packaging.version import Version, InvalidVersion |
| 41 |
|
| 42 |
# region CLI Framework |
| 43 |
|
| 44 |
|
| 45 |
def path_to_str(value: t.Any) -> str: |
| 46 |
"""Return the given value converted to a string suitable for use as a command line argument.""" |
| 47 |
return f"{value}/" if isinstance(value, pathlib.Path) and value.is_dir() else str(value) |
| 48 |
|
| 49 |
|
| 50 |
@t.overload |
| 51 |
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str, capture_output: t.Literal[True]) -> CompletedProcess: ... |
| 52 |
|
| 53 |
|
| 54 |
@t.overload |
| 55 |
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str, capture_output: t.Literal[False]) -> None: ... |
| 56 |
|
| 57 |
|
| 58 |
@t.overload |
| 59 |
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str, capture_output: bool) -> CompletedProcess | None: ... |
| 60 |
|
| 61 |
|
| 62 |
@t.overload |
| 63 |
def run(*args: t.Any, env: dict[str, t.Any] | None, cwd: pathlib.Path | str) -> None: ... |
| 64 |
|
| 65 |
|
| 66 |
def run( |
| 67 |
*args: t.Any, |
| 68 |
env: dict[str, t.Any] | None, |
| 69 |
cwd: pathlib.Path | str, |
| 70 |
capture_output: bool = False, |
| 71 |
) -> CompletedProcess | None: |
| 72 |
"""Run the specified command.""" |
| 73 |
args = [arg.relative_to(cwd) if isinstance(arg, pathlib.Path) else arg for arg in args] |
| 74 |
|
| 75 |
str_args = tuple(path_to_str(arg) for arg in args) |
| 76 |
str_env = {key: path_to_str(value) for key, value in env.items()} if env is not None else None |
| 77 |
|
| 78 |
display.show(f"--> {shlex.join(str_args)}", color=Display.CYAN) |
| 79 |
|
| 80 |
try: |
| 81 |
p = subprocess.run(str_args, check=True, text=True, env=str_env, cwd=cwd, capture_output=capture_output) |
| 82 |
except subprocess.CalledProcessError as ex: |
| 83 |
# improve type hinting and include stdout/stderr (if any) in the message |
| 84 |
raise CalledProcessError( |
| 85 |
message=str(ex), |
| 86 |
cmd=str_args, |
| 87 |
status=ex.returncode, |
| 88 |
stdout=ex.stdout, |
| 89 |
stderr=ex.stderr, |
| 90 |
) from None |
| 91 |
|
| 92 |
if not capture_output: |
| 93 |
return None |
| 94 |
|
| 95 |
# improve type hinting |
| 96 |
return CompletedProcess( |
| 97 |
stdout=p.stdout, |
| 98 |
stderr=p.stderr, |
| 99 |
) |
| 100 |
|
| 101 |
|
| 102 |
@contextlib.contextmanager |
| 103 |
def suppress_when(error_as_warning: bool) -> t.Generator[None, None, None]: |
| 104 |
"""Conditionally convert an ApplicationError in the provided context to a warning.""" |
| 105 |
if error_as_warning: |
| 106 |
try: |
| 107 |
yield |
| 108 |
except ApplicationError as ex: |
| 109 |
display.warning(ex) |
| 110 |
else: |
| 111 |
yield |
| 112 |
|
| 113 |
|
| 114 |
class ApplicationError(Exception): |
| 115 |
"""A fatal application error which will be shown without a traceback.""" |
| 116 |
|
| 117 |
|
| 118 |
class CalledProcessError(Exception): |
| 119 |
"""Results from a failed process.""" |
| 120 |
|
| 121 |
def __init__(self, message: str, cmd: tuple[str, ...], status: int, stdout: str | None, stderr: str | None) -> None: |
| 122 |
if stdout and (stdout := stdout.strip()): |
| 123 |
message += f"\n>>> Standard Output\n{stdout}" |
| 124 |
|
| 125 |
if stderr and (stderr := stderr.strip()): |
| 126 |
message += f"\n>>> Standard Error\n{stderr}" |
| 127 |
|
| 128 |
super().__init__(message) |
| 129 |
|
| 130 |
self.cmd = cmd |
| 131 |
self.status = status |
| 132 |
self.stdout = stdout |
| 133 |
self.stderr = stderr |
| 134 |
|
| 135 |
|
| 136 |
@dataclasses.dataclass(frozen=True) |
| 137 |
class CompletedProcess: |
| 138 |
"""Results from a completed process.""" |
| 139 |
|
| 140 |
stdout: str |
| 141 |
stderr: str |
| 142 |
|
| 143 |
|
| 144 |
class Display: |
| 145 |
"""Display interface for sending output to the console.""" |
| 146 |
|
| 147 |
CLEAR = "\033[0m" |
| 148 |
RED = "\033[31m" |
| 149 |
BLUE = "\033[34m" |
| 150 |
PURPLE = "\033[35m" |
| 151 |
CYAN = "\033[36m" |
| 152 |
|
| 153 |
def fatal(self, message: t.Any) -> None: |
| 154 |
"""Print a fatal message to the console.""" |
| 155 |
self.show(f"FATAL: {message}", color=self.RED) |
| 156 |
|
| 157 |
def warning(self, message: t.Any) -> None: |
| 158 |
"""Print a warning message to the console.""" |
| 159 |
self.show(f"WARNING: {message}", color=self.PURPLE) |
| 160 |
|
| 161 |
def show(self, message: t.Any, color: str | None = None) -> None: |
| 162 |
"""Print a message to the console.""" |
| 163 |
print(f"{color or self.CLEAR}{message}{self.CLEAR}", flush=True) |
| 164 |
|
| 165 |
|
| 166 |
class CommandFramework: |
| 167 |
""" |
| 168 |
Simple command line framework inspired by nox. |
| 169 |
|
| 170 |
Argument parsing is handled by argparse. Each function annotated with an instance of this class becomes a subcommand. |
| 171 |
Options are shared across all commands, and are defined by providing kwargs when creating an instance of this class. |
| 172 |
Options are only defined for commands which have a matching parameter. |
| 173 |
|
| 174 |
The name of each kwarg is the option name, which will be prefixed with `--` and with underscores converted to dashes. |
| 175 |
The value of each kwarg is passed as kwargs to ArgumentParser.add_argument. Passing None results in an internal only parameter. |
| 176 |
|
| 177 |
The following custom kwargs are recognized and are not passed to add_argument: |
| 178 |
|
| 179 |
name - Override the positional argument (option) passed to add_argument. |
| 180 |
exclusive - Put the argument in an exclusive group of the given name. |
| 181 |
""" |
| 182 |
|
| 183 |
def __init__(self, **kwargs: dict[str, t.Any] | None) -> None: |
| 184 |
self.commands: list[t.Callable[..., None]] = [] |
| 185 |
self.arguments = kwargs |
| 186 |
self.parsed_arguments: argparse.Namespace | None = None |
| 187 |
|
| 188 |
def __call__[T: t.Callable[..., None]](self, func: T) -> T: |
| 189 |
"""Register the decorated function as a CLI command.""" |
| 190 |
self.commands.append(func) |
| 191 |
return func |
| 192 |
|
| 193 |
def run(self, *args: t.Callable[..., None], **kwargs) -> None: |
| 194 |
"""Run the specified command(s), using any provided internal args.""" |
| 195 |
for arg in args: |
| 196 |
self._run(arg, **kwargs) |
| 197 |
|
| 198 |
def main(self) -> None: |
| 199 |
"""Main program entry point.""" |
| 200 |
parser = argparse.ArgumentParser(description=__doc__) |
| 201 |
subparsers = parser.add_subparsers(metavar="COMMAND", required=True) |
| 202 |
|
| 203 |
for func in self.commands: |
| 204 |
func_parser = subparsers.add_parser(self._format_command_name(func), description=func.__doc__, help=func.__doc__) |
| 205 |
func_parser.set_defaults(func=func) |
| 206 |
|
| 207 |
exclusive_groups = {} |
| 208 |
signature = inspect.signature(func) |
| 209 |
|
| 210 |
for name in signature.parameters: |
| 211 |
if name not in self.arguments: |
| 212 |
raise RuntimeError(f"The '{name}' argument, used by '{func.__name__}', has not been defined.") |
| 213 |
|
| 214 |
if (arguments := self.arguments.get(name)) is None: |
| 215 |
continue # internal use |
| 216 |
|
| 217 |
arguments = arguments.copy() |
| 218 |
exclusive = arguments.pop("exclusive", None) |
| 219 |
|
| 220 |
# noinspection PyProtectedMember, PyUnresolvedReferences |
| 221 |
command_parser: argparse._ActionsContainer |
| 222 |
|
| 223 |
if exclusive: |
| 224 |
if exclusive not in exclusive_groups: |
| 225 |
exclusive_groups[exclusive] = func_parser.add_mutually_exclusive_group() |
| 226 |
|
| 227 |
command_parser = exclusive_groups[exclusive] |
| 228 |
else: |
| 229 |
command_parser = func_parser |
| 230 |
|
| 231 |
if option_name := arguments.pop("name", None): |
| 232 |
arguments.update(dest=name) |
| 233 |
else: |
| 234 |
option_name = f"--{name.replace('_', '-')}" |
| 235 |
|
| 236 |
command_parser.add_argument(option_name, **arguments) |
| 237 |
|
| 238 |
try: |
| 239 |
# noinspection PyUnresolvedReferences |
| 240 |
import argcomplete |
| 241 |
except ImportError: |
| 242 |
pass |
| 243 |
else: |
| 244 |
argcomplete.autocomplete(parser) |
| 245 |
|
| 246 |
self.parsed_arguments = parser.parse_args() |
| 247 |
|
| 248 |
try: |
| 249 |
self.run(self.parsed_arguments.func) |
| 250 |
except ApplicationError as ex: |
| 251 |
display.fatal(ex) |
| 252 |
sys.exit(1) |
| 253 |
|
| 254 |
def _run(self, func: t.Callable[..., None], **kwargs) -> None: |
| 255 |
"""Run the specified command, using any provided internal args.""" |
| 256 |
signature = inspect.signature(func) |
| 257 |
func_args = {name: getattr(self.parsed_arguments, name) for name in signature.parameters if hasattr(self.parsed_arguments, name)} |
| 258 |
func_args.update({name: value for name, value in kwargs.items() if name in signature.parameters}) |
| 259 |
printable_args = ", ".join(f"{name}={repr(value)}" for name, value in func_args.items()) |
| 260 |
label = f"{self._format_command_name(func)}({printable_args})" |
| 261 |
|
| 262 |
display.show(f"==> {label}", color=Display.BLUE) |
| 263 |
|
| 264 |
try: |
| 265 |
func(**func_args) |
| 266 |
except BaseException: |
| 267 |
display.show(f"!!! {label}", color=Display.RED) |
| 268 |
raise |
| 269 |
|
| 270 |
display.show(f"<== {label}", color=Display.BLUE) |
| 271 |
|
| 272 |
@staticmethod |
| 273 |
def _format_command_name(func: t.Callable[..., None]) -> str: |
| 274 |
"""Return the friendly name of the given command.""" |
| 275 |
return func.__name__.replace("_", "-") |
| 276 |
|
| 277 |
|
| 278 |
display = Display() |
| 279 |
|
| 280 |
|
| 281 |
# endregion |
| 282 |
# region Data Classes |
| 283 |
|
| 284 |
|
| 285 |
@dataclasses.dataclass(frozen=True) |
| 286 |
class GitHubRelease: |
| 287 |
"""Details required to create a GitHub release.""" |
| 288 |
|
| 289 |
user: str |
| 290 |
repo: str |
| 291 |
tag: str |
| 292 |
target: str |
| 293 |
title: str |
| 294 |
body: str |
| 295 |
pre_release: bool |
| 296 |
|
| 297 |
|
| 298 |
@dataclasses.dataclass(frozen=True) |
| 299 |
class PullRequest: |
| 300 |
"""Details required to create a pull request.""" |
| 301 |
|
| 302 |
upstream_user: str |
| 303 |
upstream_repo: str |
| 304 |
upstream_branch: str |
| 305 |
user: str |
| 306 |
repo: str |
| 307 |
branch: str |
| 308 |
title: str |
| 309 |
body: str |
| 310 |
|
| 311 |
|
| 312 |
@dataclasses.dataclass(frozen=True) |
| 313 |
class Remote: |
| 314 |
"""Details about a git remote.""" |
| 315 |
|
| 316 |
name: str |
| 317 |
user: str |
| 318 |
repo: str |
| 319 |
|
| 320 |
|
| 321 |
@dataclasses.dataclass(frozen=True) |
| 322 |
class Remotes: |
| 323 |
"""Details about git removes.""" |
| 324 |
|
| 325 |
fork: Remote |
| 326 |
upstream: Remote |
| 327 |
|
| 328 |
|
| 329 |
@dataclasses.dataclass(frozen=True) |
| 330 |
class GitState: |
| 331 |
"""Details about the state of the git repository.""" |
| 332 |
|
| 333 |
remotes: Remotes |
| 334 |
branch: str | None |
| 335 |
commit: str |
| 336 |
|
| 337 |
|
| 338 |
@dataclasses.dataclass(frozen=True) |
| 339 |
class ReleaseArtifact: |
| 340 |
"""Information about a release artifact on PyPI.""" |
| 341 |
|
| 342 |
package_type: str |
| 343 |
package_label: str |
| 344 |
url: str |
| 345 |
size: int |
| 346 |
digest: str |
| 347 |
digest_algorithm: str |
| 348 |
|
| 349 |
|
| 350 |
# endregion |
| 351 |
# region Utilities |
| 352 |
|
| 353 |
|
| 354 |
SCRIPT_DIR = pathlib.Path(__file__).parent.resolve() |
| 355 |
CHECKOUT_DIR = SCRIPT_DIR.parent |
| 356 |
|
| 357 |
ANSIBLE_LIB_DIR = CHECKOUT_DIR / "lib" |
| 358 |
ANSIBLE_DIR = ANSIBLE_LIB_DIR / "ansible" |
| 359 |
ANSIBLE_BIN_DIR = CHECKOUT_DIR / "bin" |
| 360 |
ANSIBLE_RELEASE_FILE = ANSIBLE_DIR / "release.py" |
| 361 |
ANSIBLE_REQUIREMENTS_FILE = CHECKOUT_DIR / "requirements.txt" |
| 362 |
ANSIBLE_CHANGELOG_REQUIREMENTS_FILE = CHECKOUT_DIR / "test/lib/ansible_test/_data/requirements/sanity.changelog.txt" |
| 363 |
ANSIBLE_PYPROJECT_TOML_FILE = CHECKOUT_DIR / "pyproject.toml" |
| 364 |
|
| 365 |
DIST_DIR = CHECKOUT_DIR / "dist" |
| 366 |
VENV_DIR = DIST_DIR / ".venv" / "release" |
| 367 |
|
| 368 |
CHANGELOGS_DIR = CHECKOUT_DIR / "changelogs" |
| 369 |
CHANGELOGS_FRAGMENTS_DIR = CHANGELOGS_DIR / "fragments" |
| 370 |
|
| 371 |
ANSIBLE_VERSION_PATTERN = re.compile("^__version__ = '(?P<version>.*)'$", re.MULTILINE) |
| 372 |
ANSIBLE_VERSION_FORMAT = "__version__ = '{version}'" |
| 373 |
|
| 374 |
DIGEST_ALGORITHM = "sha256" |
| 375 |
|
| 376 |
# These endpoint names match those defined as defaults in twine. |
| 377 |
# See: https://github.com/pypa/twine/blob/9c2c0a1c535155931c3d879359330cb836950c6a/twine/utils.py#L82-L85 |
| 378 |
PYPI_ENDPOINTS = dict( |
| 379 |
pypi="https://pypi.org/pypi", |
| 380 |
testpypi="https://test.pypi.org/pypi", |
| 381 |
) |
| 382 |
|
| 383 |
PIP_ENV = dict( |
| 384 |
PIP_REQUIRE_VIRTUALENV="yes", |
| 385 |
PIP_DISABLE_PIP_VERSION_CHECK="yes", |
| 386 |
) |
| 387 |
|
| 388 |
|
| 389 |
class VersionMode(enum.Enum): |
| 390 |
"""How to handle the ansible-core version.""" |
| 391 |
|
| 392 |
DEFAULT = enum.auto() |
| 393 |
"""Do not allow development versions. Do not allow post release versions.""" |
| 394 |
STRIP_POST = enum.auto() |
| 395 |
"""Do not allow development versions. Strip the post release from the version if present.""" |
| 396 |
REQUIRE_POST = enum.auto() |
| 397 |
"""Do not allow development versions. Require a post release version.""" |
| 398 |
REQUIRE_DEV_POST = enum.auto() |
| 399 |
"""Require a development or post release version.""" |
| 400 |
ALLOW_DEV_POST = enum.auto() |
| 401 |
"""Allow development and post release versions.""" |
| 402 |
|
| 403 |
def apply(self, version: Version) -> Version: |
| 404 |
"""Apply the mode to the given version and return the result.""" |
| 405 |
original_version = version |
| 406 |
|
| 407 |
release_component_count = 3 |
| 408 |
|
| 409 |
if len(version.release) != release_component_count: |
| 410 |
raise ApplicationError(f"Version {version} contains {version.release} release components instead of {release_component_count}.") |
| 411 |
|
| 412 |
if version.epoch: |
| 413 |
raise ApplicationError(f"Version {version} contains an epoch component: {version.epoch}") |
| 414 |
|
| 415 |
if version.local is not None: |
| 416 |
raise ApplicationError(f"Version {version} contains a local component: {version.local}") |
| 417 |
|
| 418 |
if version.is_devrelease and version.is_postrelease: |
| 419 |
raise ApplicationError(f"Version {version} is a development and post release version.") |
| 420 |
|
| 421 |
if self == VersionMode.ALLOW_DEV_POST: |
| 422 |
return version |
| 423 |
|
| 424 |
if self == VersionMode.REQUIRE_DEV_POST: |
| 425 |
if not version.is_devrelease and not version.is_postrelease: |
| 426 |
raise ApplicationError(f"Version {version} is not a development or post release version.") |
| 427 |
|
| 428 |
return version |
| 429 |
|
| 430 |
if version.is_devrelease: |
| 431 |
raise ApplicationError(f"Version {version} is a development release: {version.dev}") |
| 432 |
|
| 433 |
if self == VersionMode.STRIP_POST: |
| 434 |
if version.is_postrelease: |
| 435 |
version = Version(str(version).removesuffix(f".post{version.post}")) |
| 436 |
display.warning(f"Using version {version} by stripping the post release suffix from version {original_version}.") |
| 437 |
|
| 438 |
return version |
| 439 |
|
| 440 |
if self == VersionMode.REQUIRE_POST: |
| 441 |
if not version.is_postrelease: |
| 442 |
raise ApplicationError(f"Version {version} is not a post release version.") |
| 443 |
|
| 444 |
return version |
| 445 |
|
| 446 |
if version.is_postrelease: |
| 447 |
raise ApplicationError(f"Version {version} is a post release.") |
| 448 |
|
| 449 |
if self == VersionMode.DEFAULT: |
| 450 |
return version |
| 451 |
|
| 452 |
raise NotImplementedError(self) |
| 453 |
|
| 454 |
|
| 455 |
@t.overload |
| 456 |
def git(*args: t.Any, capture_output: t.Literal[True]) -> CompletedProcess: ... |
| 457 |
|
| 458 |
|
| 459 |
@t.overload |
| 460 |
def git(*args: t.Any, capture_output: t.Literal[False]) -> None: ... |
| 461 |
|
| 462 |
|
| 463 |
@t.overload |
| 464 |
def git(*args: t.Any) -> None: ... |
| 465 |
|
| 466 |
|
| 467 |
def git(*args: t.Any, capture_output: bool = False) -> CompletedProcess | None: |
| 468 |
"""Run the specified git command.""" |
| 469 |
return run("git", *args, env=None, cwd=CHECKOUT_DIR, capture_output=capture_output) |
| 470 |
|
| 471 |
|
| 472 |
def get_commit(rev: str | None = None) -> str: |
| 473 |
"""Return the commit associated with the given rev, or HEAD if no rev is given.""" |
| 474 |
try: |
| 475 |
return git("rev-parse", "--quiet", "--verify", "--end-of-options", f"{rev or 'HEAD'}^{{commit}}", capture_output=True).stdout.strip() |
| 476 |
except CalledProcessError as ex: |
| 477 |
if ex.status == 1 and not ex.stdout and not ex.stderr: |
| 478 |
raise ApplicationError(f"Could not find commit: {rev}") from None |
| 479 |
|
| 480 |
raise |
| 481 |
|
| 482 |
|
| 483 |
def prepare_pull_request(version: Version, branch: str, title: str, add: t.Iterable[pathlib.Path | str], allow_stale: bool) -> PullRequest: |
| 484 |
"""Return pull request parameters using the provided details.""" |
| 485 |
git_state = get_git_state(version, allow_stale) |
| 486 |
|
| 487 |
if not git("status", "--porcelain", "--untracked-files=no", capture_output=True).stdout.strip(): |
| 488 |
raise ApplicationError("There are no changes to commit. Did you skip a step?") |
| 489 |
|
| 490 |
upstream_branch = get_upstream_branch(version) |
| 491 |
body = create_pull_request_body(title) |
| 492 |
|
| 493 |
git("checkout", "-b", branch) |
| 494 |
git("add", *add) |
| 495 |
git("commit", "-m", title) |
| 496 |
git("push", "--set-upstream", git_state.remotes.fork.name, branch) |
| 497 |
git("checkout", git_state.branch or git_state.commit) |
| 498 |
git("branch", "-d", branch) |
| 499 |
|
| 500 |
pr = PullRequest( |
| 501 |
upstream_user=git_state.remotes.upstream.user, |
| 502 |
upstream_repo=git_state.remotes.upstream.repo, |
| 503 |
upstream_branch=upstream_branch, |
| 504 |
user=git_state.remotes.fork.user, |
| 505 |
repo=git_state.remotes.fork.repo, |
| 506 |
branch=branch, |
| 507 |
title=title, |
| 508 |
body=body, |
| 509 |
) |
| 510 |
|
| 511 |
return pr |
| 512 |
|
| 513 |
|
| 514 |
def create_github_release(release: GitHubRelease) -> None: |
| 515 |
"""Open a browser tab for creating the given GitHub release.""" |
| 516 |
# See: https://docs.github.com/en/repositories/releasing-projects-on-github/automation-for-release-forms-with-query-parameters |
| 517 |
|
| 518 |
params = dict( |
| 519 |
tag=release.tag, |
| 520 |
target=release.target, |
| 521 |
title=release.title, |
| 522 |
body=release.body, |
| 523 |
prerelease=1 if release.pre_release else 0, |
| 524 |
) |
| 525 |
|
| 526 |
query_string = urllib.parse.urlencode(params) |
| 527 |
url = f"https://github.com/{release.user}/{release.repo}/releases/new?{query_string}" |
| 528 |
|
| 529 |
display.show("Opening release creation page in new tab using default browser ...") |
| 530 |
webbrowser.open_new_tab(url) |
| 531 |
|
| 532 |
|
| 533 |
def create_pull_request(pr: PullRequest) -> None: |
| 534 |
"""Open a browser tab for creating the given pull request.""" |
| 535 |
# 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 |
| 536 |
|
| 537 |
params = dict( |
| 538 |
quick_pull=1, |
| 539 |
title=pr.title, |
| 540 |
body=pr.body, |
| 541 |
) |
| 542 |
|
| 543 |
query_string = urllib.parse.urlencode(params) |
| 544 |
url = f"https://github.com/{pr.upstream_user}/{pr.upstream_repo}/compare/{pr.upstream_branch}...{pr.user}:{pr.repo}:{pr.branch}?{query_string}" |
| 545 |
|
| 546 |
display.show("Opening pull request in new tab using default browser ...") |
| 547 |
webbrowser.open_new_tab(url) |
| 548 |
|
| 549 |
|
| 550 |
def create_pull_request_body(title: str) -> str: |
| 551 |
"""Return a simple pull request body created from the given title.""" |
| 552 |
body = f""" |
| 553 |
##### SUMMARY |
| 554 |
|
| 555 |
{title} |
| 556 |
|
| 557 |
##### ISSUE TYPE |
| 558 |
|
| 559 |
Feature Pull Request |
| 560 |
""" |
| 561 |
|
| 562 |
return body.lstrip() |
| 563 |
|
| 564 |
|
| 565 |
def get_remote(name: str, push: bool) -> Remote: |
| 566 |
"""Return details about the specified remote.""" |
| 567 |
remote_url = git("remote", "get-url", *(["--push"] if push else []), name, capture_output=True).stdout.strip() |
| 568 |
remote_match = re.search(r"[@/]github[.]com[:/](?P<user>[^/]+)/(?P<repo>[^.]+)(?:[.]git)?$", remote_url) |
| 569 |
|
| 570 |
if not remote_match: |
| 571 |
raise RuntimeError(f"Unable to identify the user and repo in the '{name}' remote: {remote_url}") |
| 572 |
|
| 573 |
remote = Remote( |
| 574 |
name=name, |
| 575 |
user=remote_match.group("user"), |
| 576 |
repo=remote_match.group("repo"), |
| 577 |
) |
| 578 |
|
| 579 |
return remote |
| 580 |
|
| 581 |
|
| 582 |
@functools.cache |
| 583 |
def get_remotes() -> Remotes: |
| 584 |
"""Return details about the remotes we need to use.""" |
| 585 |
# assume the devel branch has its upstream remote pointing to the user's fork |
| 586 |
fork_remote_name = git("branch", "--list", "devel", "--format=%(upstream:remotename)", capture_output=True).stdout.strip() |
| 587 |
|
| 588 |
if not fork_remote_name: |
| 589 |
raise ApplicationError("Could not determine the remote for your fork of Ansible.") |
| 590 |
|
| 591 |
display.show(f"Detected '{fork_remote_name}' as the remote for your fork of Ansible.") |
| 592 |
|
| 593 |
# assume there is only one ansible org remote, which would allow release testing using another repo in the same org without special configuration |
| 594 |
all_remotes = git("remote", "-v", capture_output=True).stdout.strip().splitlines() |
| 595 |
ansible_remote_names = set(line.split()[0] for line in all_remotes if re.search(r"[@/]github[.]com[:/]ansible/", line)) |
| 596 |
|
| 597 |
if not ansible_remote_names: |
| 598 |
raise ApplicationError(f"Could not determine the remote which '{fork_remote_name}' was forked from.") |
| 599 |
|
| 600 |
if len(ansible_remote_names) > 1: |
| 601 |
raise ApplicationError(f"Found multiple candidates for the remote from which '{fork_remote_name}' was forked from: {', '.join(ansible_remote_names)}") |
| 602 |
|
| 603 |
upstream_remote_name = ansible_remote_names.pop() |
| 604 |
|
| 605 |
display.show(f"Detected '{upstream_remote_name}' as the remote from which '{fork_remote_name}' was forked from.") |
| 606 |
|
| 607 |
if fork_remote_name == upstream_remote_name: |
| 608 |
raise ApplicationError("The remote for your fork of Ansible cannot be the same as the remote from which it was forked.") |
| 609 |
|
| 610 |
remotes = Remotes( |
| 611 |
fork=get_remote(fork_remote_name, push=True), |
| 612 |
upstream=get_remote(upstream_remote_name, push=False), |
| 613 |
) |
| 614 |
|
| 615 |
return remotes |
| 616 |
|
| 617 |
|
| 618 |
def get_upstream_branch(version: Version) -> str: |
| 619 |
"""Return the upstream branch name for the given version.""" |
| 620 |
return f"stable-{version.major}.{version.minor}" |
| 621 |
|
| 622 |
|
| 623 |
def get_git_state(version: Version, allow_stale: bool) -> GitState: |
| 624 |
"""Return information about the current state of the git repository.""" |
| 625 |
remotes = get_remotes() |
| 626 |
upstream_branch = get_upstream_branch(version) |
| 627 |
|
| 628 |
git("fetch", remotes.upstream.name, upstream_branch) |
| 629 |
|
| 630 |
upstream_ref = f"{remotes.upstream.name}/{upstream_branch}" |
| 631 |
upstream_commit = get_commit(upstream_ref) |
| 632 |
|
| 633 |
commit = get_commit() |
| 634 |
|
| 635 |
if commit != upstream_commit: |
| 636 |
with suppress_when(allow_stale): |
| 637 |
raise ApplicationError(f"The current commit ({commit}) does not match {upstream_ref} ({upstream_commit}).") |
| 638 |
|
| 639 |
branch = git("branch", "--show-current", capture_output=True).stdout.strip() or None |
| 640 |
|
| 641 |
state = GitState( |
| 642 |
remotes=remotes, |
| 643 |
branch=branch, |
| 644 |
commit=commit, |
| 645 |
) |
| 646 |
|
| 647 |
return state |
| 648 |
|
| 649 |
|
| 650 |
@functools.cache |
| 651 |
def ensure_venv(requirements_content: str) -> dict[str, t.Any]: |
| 652 |
"""Ensure the release venv is ready and return the env vars needed to use it.""" |
| 653 |
requirements_hash = hashlib.sha256(requirements_content.encode()).hexdigest()[:8] |
| 654 |
|
| 655 |
python_version = ".".join(map(str, sys.version_info[:2])) |
| 656 |
|
| 657 |
venv_dir = VENV_DIR / python_version / requirements_hash |
| 658 |
venv_bin_dir = venv_dir / "bin" |
| 659 |
venv_requirements_file = venv_dir / "requirements.txt" |
| 660 |
venv_marker_file = venv_dir / "marker.txt" |
| 661 |
|
| 662 |
env = os.environ.copy() |
| 663 |
env.pop("PYTHONPATH", None) # avoid interference from ansible being injected into the environment |
| 664 |
env.update( |
| 665 |
PATH=os.pathsep.join((str(venv_bin_dir), env["PATH"])), |
| 666 |
) |
| 667 |
|
| 668 |
if not venv_marker_file.exists(): |
| 669 |
display.show(f"Creating a Python {python_version} virtual environment ({requirements_hash}) ...") |
| 670 |
|
| 671 |
if venv_dir.exists(): |
| 672 |
shutil.rmtree(venv_dir) |
| 673 |
|
| 674 |
venv.create(venv_dir, with_pip=True) |
| 675 |
|
| 676 |
venv_requirements_file.write_text(requirements_content) |
| 677 |
|
| 678 |
run("pip", "install", "-r", venv_requirements_file, env=env | PIP_ENV, cwd=CHECKOUT_DIR) |
| 679 |
|
| 680 |
venv_marker_file.touch() |
| 681 |
|
| 682 |
return env |
| 683 |
|
| 684 |
|
| 685 |
def get_pypi_project(repository: str, project: str, version: Version | None = None) -> dict[str, t.Any]: |
| 686 |
"""Return the project JSON from PyPI for the specified repository, project and version (optional).""" |
| 687 |
endpoint = PYPI_ENDPOINTS[repository] |
| 688 |
|
| 689 |
if version: |
| 690 |
url = f"{endpoint}/{project}/{version}/json" |
| 691 |
else: |
| 692 |
url = f"{endpoint}/{project}/json" |
| 693 |
|
| 694 |
opener = urllib.request.build_opener() |
| 695 |
response: http.client.HTTPResponse |
| 696 |
|
| 697 |
try: |
| 698 |
with opener.open(url) as response: |
| 699 |
data = json.load(response) |
| 700 |
except urllib.error.HTTPError as ex: |
| 701 |
if version: |
| 702 |
target = f'{project!r} version {version}' |
| 703 |
else: |
| 704 |
target = f'{project!r}' |
| 705 |
|
| 706 |
if ex.status == http.HTTPStatus.NOT_FOUND: |
| 707 |
raise ApplicationError(f"Could not find {target} on PyPI.") from None |
| 708 |
|
| 709 |
raise RuntimeError(f"Failed to get {target} from PyPI.") from ex |
| 710 |
|
| 711 |
return data |
| 712 |
|
| 713 |
|
| 714 |
def get_ansible_version(version: str | None = None, /, commit: str | None = None, mode: VersionMode = VersionMode.DEFAULT) -> Version: |
| 715 |
"""Parse and return the current ansible-core version, the provided version or the version from the provided commit.""" |
| 716 |
if version and commit: |
| 717 |
raise ValueError("Specify only one of: version, commit") |
| 718 |
|
| 719 |
if version: |
| 720 |
source = "" |
| 721 |
else: |
| 722 |
if commit: |
| 723 |
current = git("show", f"{commit}:{ANSIBLE_RELEASE_FILE.relative_to(CHECKOUT_DIR)}", capture_output=True).stdout |
| 724 |
else: |
| 725 |
current = ANSIBLE_RELEASE_FILE.read_text() |
| 726 |
|
| 727 |
if not (match := ANSIBLE_VERSION_PATTERN.search(current)): |
| 728 |
raise RuntimeError("Failed to get the ansible-core version.") |
| 729 |
|
| 730 |
version = match.group("version") |
| 731 |
source = f" in '{ANSIBLE_RELEASE_FILE}'" |
| 732 |
|
| 733 |
try: |
| 734 |
parsed_version = Version(version) |
| 735 |
except InvalidVersion: |
| 736 |
raise ApplicationError(f"Invalid version{source}: {version}") from None |
| 737 |
|
| 738 |
parsed_version = mode.apply(parsed_version) |
| 739 |
|
| 740 |
return parsed_version |
| 741 |
|
| 742 |
|
| 743 |
def get_next_version(version: Version, /, final: bool = False, pre: str | None = None, mode: VersionMode = VersionMode.DEFAULT) -> Version: |
| 744 |
"""Return the next version after the specified version.""" |
| 745 |
|
| 746 |
# TODO: consider using development versions instead of post versions after a release is published |
| 747 |
|
| 748 |
pre = pre or "" |
| 749 |
micro = version.micro |
| 750 |
|
| 751 |
if version.is_devrelease: |
| 752 |
# The next version of a development release is the same version without the development component. |
| 753 |
if final: |
| 754 |
pre = "" |
| 755 |
elif not pre and version.pre is not None: |
| 756 |
pre = f"{version.pre[0]}{version.pre[1]}" |
| 757 |
elif not pre: |
| 758 |
pre = "b1" # when there is no existing pre and none specified, advance to b1 |
| 759 |
|
| 760 |
elif version.is_postrelease: |
| 761 |
# The next version of a post release is the next pre-release *or* micro release component. |
| 762 |
if final: |
| 763 |
pre = "" |
| 764 |
elif not pre and version.pre is not None: |
| 765 |
pre = f"{version.pre[0]}{version.pre[1] + 1}" |
| 766 |
elif not pre: |
| 767 |
pre = "rc1" # when there is no existing pre and none specified, advance to rc1 |
| 768 |
|
| 769 |
if version.pre is None: |
| 770 |
micro = version.micro + 1 |
| 771 |
else: |
| 772 |
raise ApplicationError(f"Version {version} is not a development or post release version.") |
| 773 |
|
| 774 |
version = f"{version.major}.{version.minor}.{micro}{pre}" |
| 775 |
|
| 776 |
return get_ansible_version(version, mode=mode) |
| 777 |
|
| 778 |
|
| 779 |
def check_ansible_version(current_version: Version, requested_version: Version) -> None: |
| 780 |
"""Verify the requested version is valid for the current version.""" |
| 781 |
if requested_version.release[:2] != current_version.release[:2]: |
| 782 |
raise ApplicationError(f"Version {requested_version} does not match the major and minor portion of the current version: {current_version}") |
| 783 |
|
| 784 |
if requested_version < current_version: |
| 785 |
raise ApplicationError(f"Version {requested_version} is older than the current version: {current_version}") |
| 786 |
|
| 787 |
# TODO: consider additional checks to avoid mistakes when incrementing the release version |
| 788 |
|
| 789 |
|
| 790 |
def set_ansible_version(current_version: Version, requested_version: Version) -> None: |
| 791 |
"""Set the current ansible-core version.""" |
| 792 |
check_ansible_version(current_version, requested_version) |
| 793 |
|
| 794 |
if requested_version == current_version: |
| 795 |
return |
| 796 |
|
| 797 |
display.show(f"Updating version {current_version} to {requested_version} ...") |
| 798 |
|
| 799 |
current = ANSIBLE_RELEASE_FILE.read_text() |
| 800 |
updated = ANSIBLE_VERSION_PATTERN.sub(ANSIBLE_VERSION_FORMAT.format(version=requested_version), current) |
| 801 |
|
| 802 |
if current == updated: |
| 803 |
raise RuntimeError("Failed to set the ansible-core version.") |
| 804 |
|
| 805 |
ANSIBLE_RELEASE_FILE.write_text(updated) |
| 806 |
|
| 807 |
|
| 808 |
def get_latest_setuptools_version() -> Version: |
| 809 |
"""Return the latest setuptools version found on PyPI.""" |
| 810 |
data = get_pypi_project('pypi', 'setuptools') |
| 811 |
version = Version(data['info']['version']) |
| 812 |
|
| 813 |
return version |
| 814 |
|
| 815 |
|
| 816 |
def set_setuptools_upper_bound(requested_version: Version) -> None: |
| 817 |
"""Set the upper bound on setuptools in pyproject.toml.""" |
| 818 |
current = ANSIBLE_PYPROJECT_TOML_FILE.read_text() |
| 819 |
pattern = re.compile(r'^(?P<begin>requires = \["setuptools >= )(?P<lower>[^,]+)(?P<middle>, <= )(?P<upper>[^"]+)(?P<end>".*)$', re.MULTILINE) |
| 820 |
match = pattern.search(current) |
| 821 |
|
| 822 |
if not match: |
| 823 |
raise ApplicationError(f"Unable to find the 'requires' entry in: {ANSIBLE_PYPROJECT_TOML_FILE.relative_to(CHECKOUT_DIR)}") |
| 824 |
|
| 825 |
current_version = Version(match.group('upper')) |
| 826 |
|
| 827 |
if requested_version == current_version: |
| 828 |
return |
| 829 |
|
| 830 |
display.show(f"Updating setuptools upper bound from {current_version} to {requested_version} ...") |
| 831 |
|
| 832 |
updated = pattern.sub(fr'\g<begin>\g<lower>\g<middle>{requested_version}\g<end>', current) |
| 833 |
|
| 834 |
if current == updated: |
| 835 |
raise RuntimeError("Failed to set the setuptools upper bound.") |
| 836 |
|
| 837 |
ANSIBLE_PYPROJECT_TOML_FILE.write_text(updated) |
| 838 |
|
| 839 |
|
| 840 |
def create_reproducible_sdist(original_path: pathlib.Path, output_path: pathlib.Path, mtime: int) -> None: |
| 841 |
"""Read the specified sdist and write out a new copy with uniform file metadata at the specified location.""" |
| 842 |
with tarfile.open(original_path) as original_archive: |
| 843 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 844 |
tar_file = pathlib.Path(temp_dir) / "sdist.tar" |
| 845 |
|
| 846 |
with tarfile.open(tar_file, mode="w") as tar_archive: |
| 847 |
for original_info in original_archive.getmembers(): # type: tarfile.TarInfo |
| 848 |
tar_archive.addfile(create_reproducible_tar_info(original_info, mtime), original_archive.extractfile(original_info)) |
| 849 |
|
| 850 |
with tar_file.open("rb") as tar_archive: |
| 851 |
with gzip.GzipFile(output_path, "wb", mtime=mtime) as output_archive: |
| 852 |
shutil.copyfileobj(tar_archive, output_archive) |
| 853 |
|
| 854 |
|
| 855 |
def create_reproducible_tar_info(original: tarfile.TarInfo, mtime: int) -> tarfile.TarInfo: |
| 856 |
"""Return a copy of the given TarInfo with uniform file metadata.""" |
| 857 |
sanitized = tarfile.TarInfo() |
| 858 |
sanitized.name = original.name |
| 859 |
sanitized.size = original.size |
| 860 |
sanitized.mtime = mtime |
| 861 |
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 |
| 862 |
sanitized.type = original.type |
| 863 |
sanitized.linkname = original.linkname |
| 864 |
sanitized.uid = 0 |
| 865 |
sanitized.gid = 0 |
| 866 |
sanitized.uname = "root" |
| 867 |
sanitized.gname = "root" |
| 868 |
|
| 869 |
if original.mode & (stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH): |
| 870 |
sanitized.mode |= stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH |
| 871 |
|
| 872 |
return sanitized |
| 873 |
|
| 874 |
|
| 875 |
def test_built_artifact(path: pathlib.Path) -> None: |
| 876 |
"""Test the specified built artifact by installing it in a venv and running some basic commands.""" |
| 877 |
with tempfile.TemporaryDirectory() as temp_dir_name: |
| 878 |
temp_dir = pathlib.Path(temp_dir_name) |
| 879 |
|
| 880 |
venv_dir = temp_dir / "venv" |
| 881 |
venv_bin_dir = venv_dir / "bin" |
| 882 |
|
| 883 |
venv.create(venv_dir, with_pip=True) |
| 884 |
|
| 885 |
env = os.environ.copy() |
| 886 |
env.pop("PYTHONPATH", None) # avoid interference from ansible being injected into the environment |
| 887 |
env.update( |
| 888 |
PATH=os.pathsep.join((str(venv_bin_dir), env["PATH"])), |
| 889 |
) |
| 890 |
|
| 891 |
run("pip", "install", path, env=env | PIP_ENV, cwd=CHECKOUT_DIR) |
| 892 |
|
| 893 |
run("ansible", "--version", env=env, cwd=CHECKOUT_DIR) |
| 894 |
run("ansible-test", "--version", env=env, cwd=CHECKOUT_DIR) |
| 895 |
|
| 896 |
|
| 897 |
def get_sdist_path(version: Version, dist_dir: pathlib.Path = DIST_DIR) -> pathlib.Path: |
| 898 |
"""Return the path to the sdist file.""" |
| 899 |
return dist_dir / f"ansible_core-{version}.tar.gz" |
| 900 |
|
| 901 |
|
| 902 |
def get_wheel_path(version: Version, dist_dir: pathlib.Path = DIST_DIR) -> pathlib.Path: |
| 903 |
"""Return the path to the wheel file.""" |
| 904 |
return dist_dir / f"ansible_core-{version}-py3-none-any.whl" |
| 905 |
|
| 906 |
|
| 907 |
def calculate_digest(path: pathlib.Path) -> str: |
| 908 |
"""Return the digest for the specified file.""" |
| 909 |
with open(path, "rb") as f: |
| 910 |
digest = hashlib.file_digest(f, DIGEST_ALGORITHM) |
| 911 |
return digest.hexdigest() |
| 912 |
|
| 913 |
|
| 914 |
@functools.cache |
| 915 |
def get_release_artifact_details(repository: str, version: Version, validate: bool) -> list[ReleaseArtifact]: |
| 916 |
"""Return information about the release artifacts hosted on PyPI.""" |
| 917 |
data = get_pypi_project(repository, 'ansible-core', version) |
| 918 |
artifacts = [describe_release_artifact(version, item, validate) for item in data["urls"]] |
| 919 |
|
| 920 |
expected_artifact_types = {"bdist_wheel", "sdist"} |
| 921 |
found_artifact_types = set(artifact.package_type for artifact in artifacts) |
| 922 |
|
| 923 |
if found_artifact_types != expected_artifact_types: |
| 924 |
raise RuntimeError(f"Expected {expected_artifact_types} artifact types, but found {found_artifact_types} instead.") |
| 925 |
|
| 926 |
return artifacts |
| 927 |
|
| 928 |
|
| 929 |
def describe_release_artifact(version: Version, item: dict[str, t.Any], validate: bool) -> ReleaseArtifact: |
| 930 |
"""Return release artifact details extracted from the given PyPI data.""" |
| 931 |
package_type = item["packagetype"] |
| 932 |
|
| 933 |
# The artifact URL is documented as stable, so is safe to put in release notes. |
| 934 |
# See: https://github.com/pypi/warehouse/blame/c95be4a1055f4b36a8852715eb80318c81fc00ca/docs/api-reference/integration-guide.rst#L86-L90 |
| 935 |
url = item["url"] |
| 936 |
|
| 937 |
pypi_size = item["size"] |
| 938 |
pypi_digest = item["digests"][DIGEST_ALGORITHM] |
| 939 |
|
| 940 |
if package_type == "bdist_wheel": |
| 941 |
local_artifact_file = get_wheel_path(version) |
| 942 |
package_label = "Built Distribution" |
| 943 |
elif package_type == "sdist": |
| 944 |
local_artifact_file = get_sdist_path(version) |
| 945 |
package_label = "Source Distribution" |
| 946 |
else: |
| 947 |
raise NotImplementedError(f"Package type '{package_type}' is not supported.") |
| 948 |
|
| 949 |
if validate: |
| 950 |
try: |
| 951 |
local_size = local_artifact_file.stat().st_size |
| 952 |
local_digest = calculate_digest(local_artifact_file) |
| 953 |
except FileNotFoundError: |
| 954 |
raise ApplicationError(f"Missing local artifact: {local_artifact_file.relative_to(CHECKOUT_DIR)}") from None |
| 955 |
|
| 956 |
if local_size != pypi_size: |
| 957 |
raise ApplicationError(f"The {version} local {package_type} size {local_size} does not match the PyPI size {pypi_size}.") |
| 958 |
|
| 959 |
if local_digest != pypi_digest: |
| 960 |
raise ApplicationError(f"The {version} local {package_type} digest '{local_digest}' does not match the PyPI digest '{pypi_digest}'.") |
| 961 |
|
| 962 |
return ReleaseArtifact( |
| 963 |
package_type=package_type, |
| 964 |
package_label=package_label, |
| 965 |
url=url, |
| 966 |
size=pypi_size, |
| 967 |
digest=pypi_digest, |
| 968 |
digest_algorithm=DIGEST_ALGORITHM.upper(), |
| 969 |
) |
| 970 |
|
| 971 |
|
| 972 |
def get_next_release_date(start: datetime.date, step: int, after: datetime.date) -> datetime.date: |
| 973 |
"""Return the next release date.""" |
| 974 |
if start > after: |
| 975 |
raise ValueError(f"{start=} is greater than {after=}") |
| 976 |
|
| 977 |
current_delta = after - start |
| 978 |
release_delta = datetime.timedelta(days=(math.floor(current_delta.days / step) + 1) * step) |
| 979 |
|
| 980 |
release = start + release_delta |
| 981 |
|
| 982 |
return release |
| 983 |
|
| 984 |
|
| 985 |
def create_template_environment() -> jinja2.Environment: |
| 986 |
"""Create and return a jinja2 environment.""" |
| 987 |
env = jinja2.Environment() |
| 988 |
env.filters.update( |
| 989 |
basename=os.path.basename, |
| 990 |
) |
| 991 |
|
| 992 |
return env |
| 993 |
|
| 994 |
|
| 995 |
def create_github_release_notes(upstream: Remote, repository: str, version: Version, validate: bool) -> str: |
| 996 |
"""Create and return GitHub release notes.""" |
| 997 |
env = create_template_environment() |
| 998 |
template = env.from_string(GITHUB_RELEASE_NOTES_TEMPLATE) |
| 999 |
|
| 1000 |
variables = dict( |
| 1001 |
version=version, |
| 1002 |
releases=get_release_artifact_details(repository, version, validate), |
| 1003 |
changelog=f"https://github.com/{upstream.user}/{upstream.repo}/blob/v{version}/changelogs/CHANGELOG-v{version.major}.{version.minor}.rst", |
| 1004 |
) |
| 1005 |
|
| 1006 |
release_notes = template.render(**variables).strip() |
| 1007 |
|
| 1008 |
return release_notes |
| 1009 |
|
| 1010 |
|
| 1011 |
# endregion |
| 1012 |
# region Templates |
| 1013 |
|
| 1014 |
|
| 1015 |
GITHUB_RELEASE_NOTES_TEMPLATE = """ |
| 1016 |
# Changelog |
| 1017 |
|
| 1018 |
See the [full changelog]({{ changelog }}) for the changes included in this release. |
| 1019 |
|
| 1020 |
# Release Artifacts |
| 1021 |
|
| 1022 |
{%- for release in releases %} |
| 1023 |
* {{ release.package_label }}: [{{ release.url|basename }}]({{ release.url }}) - ‌{{ release.size }} bytes |
| 1024 |
* {{ release.digest }} ({{ release.digest_algorithm }}) |
| 1025 |
{%- endfor %} |
| 1026 |
""" |
| 1027 |
|
| 1028 |
|
| 1029 |
# endregion |
| 1030 |
# region Commands |
| 1031 |
|
| 1032 |
|
| 1033 |
command = CommandFramework( |
| 1034 |
repository=dict(metavar="REPO", choices=tuple(PYPI_ENDPOINTS), default="pypi", help="PyPI repository to use: %(choices)s [%(default)s]"), |
| 1035 |
version=dict(exclusive="version", help="version to set"), |
| 1036 |
pre=dict(exclusive="version", help="increment version to the specified pre-release (aN, bN, rcN)"), |
| 1037 |
final=dict(exclusive="version", action="store_true", help="increment version to the next final release"), |
| 1038 |
commit=dict(help="commit to tag"), |
| 1039 |
validate=dict(name="--no-validate", action="store_false", help="disable validation of PyPI artifacts against local ones"), |
| 1040 |
prompt=dict(name="--no-prompt", action="store_false", help="disable interactive prompt before publishing with twine"), |
| 1041 |
setuptools=dict(name='--no-setuptools', action="store_false", help="disable updating setuptools upper bound"), |
| 1042 |
allow_tag=dict(action="store_true", help="allow an existing release tag (for testing)"), |
| 1043 |
allow_stale=dict(action="store_true", help="allow a stale checkout (for testing)"), |
| 1044 |
allow_dirty=dict(action="store_true", help="allow untracked files and files with changes (for testing)"), |
| 1045 |
) |
| 1046 |
|
| 1047 |
|
| 1048 |
@command |
| 1049 |
def instructions() -> None: |
| 1050 |
"""Show instructions for the release process.""" |
| 1051 |
message = """ |
| 1052 |
Releases must be performed using an up-to-date checkout of a fork of the Ansible repository. |
| 1053 |
|
| 1054 |
1. Make sure your checkout is up-to-date. |
| 1055 |
2. Run the `prepare` command [1], then: |
| 1056 |
a. Submit the PR opened in the browser. |
| 1057 |
b. Wait for CI to pass. |
| 1058 |
c. Merge the PR. |
| 1059 |
3. Update your checkout to include the commit from the PR which was just merged. |
| 1060 |
4. Run the `complete` command [2], then: |
| 1061 |
a. Submit the GitHub release opened in the browser. |
| 1062 |
b. Submit the PR opened in the browser. |
| 1063 |
c. Wait for CI to pass. |
| 1064 |
d. Merge the PR. |
| 1065 |
|
| 1066 |
[1] Use the `--final`, `--pre` or `--version` option for control over the version. |
| 1067 |
[2] During the `publish` step, `twine` may prompt for credentials. |
| 1068 |
""" |
| 1069 |
|
| 1070 |
display.show(message.strip()) |
| 1071 |
|
| 1072 |
|
| 1073 |
@command |
| 1074 |
def show_version(final: bool = False, pre: str | None = None) -> None: |
| 1075 |
"""Show the current and next ansible-core version.""" |
| 1076 |
current_version = get_ansible_version(mode=VersionMode.ALLOW_DEV_POST) |
| 1077 |
display.show(f"Current version: {current_version}") |
| 1078 |
|
| 1079 |
try: |
| 1080 |
next_version = get_next_version(current_version, final=final, pre=pre) |
| 1081 |
except ApplicationError as ex: |
| 1082 |
display.show(f" Next version: Unknown - {ex}") |
| 1083 |
else: |
| 1084 |
display.show(f" Next version: {next_version}") |
| 1085 |
|
| 1086 |
check_ansible_version(current_version, next_version) |
| 1087 |
|
| 1088 |
|
| 1089 |
@command |
| 1090 |
def check_state(allow_stale: bool = False) -> None: |
| 1091 |
"""Verify the git repository is in a usable state for creating a pull request.""" |
| 1092 |
get_git_state(get_ansible_version(), allow_stale) |
| 1093 |
|
| 1094 |
|
| 1095 |
# noinspection PyUnusedLocal |
| 1096 |
@command |
| 1097 |
def prepare(final: bool = False, pre: str | None = None, version: str | None = None, setuptools: bool | None = None) -> None: |
| 1098 |
"""Prepare a release.""" |
| 1099 |
command.run( |
| 1100 |
update_version, |
| 1101 |
update_setuptools, |
| 1102 |
check_state, |
| 1103 |
generate_summary, |
| 1104 |
generate_changelog, |
| 1105 |
create_release_pr, |
| 1106 |
) |
| 1107 |
|
| 1108 |
|
| 1109 |
@command |
| 1110 |
def update_version(final: bool = False, pre: str | None = None, version: str | None = None) -> None: |
| 1111 |
"""Update the version embedded in the source code.""" |
| 1112 |
current_version = get_ansible_version(mode=VersionMode.REQUIRE_DEV_POST) |
| 1113 |
|
| 1114 |
if version: |
| 1115 |
requested_version = get_ansible_version(version) |
| 1116 |
else: |
| 1117 |
requested_version = get_next_version(current_version, final=final, pre=pre) |
| 1118 |
|
| 1119 |
set_ansible_version(current_version, requested_version) |
| 1120 |
|
| 1121 |
|
| 1122 |
@command |
| 1123 |
def update_setuptools(setuptools: bool) -> None: |
| 1124 |
"""Update the setuptools upper bound in pyproject.toml.""" |
| 1125 |
if not setuptools: |
| 1126 |
return |
| 1127 |
|
| 1128 |
requested_version = get_latest_setuptools_version() |
| 1129 |
set_setuptools_upper_bound(requested_version) |
| 1130 |
|
| 1131 |
|
| 1132 |
@command |
| 1133 |
def generate_summary() -> None: |
| 1134 |
"""Generate a summary changelog fragment for this release.""" |
| 1135 |
version = get_ansible_version() |
| 1136 |
release_date = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d") |
| 1137 |
summary_path = CHANGELOGS_FRAGMENTS_DIR / f"{version}_summary.yaml" |
| 1138 |
major_minor = f"{version.major}.{version.minor}" |
| 1139 |
|
| 1140 |
content = f""" |
| 1141 |
release_summary: | |
| 1142 |
| Release Date: {release_date} |
| 1143 |
| `Porting Guide <https://docs.ansible.com/ansible-core/{major_minor}/porting_guides/porting_guide_core_{major_minor}.html>`__ |
| 1144 |
""" |
| 1145 |
|
| 1146 |
summary_path.write_text(content.lstrip()) |
| 1147 |
|
| 1148 |
|
| 1149 |
@command |
| 1150 |
def generate_changelog() -> None: |
| 1151 |
"""Generate the changelog and validate the results.""" |
| 1152 |
changelog_requirements = ( |
| 1153 |
ANSIBLE_CHANGELOG_REQUIREMENTS_FILE.read_text() |
| 1154 |
+ ANSIBLE_REQUIREMENTS_FILE.read_text() # TODO: consider pinning the ansible requirements and dependencies |
| 1155 |
) |
| 1156 |
|
| 1157 |
env = ensure_venv(changelog_requirements) |
| 1158 |
env.update( |
| 1159 |
PATH=os.pathsep.join((str(ANSIBLE_BIN_DIR), env["PATH"])), |
| 1160 |
PYTHONPATH=ANSIBLE_LIB_DIR, |
| 1161 |
) |
| 1162 |
|
| 1163 |
# TODO: consider switching back to the original changelog generator instead of using antsibull-changelog |
| 1164 |
|
| 1165 |
run("antsibull-changelog", "release", "-vv", "--use-ansible-doc", env=env, cwd=CHECKOUT_DIR) |
| 1166 |
run("antsibull-changelog", "generate", "-vv", "--use-ansible-doc", env=env, cwd=CHECKOUT_DIR) |
| 1167 |
|
| 1168 |
run("ansible-test", "sanity", CHANGELOGS_DIR, ANSIBLE_RELEASE_FILE, env=env, cwd=CHECKOUT_DIR) |
| 1169 |
|
| 1170 |
|
| 1171 |
@command |
| 1172 |
def create_release_pr(allow_stale: bool = False) -> None: |
| 1173 |
"""Create a branch and open a browser tab for creating a release pull request.""" |
| 1174 |
version = get_ansible_version() |
| 1175 |
|
| 1176 |
pr = prepare_pull_request( |
| 1177 |
version=version, |
| 1178 |
branch=f"release-{version}-{secrets.token_hex(4)}", |
| 1179 |
title=f"New release v{version}", |
| 1180 |
add=( |
| 1181 |
CHANGELOGS_DIR, |
| 1182 |
ANSIBLE_RELEASE_FILE, |
| 1183 |
ANSIBLE_PYPROJECT_TOML_FILE, |
| 1184 |
), |
| 1185 |
allow_stale=allow_stale, |
| 1186 |
) |
| 1187 |
|
| 1188 |
create_pull_request(pr) |
| 1189 |
|
| 1190 |
|
| 1191 |
# noinspection PyUnusedLocal |
| 1192 |
@command |
| 1193 |
def complete(repository: str, allow_dirty: bool = False) -> None: |
| 1194 |
"""Complete a release after the prepared changes have been merged.""" |
| 1195 |
command.run( |
| 1196 |
check_state, |
| 1197 |
build, |
| 1198 |
test, |
| 1199 |
publish, |
| 1200 |
tag_release, |
| 1201 |
post_version, |
| 1202 |
create_post_pr, |
| 1203 |
) |
| 1204 |
|
| 1205 |
|
| 1206 |
@command |
| 1207 |
def build(allow_dirty: bool = False) -> None: |
| 1208 |
"""Build the sdist and wheel.""" |
| 1209 |
version = get_ansible_version(mode=VersionMode.ALLOW_DEV_POST) |
| 1210 |
|
| 1211 |
# TODO: consider pinning the build requirement and its dependencies |
| 1212 |
build_requirements = """ |
| 1213 |
build |
| 1214 |
""" |
| 1215 |
env = ensure_venv(build_requirements) |
| 1216 |
|
| 1217 |
dirty = git("status", "--porcelain", "--untracked-files=all", capture_output=True).stdout.strip().splitlines() |
| 1218 |
|
| 1219 |
if dirty: |
| 1220 |
with suppress_when(allow_dirty): |
| 1221 |
raise ApplicationError(f"There are {len(dirty)} files which are untracked and/or have changes, which will be omitted from the build.") |
| 1222 |
|
| 1223 |
sdist_file = get_sdist_path(version) |
| 1224 |
wheel_file = get_wheel_path(version) |
| 1225 |
|
| 1226 |
with tempfile.TemporaryDirectory(dir=DIST_DIR, prefix=f"build-{version}-", suffix=".tmp") as temp_dir_name: |
| 1227 |
temp_dir = pathlib.Path(temp_dir_name) |
| 1228 |
dist_dir = temp_dir / "dist" |
| 1229 |
|
| 1230 |
commit_time = int(git("show", "-s", "--format=%ct", capture_output=True).stdout) |
| 1231 |
|
| 1232 |
env.update( |
| 1233 |
SOURCE_DATE_EPOCH=commit_time, |
| 1234 |
) |
| 1235 |
|
| 1236 |
git("worktree", "add", "-d", temp_dir) |
| 1237 |
|
| 1238 |
try: |
| 1239 |
run("python", "-m", "build", env=env, cwd=temp_dir) |
| 1240 |
|
| 1241 |
create_reproducible_sdist(get_sdist_path(version, dist_dir), sdist_file, commit_time) |
| 1242 |
get_wheel_path(version, dist_dir).rename(wheel_file) |
| 1243 |
finally: |
| 1244 |
git("worktree", "remove", temp_dir) |
| 1245 |
|
| 1246 |
|
| 1247 |
@command |
| 1248 |
def test() -> None: |
| 1249 |
"""Test the sdist and wheel.""" |
| 1250 |
command.run( |
| 1251 |
test_sdist, |
| 1252 |
test_wheel, |
| 1253 |
) |
| 1254 |
|
| 1255 |
|
| 1256 |
@command |
| 1257 |
def test_sdist() -> None: |
| 1258 |
"""Test the sdist.""" |
| 1259 |
version = get_ansible_version(mode=VersionMode.ALLOW_DEV_POST) |
| 1260 |
sdist_file = get_sdist_path(version) |
| 1261 |
|
| 1262 |
with tempfile.TemporaryDirectory() as temp_dir_name: |
| 1263 |
temp_dir = pathlib.Path(temp_dir_name) |
| 1264 |
|
| 1265 |
with contextlib.ExitStack() as stack: |
| 1266 |
try: |
| 1267 |
sdist = stack.enter_context(tarfile.open(sdist_file)) |
| 1268 |
except FileNotFoundError: |
| 1269 |
raise ApplicationError(f"Missing sdist: {sdist_file.relative_to(CHECKOUT_DIR)}") from None |
| 1270 |
|
| 1271 |
sdist.extractall(temp_dir, filter='data') |
| 1272 |
|
| 1273 |
pyc_glob = "*.pyc*" |
| 1274 |
pyc_files = sorted(path.relative_to(temp_dir) for path in temp_dir.rglob(pyc_glob)) |
| 1275 |
|
| 1276 |
if pyc_files: |
| 1277 |
raise ApplicationError(f"Found {len(pyc_files)} '{pyc_glob}' file(s): {', '.join(map(str, pyc_files))}") |
| 1278 |
|
| 1279 |
test_built_artifact(sdist_file) |
| 1280 |
|
| 1281 |
|
| 1282 |
@command |
| 1283 |
def test_wheel() -> None: |
| 1284 |
"""Test the wheel.""" |
| 1285 |
version = get_ansible_version(mode=VersionMode.ALLOW_DEV_POST) |
| 1286 |
wheel_file = get_wheel_path(version) |
| 1287 |
|
| 1288 |
with tempfile.TemporaryDirectory() as temp_dir_name: |
| 1289 |
temp_dir = pathlib.Path(temp_dir_name) |
| 1290 |
|
| 1291 |
with contextlib.ExitStack() as stack: |
| 1292 |
try: |
| 1293 |
wheel = stack.enter_context(zipfile.ZipFile(wheel_file)) |
| 1294 |
except FileNotFoundError: |
| 1295 |
raise ApplicationError(f"Missing wheel for version {version}: {wheel_file}") from None |
| 1296 |
|
| 1297 |
wheel.extractall(temp_dir) |
| 1298 |
|
| 1299 |
test_built_artifact(wheel_file) |
| 1300 |
|
| 1301 |
|
| 1302 |
@command |
| 1303 |
def publish(repository: str, prompt: bool = True) -> None: |
| 1304 |
"""Publish to PyPI.""" |
| 1305 |
version = get_ansible_version() |
| 1306 |
sdist_file = get_sdist_path(version) |
| 1307 |
wheel_file = get_wheel_path(version) |
| 1308 |
|
| 1309 |
# TODO: consider pinning the twine requirement and its dependencies |
| 1310 |
publish_requirements = """ |
| 1311 |
twine |
| 1312 |
""" |
| 1313 |
env = ensure_venv(publish_requirements) |
| 1314 |
|
| 1315 |
if prompt: |
| 1316 |
try: |
| 1317 |
while input(f"Do you want to publish {version} to the '{repository}' repository?\nEnter the repository name to confirm: ") != repository: |
| 1318 |
pass |
| 1319 |
except KeyboardInterrupt: |
| 1320 |
display.show("") |
| 1321 |
raise ApplicationError("Publishing was aborted by the user.") from None |
| 1322 |
|
| 1323 |
run("twine", "upload", "-r", repository, sdist_file, wheel_file, env=env, cwd=CHECKOUT_DIR) |
| 1324 |
|
| 1325 |
|
| 1326 |
@command |
| 1327 |
def tag_release(repository: str, commit: str | None = None, validate: bool = True, allow_tag: bool = False) -> None: |
| 1328 |
"""Create a GitHub release using the current or specified commit.""" |
| 1329 |
upstream = get_remotes().upstream |
| 1330 |
|
| 1331 |
if commit: |
| 1332 |
git("fetch", upstream.name) # fetch upstream to make sure the commit can be found |
| 1333 |
|
| 1334 |
commit = get_commit(commit) |
| 1335 |
version = get_ansible_version(commit=commit) |
| 1336 |
tag = f"v{version}" |
| 1337 |
|
| 1338 |
if upstream_tag := git("ls-remote", "--tags", upstream.name, tag, capture_output=True).stdout.strip(): |
| 1339 |
with suppress_when(allow_tag): |
| 1340 |
raise ApplicationError(f"Version {version} has already been tagged: {upstream_tag}") |
| 1341 |
|
| 1342 |
upstream_branch = get_upstream_branch(version) |
| 1343 |
upstream_refs = git("branch", "-r", "--format=%(refname)", "--contains", commit, capture_output=True).stdout.strip().splitlines() |
| 1344 |
upstream_ref = f"refs/remotes/{upstream.name}/{upstream_branch}" |
| 1345 |
|
| 1346 |
if upstream_ref not in upstream_refs: |
| 1347 |
raise ApplicationError(f"Commit {upstream_ref} not found. Found {len(upstream_refs)} upstream ref(s): {', '.join(upstream_refs)}") |
| 1348 |
|
| 1349 |
body = create_github_release_notes(upstream, repository, version, validate) |
| 1350 |
|
| 1351 |
release = GitHubRelease( |
| 1352 |
user=upstream.user, |
| 1353 |
repo=upstream.repo, |
| 1354 |
target=commit, |
| 1355 |
tag=tag, |
| 1356 |
title=tag, |
| 1357 |
body=body, |
| 1358 |
pre_release=version.pre is not None, |
| 1359 |
) |
| 1360 |
|
| 1361 |
create_github_release(release) |
| 1362 |
|
| 1363 |
|
| 1364 |
@command |
| 1365 |
def post_version() -> None: |
| 1366 |
"""Set the post release version.""" |
| 1367 |
current_version = get_ansible_version() |
| 1368 |
requested_version = get_ansible_version(f"{current_version}.post0", mode=VersionMode.REQUIRE_POST) |
| 1369 |
|
| 1370 |
set_ansible_version(current_version, requested_version) |
| 1371 |
|
| 1372 |
|
| 1373 |
@command |
| 1374 |
def create_post_pr(allow_stale: bool = False) -> None: |
| 1375 |
"""Create a branch and open a browser tab for creating a post release pull request.""" |
| 1376 |
version = get_ansible_version(mode=VersionMode.REQUIRE_POST) |
| 1377 |
|
| 1378 |
pr = prepare_pull_request( |
| 1379 |
version=version, |
| 1380 |
branch=f"release-{version}-{secrets.token_hex(4)}", |
| 1381 |
title=f"Update Ansible release version to v{version}.", |
| 1382 |
add=(ANSIBLE_RELEASE_FILE,), |
| 1383 |
allow_stale=allow_stale, |
| 1384 |
) |
| 1385 |
|
| 1386 |
create_pull_request(pr) |
| 1387 |
|
| 1388 |
|
| 1389 |
# endregion |
| 1390 |
|
| 1391 |
|
| 1392 |
if __name__ == "__main__": |
| 1393 |
command.main() |