diff --git a/.github/scripts/release_tools.py b/.github/scripts/release_tools.py new file mode 100644 index 00000000..0be9b364 --- /dev/null +++ b/.github/scripts/release_tools.py @@ -0,0 +1,439 @@ +import argparse +import hashlib +import json +import os +import re +import subprocess +import sys +import tarfile +import tempfile +import tomllib +import zipfile +from dataclasses import dataclass +from email.parser import BytesParser +from pathlib import Path +from typing import TypeGuard +from urllib.parse import urlencode + + +PROJECTS = { + "azure-kusto-python": "pyproject.toml", + "azure-kusto-data": "azure-kusto-data/pyproject.toml", + "azure-kusto-ingest": "azure-kusto-ingest/pyproject.toml", + "quick-start": "quick-start/pyproject.toml", +} +PACKAGES = ("azure-kusto-data", "azure-kusto-ingest") + + +class ReleaseError(RuntimeError): + pass + + +def is_object(value: object) -> TypeGuard[dict[str, object]]: + return isinstance(value, dict) and all(isinstance(key, str) for key in value) + + +def object_value(value: object) -> dict[str, object]: + if not is_object(value): + raise ReleaseError("Expected a JSON/TOML object.") + return value + + +def string_value(value: object) -> str: + if not isinstance(value, str) or not value: + raise ReleaseError(f"Expected a nonempty string, got {value!r}.") + return value + + +def objects(value: object) -> list[dict[str, object]]: + if not isinstance(value, list): + raise ReleaseError("Expected an array of objects.") + return [object_value(item) for item in value] + + +def command(args: list[str], cwd: Path | None = None, input_text: str | None = None) -> str: + return subprocess.run(args, cwd=cwd, input=input_text, text=True, encoding="utf-8", capture_output=True, check=True).stdout + + +def commit_sha(value: object) -> str: + sha = string_value(value) + if not re.fullmatch(r"[0-9a-f]{40}", sha) or sha == "0" * 40: + raise ReleaseError(f"Expected a nonzero commit SHA, got {sha!r}.") + return sha + + +def version_numbers(version: str) -> tuple[int, int, int]: + match = re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version) + if match is None: + raise ReleaseError(f"Only stable major.minor.patch releases are supported: {version!r}.") + return int(match[1]), int(match[2]), int(match[3]) + + +@dataclass(frozen=True) +class Release: + version: str + sha: str + notes: str + + @property + def tag(self) -> str: + return f"v{self.version}" + + +class Repository: + def __init__(self, root: Path): + self.root = root + + def head(self) -> str: + return commit_sha(command(["git", "rev-parse", "HEAD"], self.root).strip()) + + def ensure_commit(self, sha: str) -> None: + sha = commit_sha(sha) + kind = command(["git", "cat-file", "--batch-check=%(objecttype)"], self.root, f"{sha}\n").strip() + if kind == f"{sha} missing": + command(["git", "fetch", "--no-tags", "--depth=1", "origin", sha], self.root) + elif kind != "commit": + raise ReleaseError(f"{sha} is not a commit: {kind}.") + + def read(self, sha: str, path: str) -> str: + return command(["git", "show", f"{commit_sha(sha)}:{path}"], self.root) + + def versions(self, sha: str) -> dict[str, str]: + result: dict[str, str] = {} + for name, path in PROJECTS.items(): + project = object_value(tomllib.loads(self.read(sha, path)).get("project")) + if project.get("name") != name: + raise ReleaseError(f"{path} does not describe {name}.") + result[name] = string_value(project.get("version")) + return result + + +def release_notes(changelog: str, version: str) -> str: + headings = list(re.finditer(r"(?m)^## \[([^\]\r\n]+)\][^\r\n]*\r?\n", changelog)) + matches = [index for index, heading in enumerate(headings) if heading[1] == version] + if len(matches) != 1: + raise ReleaseError(f"Expected exactly one changelog section for {version}.") + index = matches[0] + end = headings[index + 1].start() if index + 1 < len(headings) else len(changelog) + notes = changelog[headings[index].end() : end].strip() + if not notes: + raise ReleaseError(f"The changelog section for {version} is empty.") + return notes + "\n" + + +def snapshot(repo: Repository, sha: str) -> Release: + versions = repo.versions(sha) + if len(set(versions.values())) != 1: + raise ReleaseError(f"Project versions must be synchronized: {versions}.") + version = versions["azure-kusto-python"] + version_numbers(version) + locked = objects(tomllib.loads(repo.read(sha, "uv.lock")).get("package")) + for name in PROJECTS: + entries = [entry for entry in locked if entry.get("name") == name] + if len(entries) != 1 or entries[0].get("version") != version: + raise ReleaseError(f"uv.lock must contain one workspace record for {name}=={version}.") + return Release(version, commit_sha(sha), release_notes(repo.read(sha, "CHANGELOG.md"), version)) + + +def compare_release(repo: Repository, before: str, after: str) -> Release | None: + before, after = commit_sha(before), commit_sha(after) + if repo.head() != after: + raise ReleaseError("The checkout does not match the commit being validated.") + repo.ensure_commit(before) + previous, current = repo.versions(before), repo.versions(after) + if previous == current: + print("Project versions are unchanged; no tag, dispatch, or publication is needed.") + return None + if len(set(previous.values())) != 1: + raise ReleaseError(f"The previous project versions were not synchronized: {previous}.") + release = snapshot(repo, after) + if version_numbers(release.version) <= version_numbers(previous["azure-kusto-python"]): + raise ReleaseError("The release version must increase.") + return release + + +def prepare_push(repo: Repository, event: dict[str, object]) -> Release | None: + if event.get("ref") != "refs/heads/master" or event.get("deleted") is not False or event.get("forced") is not False: + raise ReleaseError("Release preparation requires a non-deleted, non-forced push to master.") + return compare_release(repo, commit_sha(event.get("before")), commit_sha(event.get("after"))) + + +def validate_pr(repo: Repository, event: dict[str, object], sha: str) -> Release | None: + base = object_value(object_value(event.get("pull_request")).get("base")) + if base.get("ref") != "master": + raise ReleaseError("Release metadata validation requires a PR targeting master.") + return compare_release(repo, commit_sha(base.get("sha")), commit_sha(sha)) + + +class GitHub: + def __init__(self, repository: str): + if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository): + raise ReleaseError(f"Invalid GitHub repository: {repository!r}.") + self.repository = repository + + def request(self, method: str, path: str, data: dict[str, object] | None = None, missing_ok: bool = False) -> object: + args = [ + "gh", + "api", + "--include", + "--method", + method, + "-H", + "Accept: application/vnd.github+json", + "-H", + "X-GitHub-Api-Version: 2026-03-10", + f"repos/{self.repository}/{path}", + ] + if data is not None: + args.extend(["--input", "-"]) + result = subprocess.run(args, input=json.dumps(data) if data is not None else None, text=True, encoding="utf-8", capture_output=True, check=False) + headers, separator, body = result.stdout.partition("\n\n") + status = re.match(r"HTTP/[\d.]+ (\d+)", headers) + if not separator or status is None: + raise ReleaseError(f"GitHub {method} {path} failed: {result.stderr.strip() or result.stdout.strip()}") + code = int(status[1]) + if method == "GET" and missing_ok and code == 404: + return None + if not 200 <= code < 300 or result.returncode: + raise ReleaseError(f"GitHub {method} {path} failed with HTTP {code}: {body.strip() or result.stderr.strip()}") + return json.loads(body) if body.strip() else None + + def tag_commit(self, tag: str) -> str | None: + ref = self.request("GET", f"git/ref/tags/{tag}", missing_ok=True) + if ref is None: + return None + target = object_value(object_value(ref).get("object")) + for _ in range(10): + sha = commit_sha(target.get("sha")) + if target.get("type") == "commit": + return sha + if target.get("type") != "tag": + raise ReleaseError(f"{tag} does not resolve to a commit.") + target = object_value(object_value(self.request("GET", f"git/tags/{sha}")).get("object")) + raise ReleaseError(f"{tag} has too many nested annotated tags.") + + def pages(self, path: str, key: str | None = None) -> list[dict[str, object]]: + result: list[dict[str, object]] = [] + page = 1 + while True: + separator = "&" if "?" in path else "?" + response = self.request("GET", f"{path}{separator}per_page=100&page={page}") + items = objects(object_value(response).get(key) if key else response) + result.extend(items) + if len(items) < 100: + return result + page += 1 + + def upload_asset(self, tag: str, path: Path) -> None: + command(["gh", "release", "upload", tag, str(path), "--repo", self.repository]) + + def downloaded_digest(self, tag: str, name: str) -> str: + with tempfile.TemporaryDirectory() as temporary: + command(["gh", "release", "download", tag, "--repo", self.repository, "--pattern", name, "--dir", temporary]) + return f"sha256:{file_digest(Path(temporary) / name)}" + + +def validate_tag(repo: Repository, github: GitHub, ref: str, sha: str) -> Release: + if not ref.startswith("refs/tags/v"): + raise ReleaseError("Publishing requires a stable version tag, not a branch.") + version_numbers(ref.removeprefix("refs/tags/v")) + sha = commit_sha(sha) + if repo.head() != sha: + raise ReleaseError("The checkout does not match the release commit.") + release = snapshot(repo, sha) + if ref != f"refs/tags/{release.tag}" or github.tag_commit(release.tag) != sha: + raise ReleaseError("The version tag, project versions, and release commit must agree.") + return release + + +def tag_and_dispatch(repo: Repository, github: GitHub, tag: str, sha: str) -> None: + version_numbers(tag.removeprefix("v")) + release = snapshot(repo, commit_sha(sha)) + if tag != release.tag or repo.head() != sha: + raise ReleaseError("The tag and checkout must match the validated release.") + existing = github.tag_commit(tag) + if existing is None: + github.request("POST", "git/refs", {"ref": f"refs/tags/{tag}", "sha": sha}) + print(f"Created {tag} at {sha}.") + elif existing != sha: + raise ReleaseError(f"{tag} already points to {existing}; refusing to move it to {sha}.") + query = urlencode({"branch": tag, "head_sha": sha}) + runs = [ + run + for run in github.pages(f"actions/workflows/release.yml/runs?{query}", "workflow_runs") + if run.get("head_branch") == tag and run.get("head_sha") == sha and run.get("event") in ("push", "workflow_dispatch") + ] + for run in runs: + if run.get("conclusion") == "success" or string_value(run.get("status")) != "completed": + print(f"A matching release run already exists: {string_value(run.get('html_url'))}") + return + if runs: + raise ReleaseError(f"Inspect {string_value(runs[0].get('html_url'))} and retry its failed jobs; refusing to dispatch another publisher.") + dispatched = github.request("POST", "actions/workflows/release.yml/dispatches", {"ref": tag, "return_run_details": True}) + if dispatched is None: + print(f"Dispatched release workflow for {tag} at {sha}; the API returned no run details. Inspect the release workflow runs.") + else: + print(f"Dispatched release workflow: {string_value(object_value(dispatched).get('html_url'))}.") + print("Dispatch does not imply publication succeeded.") + + +def distributions(directory: Path, version: str) -> list[Path]: + version_numbers(version) + expected = {f"{package.replace('-', '_')}-{version}{suffix}" for package in PACKAGES for suffix in ("-py3-none-any.whl", ".tar.gz")} + if {path.name for path in directory.iterdir() if path.name != ".gitignore"} != expected: + raise ReleaseError(f"Expected exactly the SDK wheels and source distributions for {version}.") + result: list[Path] = [] + for package in PACKAGES: + basename = f"{package.replace('-', '_')}-{version}" + wheel, source = directory / f"{basename}-py3-none-any.whl", directory / f"{basename}.tar.gz" + with zipfile.ZipFile(wheel) as archive: + entries = [name for name in archive.namelist() if name.endswith(".dist-info/METADATA")] + if len(entries) != 1: + raise ReleaseError(f"Expected one wheel metadata file in {wheel.name}.") + wheel_metadata = archive.read(entries[0]) + with tarfile.open(source, "r:gz") as archive: + entries = [member for member in archive.getmembers() if member.name.endswith("/PKG-INFO") and member.name.count("/") == 1] + if len(entries) != 1 or (stream := archive.extractfile(entries[0])) is None: + raise ReleaseError(f"Expected one source metadata file in {source.name}.") + with stream: + source_metadata = stream.read() + for metadata in (wheel_metadata, source_metadata): + parsed = BytesParser().parsebytes(metadata, headersonly=True) + if parsed["Name"] != package or parsed["Version"] != version: + raise ReleaseError(f"Distribution metadata does not match {package}=={version}.") + result.extend([wheel, source]) + return result + + +def file_digest(path: Path) -> str: + with path.open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def finalize_release(repo: Repository, github: GitHub, ref: str, sha: str, directory: Path) -> None: + release = validate_tag(repo, github, ref, sha) + files = distributions(directory, release.version) + matches = [item for item in github.pages("releases") if item.get("tag_name") == release.tag] + if len(matches) > 1: + raise ReleaseError(f"Multiple GitHub releases match {release.tag}; refusing to choose one.") + response = ( + matches[0] + if matches + else github.request("POST", "releases", {"tag_name": release.tag, "name": release.tag, "body": release.notes, "draft": True, "prerelease": False}) + ) + existing = object_value(response) + release_id = existing.get("id") + if ( + not isinstance(release_id, int) + or isinstance(release_id, bool) + or release_id <= 0 + or existing.get("tag_name") != release.tag + or not isinstance(existing.get("draft"), bool) + ): + raise ReleaseError("GitHub returned an invalid release.") + url = string_value(existing.get("html_url")) + assets = github.pages(f"releases/{release_id}/assets") + missing: list[Path] = [] + incomplete: list[int] = [] + for path in files: + matches = [asset for asset in assets if asset.get("name") == path.name] + if len(matches) > 1: + raise ReleaseError(f"Multiple GitHub assets are named {path.name}.") + if matches: + asset = matches[0] + if asset.get("state") == "starter": + size, asset_id = asset.get("size"), asset.get("id") + if not isinstance(size, int) or isinstance(size, bool) or size != 0: + raise ReleaseError(f"Incomplete asset {path.name} is not an empty upload placeholder; refusing to delete it.") + if not isinstance(asset_id, int) or isinstance(asset_id, bool) or asset_id <= 0: + raise ReleaseError(f"Incomplete asset {path.name} has an invalid ID.") + incomplete.append(asset_id) + missing.append(path) + continue + if asset.get("state") != "uploaded": + raise ReleaseError(f"Existing release asset {path.name} is not fully uploaded.") + digest = asset.get("digest") + if digest is None: + digest = github.downloaded_digest(release.tag, path.name) + if digest != f"sha256:{file_digest(path)}": + raise ReleaseError(f"Existing release asset {path.name} has different content; refusing to overwrite it.") + print(f"Keeping identical release asset {path.name}.") + else: + missing.append(path) + for asset_id in incomplete: + github.request("DELETE", f"releases/assets/{asset_id}") + print(f"Removed incomplete zero-byte upload placeholder {asset_id}.") + for path in missing: + github.upload_asset(release.tag, path) + print(f"Uploaded {path.name}.") + updates: dict[str, object] = {} + if existing.get("draft") is True: + updates["draft"] = False + if existing.get("prerelease") is True: + updates["prerelease"] = False + if updates: + github.request("PATCH", f"releases/{release_id}", updates) + print(f"GitHub Release finalized: {url}") + + +def emit_outputs(release: Release | None) -> None: + values = {"release": "false"} if release is None else {"release": "true", "version": release.version, "tag": release.tag, "sha": release.sha} + print(json.dumps(values)) + if output := os.environ.get("GITHUB_OUTPUT"): + with Path(output).open("a", encoding="utf-8") as stream: + stream.writelines(f"{key}={value}\n" for key, value in values.items()) + + +def main() -> int: + parser = argparse.ArgumentParser() + commands = parser.add_subparsers(dest="action", required=True) + for name in ("prepare", "validate-pr"): + prepare = commands.add_parser(name) + prepare.add_argument("--event", type=Path, required=True) + if name == "validate-pr": + prepare.add_argument("--sha", required=True) + tag = commands.add_parser("tag") + tag.add_argument("--tag", required=True) + tag.add_argument("--sha", required=True) + for name in ("validate", "finalize"): + tagged = commands.add_parser(name) + tagged.add_argument("--ref", required=True) + tagged.add_argument("--sha", required=True) + if name == "finalize": + tagged.add_argument("--dist", type=Path, required=True) + verify = commands.add_parser("verify-dist") + verify.add_argument("--dist", type=Path, required=True) + verify.add_argument("--version", required=True) + args = parser.parse_args() + try: + repo = Repository(Path.cwd()) + if args.action in ("prepare", "validate-pr"): + required_event = "push" if args.action == "prepare" else "pull_request" + if os.environ.get("GITHUB_EVENT_NAME") != required_event: + raise ReleaseError(f"{args.action} requires a {required_event} event.") + event = object_value(json.loads(args.event.read_text(encoding="utf-8"))) + emit_outputs(prepare_push(repo, event) if args.action == "prepare" else validate_pr(repo, event, args.sha)) + elif args.action == "verify-dist": + distributions(args.dist, args.version) + else: + github = GitHub(string_value(os.environ.get("GITHUB_REPOSITORY"))) + if args.action == "tag": + if os.environ.get("GITHUB_EVENT_NAME") != "push" or os.environ.get("GITHUB_REF") != "refs/heads/master": + raise ReleaseError("Only a master push can create and dispatch a release tag.") + tag_and_dispatch(repo, github, args.tag, args.sha) + else: + if os.environ.get("GITHUB_EVENT_NAME") not in ("push", "workflow_dispatch"): + raise ReleaseError("Only a tag push or tagged dispatch can publish a release.") + if args.action == "validate": + emit_outputs(validate_tag(repo, github, args.ref, args.sha)) + else: + finalize_release(repo, github, args.ref, args.sha, args.dist) + return 0 + except (ReleaseError, OSError, subprocess.CalledProcessError, tomllib.TOMLDecodeError, json.JSONDecodeError, tarfile.TarError, zipfile.BadZipFile) as error: + detail = error.stderr if isinstance(error, subprocess.CalledProcessError) and error.stderr else str(error) + print(f"::error::{detail}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/scripts/test_release_tools.py b/.github/scripts/test_release_tools.py new file mode 100644 index 00000000..306c7732 --- /dev/null +++ b/.github/scripts/test_release_tools.py @@ -0,0 +1,406 @@ +import io +import json +import os +import subprocess +import sys +import tarfile +import tempfile +import unittest +import zipfile +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path +from unittest.mock import Mock, call, patch + +import release_tools as release + + +class ReleaseToolsTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + self.repo = release.Repository(self.root) + self.git("init", "--initial-branch=master") + self.git("config", "user.name", "Release tests") + self.git("config", "user.email", "release-tests@example.invalid") + self.github = Mock(spec=release.GitHub) + self.github.repository = "Azure/azure-kusto-python" + self.before = self.commit_version("6.0.4") + self.after = self.commit_version("6.0.5") + self.github.tag_commit.return_value = self.after + self.github.pages.return_value = [] + + def git(self, *args: str) -> str: + return release.command(["git", *args], self.root).strip() + + def commit_version(self, version: str) -> str: + for name, filename in release.PROJECTS.items(): + path = self.root / filename + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f'[project]\nname = "{name}"\nversion = "{version}"\n', encoding="utf-8") + (self.root / "uv.lock").write_text("\n".join(f'[[package]]\nname = "{name}"\nversion = "{version}"\n' for name in release.PROJECTS), encoding="utf-8") + (self.root / "CHANGELOG.md").write_text( + f"# Changelog\n\n## [Unreleased]\n\n## [{version}] - 2026-11-24\n\n### Fixed\n- Release fix.\n\n## [5.0.0] - 2025-01-01\n\n- Older notes.\n", + encoding="utf-8", + ) + return self.commit() + + def commit(self) -> str: + self.git("add", ".") + self.git("commit", "-m", "Update release fixture") + return self.repo.head() + + def event(self, before: str | None = None, after: str | None = None) -> dict[str, object]: + return {"ref": "refs/heads/master", "forced": False, "deleted": False, "before": before or self.before, "after": after or self.after} + + def make_distributions(self, metadata_version: str = "6.0.5") -> Path: + directory = self.root / "dist" + directory.mkdir(exist_ok=True) + for package in release.PACKAGES: + basename = f"{package.replace('-', '_')}-6.0.5" + metadata = f"Metadata-Version: 2.4\nName: {package}\nVersion: {metadata_version}\n\n".encode() + with zipfile.ZipFile(directory / f"{basename}-py3-none-any.whl", "w") as archive: + archive.writestr(f"{basename}.dist-info/METADATA", metadata) + with tarfile.open(directory / f"{basename}.tar.gz", "w:gz") as archive: + info = tarfile.TarInfo(f"{basename}/PKG-INFO") + info.size = len(metadata) + archive.addfile(info, io.BytesIO(metadata)) + return directory + + def uploaded_asset(self, path: Path) -> dict[str, object]: + return {"id": 456, "name": path.name, "state": "uploaded", "size": path.stat().st_size, "digest": f"sha256:{release.file_digest(path)}"} + + def mock_release(self, assets: list[dict[str, object]] | None = None, *, draft: bool = False, prerelease: bool = False) -> None: + existing = { + "id": 123, + "tag_name": "v6.0.5", + "draft": draft, + "prerelease": prerelease, + "body": "Maintainer notes", + "html_url": "https://example.invalid/release", + } + self.github.pages.side_effect = [[existing], [] if assets is None else assets] + + def test_release_pr_transition_and_notes(self) -> None: + planned = release.prepare_push(self.repo, self.event()) + self.assertIsNotNone(planned) + if planned is not None: + self.assertEqual((planned.version, planned.sha, planned.notes), ("6.0.5", self.after, "### Fixed\n- Release fix.\n")) + + def test_unchanged_versions_do_not_release(self) -> None: + (self.root / "pyproject.toml").write_text( + (self.root / "pyproject.toml").read_text(encoding="utf-8") + 'description = "Dependency-only or tooling edit"\n', encoding="utf-8" + ) + unchanged = self.commit() + self.assertIsNone(release.prepare_push(self.repo, self.event(self.after, unchanged))) + event = {"pull_request": {"base": {"ref": "master", "sha": self.after}}} + self.assertIsNone(release.validate_pr(self.repo, event, unchanged)) + self.github.assert_not_called() + + def test_pr_cli_validates_metadata_without_mutating_github(self) -> None: + event = self.root / "event.json" + event.write_text(json.dumps({"pull_request": {"base": {"ref": "master", "sha": self.before}}}), encoding="utf-8") + with ( + patch.dict(os.environ, {"GITHUB_EVENT_NAME": "pull_request", "GITHUB_OUTPUT": ""}), + patch.object(sys, "argv", ["release_tools.py", "validate-pr", "--event", str(event), "--sha", self.after]), + patch.object(release, "Repository", return_value=self.repo), + patch.object(release, "GitHub") as github, + redirect_stdout(io.StringIO()), + ): + self.assertEqual(release.main(), 0) + github.assert_not_called() + + def test_pr_validation_rejects_missing_changelog_before_merge(self) -> None: + event = {"pull_request": {"base": {"ref": "master", "sha": self.before}}} + planned = release.validate_pr(self.repo, event, self.after) + self.assertIsNotNone(planned) + if planned is not None: + self.assertEqual(planned.sha, self.after) + (self.root / "CHANGELOG.md").write_text("## [6.0.4]\n\nOld notes only.\n", encoding="utf-8") + invalid = self.commit() + with self.assertRaisesRegex(release.ReleaseError, "changelog section"): + release.validate_pr(self.repo, event, invalid) + self.github.request.assert_not_called() + + def test_multi_commit_push_uses_before_snapshot(self) -> None: + (self.root / "README.md").write_text("Another commit after the bump.\n", encoding="utf-8") + last = self.commit() + planned = release.prepare_push(self.repo, self.event(self.before, last)) + self.assertIsNotNone(planned) + if planned is not None: + self.assertEqual(planned.sha, last) + + def test_shallow_checkout_fetches_the_previous_snapshot(self) -> None: + checkout = self.root / "shallow" + release.command(["git", "clone", "--depth=1", self.root.as_uri(), str(checkout)]) + planned = release.prepare_push(release.Repository(checkout), self.event()) + self.assertIsNotNone(planned) + if planned is not None: + self.assertEqual(planned.sha, self.after) + + def test_invalid_push_contexts_fail(self) -> None: + for overrides in ( + {"ref": "refs/heads/feature"}, + {"forced": True}, + {"deleted": True}, + {"before": "0" * 40}, + {"after": self.before}, + ): + with self.subTest(overrides=overrides), self.assertRaises(release.ReleaseError): + release.prepare_push(self.repo, self.event() | overrides) + + def test_inconsistent_release_metadata_fails(self) -> None: + for filename, original, replacement in ( + ("azure-kusto-data/pyproject.toml", 'version = "6.0.5"', 'version = "6.0.4"'), + ("uv.lock", 'version = "6.0.5"', 'version = "6.0.4"'), + ("CHANGELOG.md", "[6.0.5]", "[6.0.6]"), + ): + with self.subTest(filename=filename): + path = self.root / filename + contents = path.read_text(encoding="utf-8") + path.write_text(contents.replace(original, replacement, 1), encoding="utf-8") + invalid = self.commit() + with self.assertRaises(release.ReleaseError): + release.prepare_push(self.repo, self.event(self.before, invalid)) + event = {"pull_request": {"base": {"ref": "master", "sha": self.before}}} + with self.assertRaises(release.ReleaseError): + release.validate_pr(self.repo, event, invalid) + path.write_text(contents, encoding="utf-8") + self.commit() + + def test_decreasing_and_prerelease_versions_fail(self) -> None: + for version in ("6.0.3", "6.0.6rc1", "06.0.6"): + with self.subTest(version=version): + invalid = self.commit_version(version) + with self.assertRaises(release.ReleaseError): + release.prepare_push(self.repo, self.event(self.before, invalid)) + + def test_publishing_requires_matching_tag_and_commit(self) -> None: + planned = release.validate_tag(self.repo, self.github, "refs/tags/v6.0.5", self.after) + self.assertEqual(planned.sha, self.after) + for ref, sha in (("refs/heads/master", self.after), ("refs/tags/v6.0.4", self.after), ("refs/tags/v6.0.5", self.before)): + with self.subTest(ref=ref, sha=sha), self.assertRaises(release.ReleaseError): + release.validate_tag(self.repo, self.github, ref, sha) + self.github.tag_commit.return_value = self.before + with self.assertRaises(release.ReleaseError): + release.validate_tag(self.repo, self.github, "refs/tags/v6.0.5", self.after) + + def test_create_tag_and_explicitly_dispatch(self) -> None: + self.github.tag_commit.return_value = None + self.github.request.return_value = {"html_url": "https://github.com/Azure/azure-kusto-python/actions/runs/123"} + release.tag_and_dispatch(self.repo, self.github, "v6.0.5", self.after) + self.assertEqual( + self.github.request.call_args_list, + [ + call("POST", "git/refs", {"ref": "refs/tags/v6.0.5", "sha": self.after}), + call("POST", "actions/workflows/release.yml/dispatches", {"ref": "v6.0.5", "return_run_details": True}), + ], + ) + + def test_successful_empty_dispatch_response_is_not_a_failure(self) -> None: + self.github.request.return_value = None + with redirect_stdout(io.StringIO()) as output: + release.tag_and_dispatch(self.repo, self.github, "v6.0.5", self.after) + self.github.request.assert_called_once_with("POST", "actions/workflows/release.yml/dispatches", {"ref": "v6.0.5", "return_run_details": True}) + self.assertIn("Dispatched release workflow for v6.0.5", output.getvalue()) + + def test_existing_tag_recovers_dispatch_but_never_moves(self) -> None: + self.github.request.return_value = {"html_url": "https://github.com/Azure/azure-kusto-python/actions/runs/123"} + release.tag_and_dispatch(self.repo, self.github, "v6.0.5", self.after) + self.github.request.assert_called_once_with("POST", "actions/workflows/release.yml/dispatches", {"ref": "v6.0.5", "return_run_details": True}) + self.github.reset_mock() + self.github.tag_commit.return_value = self.before + with self.assertRaisesRegex(release.ReleaseError, "refusing to move"): + release.tag_and_dispatch(self.repo, self.github, "v6.0.5", self.after) + self.github.request.assert_not_called() + + def test_existing_push_or_dispatch_run_is_not_duplicated(self) -> None: + for event, status, conclusion in (("push", "in_progress", None), ("workflow_dispatch", "completed", "success"), ("push", "completed", "failure")): + with self.subTest(event=event, status=status): + self.github.reset_mock() + self.github.pages.return_value = [ + { + "event": event, + "status": status, + "conclusion": conclusion, + "head_branch": "v6.0.5", + "head_sha": self.after, + "html_url": "https://example.invalid/run", + } + ] + if conclusion == "failure": + with self.assertRaisesRegex(release.ReleaseError, "retry its failed jobs"): + release.tag_and_dispatch(self.repo, self.github, "v6.0.5", self.after) + else: + release.tag_and_dispatch(self.repo, self.github, "v6.0.5", self.after) + self.github.request.assert_not_called() + + def test_distribution_metadata_must_match_before_upload(self) -> None: + directory = self.make_distributions() + self.assertEqual(len(release.distributions(directory, "6.0.5")), 4) + self.make_distributions(metadata_version="6.0.4") + with self.assertRaisesRegex(release.ReleaseError, "metadata does not match"): + release.distributions(directory, "6.0.5") + + def test_existing_release_preserves_notes_and_matching_assets(self) -> None: + directory = self.make_distributions() + files = release.distributions(directory, "6.0.5") + self.mock_release([self.uploaded_asset(files[0])]) + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.request.assert_not_called() + self.assertEqual(self.github.upload_asset.call_args_list, [call("v6.0.5", path) for path in files[1:]]) + + def test_recovered_stable_release_clears_prerelease_for_drafts_and_published_releases(self) -> None: + directory = self.make_distributions() + assets = [self.uploaded_asset(path) for path in release.distributions(directory, "6.0.5")] + for draft in (True, False): + with self.subTest(draft=draft): + self.github.reset_mock(side_effect=True) + self.mock_release(assets, draft=draft, prerelease=True) + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + expected = {"prerelease": False} + if draft: + expected["draft"] = False + self.github.request.assert_called_once_with("PATCH", "releases/123", expected) + self.github.upload_asset.assert_not_called() + self.github.downloaded_digest.assert_not_called() + + def test_matching_draft_on_later_page_resumes_with_its_assets(self) -> None: + directory = self.make_distributions() + draft = {"id": 789, "tag_name": "v6.0.5", "draft": True, "body": "Original draft notes", "html_url": "https://example.invalid/draft"} + assets = [self.uploaded_asset(path) for path in release.distributions(directory, "6.0.5")] + github = release.GitHub("Azure/azure-kusto-python") + with ( + patch.object(github, "tag_commit", return_value=self.after), + patch.object(github, "request", side_effect=[[{"tag_name": f"v0.0.{i}"} for i in range(100)], [draft], assets, {}]) as request, + patch.object(github, "upload_asset") as upload, + ): + release.finalize_release(self.repo, github, "refs/tags/v6.0.5", self.after, directory) + self.assertEqual( + request.call_args_list, + [ + call("GET", "releases?per_page=100&page=1"), + call("GET", "releases?per_page=100&page=2"), + call("GET", "releases/789/assets?per_page=100&page=1"), + call("PATCH", "releases/789", {"draft": False}), + ], + ) + upload.assert_not_called() + + def test_ambiguous_matching_releases_fail_without_mutation(self) -> None: + directory = self.make_distributions() + self.github.pages.return_value = [{"tag_name": "v6.0.5", "draft": False}, {"tag_name": "v6.0.5", "draft": True}] + with self.assertRaisesRegex(release.ReleaseError, "Multiple GitHub releases"): + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.request.assert_not_called() + self.github.upload_asset.assert_not_called() + + def test_conflicting_asset_is_not_overwritten(self) -> None: + directory = self.make_distributions() + first = release.distributions(directory, "6.0.5")[0] + self.mock_release([self.uploaded_asset(first) | {"digest": "sha256:different"}]) + with self.assertRaisesRegex(release.ReleaseError, "refusing to overwrite"): + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.upload_asset.assert_not_called() + + def test_zero_byte_starter_asset_is_deleted_and_reuploaded(self) -> None: + directory = self.make_distributions() + files = release.distributions(directory, "6.0.5") + self.mock_release([self.uploaded_asset(files[0]) | {"state": "starter", "size": 0, "digest": None}]) + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.request.assert_called_once_with("DELETE", "releases/assets/456") + self.assertEqual(self.github.upload_asset.call_args_list, [call("v6.0.5", path) for path in files]) + self.github.downloaded_digest.assert_not_called() + + def test_only_valid_empty_starter_assets_can_be_deleted(self) -> None: + directory = self.make_distributions() + first = release.distributions(directory, "6.0.5")[0] + for overrides in ( + {"state": "starter", "size": 1}, + {"state": "starter", "size": 0, "id": None}, + {"state": "starter", "size": 0, "id": True}, + {"state": "uploaded", "size": 0, "digest": "sha256:different"}, + ): + with self.subTest(overrides=overrides): + self.github.reset_mock(side_effect=True) + self.mock_release([self.uploaded_asset(first) | overrides]) + with self.assertRaises(release.ReleaseError): + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.request.assert_not_called() + self.github.upload_asset.assert_not_called() + + def test_legacy_asset_is_compared_using_downloaded_content(self) -> None: + directory = self.make_distributions() + first = release.distributions(directory, "6.0.5")[0] + self.mock_release([self.uploaded_asset(first) | {"digest": None}]) + self.github.downloaded_digest.return_value = f"sha256:{release.file_digest(first)}" + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.downloaded_digest.assert_called_once_with("v6.0.5", first.name) + self.assertNotIn(call("v6.0.5", first), self.github.upload_asset.call_args_list) + + def test_retry_resumes_finalization_without_replacing_uploaded_assets(self) -> None: + directory = self.make_distributions() + files = release.distributions(directory, "6.0.5") + self.mock_release() + self.github.upload_asset.side_effect = [None, subprocess.CalledProcessError(1, ["gh", "release", "upload"], stderr="Upload interrupted")] + with self.assertRaises(subprocess.CalledProcessError): + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.github.reset_mock(side_effect=True) + self.mock_release([self.uploaded_asset(files[0])]) + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.assertEqual(self.github.upload_asset.call_args_list, [call("v6.0.5", path) for path in files[1:]]) + self.github.request.assert_not_called() + + def test_new_release_publishes_only_after_uploads(self) -> None: + directory = self.make_distributions() + self.github.pages.side_effect = [[], []] + self.github.request.side_effect = [{"id": 123, "tag_name": "v6.0.5", "draft": True, "html_url": "https://example.invalid/release"}, {}] + release.finalize_release(self.repo, self.github, "refs/tags/v6.0.5", self.after, directory) + self.assertEqual(self.github.upload_asset.call_count, 4) + self.assertEqual(self.github.request.call_args_list[-1], call("PATCH", "releases/123", {"draft": False})) + + +class GitHubResponseTests(unittest.TestCase): + def test_pr_events_cannot_prepare_tag_or_finalize_a_release(self) -> None: + for args in ( + ["prepare", "--event", "unused.json"], + ["tag", "--tag", "v6.0.5", "--sha", "a" * 40], + ["finalize", "--ref", "refs/pull/1/merge", "--sha", "a" * 40, "--dist", "unused"], + ): + with ( + self.subTest(action=args[0]), + patch.dict( + os.environ, {"GITHUB_EVENT_NAME": "pull_request", "GITHUB_REF": "refs/pull/1/merge", "GITHUB_REPOSITORY": "Azure/azure-kusto-python"} + ), + patch.object(sys, "argv", ["release_tools.py", *args]), + patch.object(release, "GitHub") as github, + redirect_stderr(io.StringIO()), + ): + self.assertEqual(release.main(), 1) + self.assertEqual(github.return_value.mock_calls, []) + + def test_only_not_found_can_be_treated_as_missing(self) -> None: + github = release.GitHub("Azure/azure-kusto-python") + for code in (404, 403, 429, 500): + response = subprocess.CompletedProcess( + ["gh"], 1, f"HTTP/2.0 {code} Error\ncontent-type: application/json\n\n" + json.dumps({"message": "API error"}), "" + ) + with self.subTest(code=code), patch.object(release.subprocess, "run", return_value=response): + if code == 404: + self.assertIsNone(github.request("GET", "releases/tags/v6.0.5", missing_ok=True)) + else: + with self.assertRaisesRegex(release.ReleaseError, f"HTTP {code}"): + github.request("GET", "releases/tags/v6.0.5", missing_ok=True) + + def test_annotated_tags_are_resolved(self) -> None: + github = release.GitHub("Azure/azure-kusto-python") + with patch.object( + github, + "request", + side_effect=[{"object": {"type": "tag", "sha": "a" * 40}}, {"object": {"type": "commit", "sha": "b" * 40}}], + ): + self.assertEqual(github.tag_commit("v6.0.5"), "b" * 40) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 670d2756..92eeee28 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,40 +1,108 @@ -# This workflows will upload a Python Package using Twine when a release is created -# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries - name: release + permissions: - checks: write - pull-requests: write - packages: write - deployments: write - contents: write - id-token: write + contents: read on: push: tags: - "v[0-9]+.[0-9]+.[0-9]+" + workflow_dispatch: + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false jobs: - deploy: + build: + runs-on: ubuntu-latest + outputs: + artifact-id: ${{ steps.artifact.outputs.artifact-id }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - name: Install uv and set the build Python version + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.9" + enable-cache: true + - name: Validate the release tag and metadata + id: release + env: + GH_TOKEN: ${{ github.token }} + run: uv run --no-project --python 3.11 python .github/scripts/release_tools.py validate --ref "$GITHUB_REF" --sha "$GITHUB_SHA" + - name: Build + run: uv build --all-packages + - name: Verify the SDK distribution metadata + env: + RELEASE_VERSION: ${{ steps.release.outputs.version }} + run: uv run --no-project --python 3.11 python .github/scripts/release_tools.py verify-dist --dist dist --version "$RELEASE_VERSION" + - name: Retain the exact distributions for publishing and recovery + id: artifact + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: release-${{ github.ref_name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: dist/ + if-no-files-found: error + compression-level: 0 + + publish: + needs: build runs-on: ubuntu-latest environment: release + permissions: + contents: read + id-token: write + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + artifact-ids: ${{ needs.build.outputs.artifact-id }} + path: dist + digest-mismatch: error + - name: Publish + id: publish + uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 + with: + packages-dir: dist + - name: Record publication outcome + if: always() + env: + PUBLISH_OUTCOME: ${{ steps.publish.outcome }} + run: | + if [[ "$PUBLISH_OUTCOME" == "success" ]]; then + echo "PyPI publication succeeded. Retry only failed GitHub finalization jobs, not the whole workflow." >> "$GITHUB_STEP_SUMMARY" + else + echo "::warning::Inspect the Publish logs before retrying: partial PyPI uploads may exist. Retain the original build artifact." + echo "Publication did not complete. Inspect the Publish logs for partial uploads before any retry." >> "$GITHUB_STEP_SUMMARY" + fi + + github-release: + needs: [build, publish] + runs-on: ubuntu-latest + permissions: + contents: write steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - name: Install uv and set the python version - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - with: - python-version: '3.9' - enable-cache: true - - name: Build - run: uv build --all-packages - - name: Publish - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # v1.14.3 - with: - packages-dir: dist - - name: Release - uses: docker://antonyurchenko/git-release:latest - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - args: dist/*.tar.gz dist/*.whl + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.11" + enable-cache: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + artifact-ids: ${{ needs.build.outputs.artifact-id }} + path: dist + digest-mismatch: error + - name: Create or complete the GitHub Release without republishing PyPI + env: + GH_TOKEN: ${{ github.token }} + run: uv run --no-project --python 3.11 python .github/scripts/release_tools.py finalize --ref "$GITHUB_REF" --sha "$GITHUB_SHA" --dist dist + - name: Record finalization recovery instructions + if: failure() + run: | + echo "::error::PyPI publication already succeeded. Rerun failed jobs only; do not rerun the entire workflow." + echo "PyPI publication succeeded. Use **Re-run failed jobs** to retry GitHub finalization with the retained distributions." >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/tag-release.yml b/.github/workflows/tag-release.yml new file mode 100644 index 00000000..b5f38f92 --- /dev/null +++ b/.github/workflows/tag-release.yml @@ -0,0 +1,85 @@ +name: prepare release + +on: + push: + branches: ["master"] + pull_request: + branches: ["master"] + paths: + - ".github/scripts/**" + - ".github/workflows/release.yml" + - ".github/workflows/tag-release.yml" + - "pyproject.toml" + - "azure-kusto-data/pyproject.toml" + - "azure-kusto-ingest/pyproject.toml" + - "quick-start/pyproject.toml" + - "uv.lock" + - "CHANGELOG.md" + +permissions: + contents: read + +jobs: + validate: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.11" + enable-cache: false + - name: Test release automation without credentials + run: uv run --no-project --python 3.11 python -m unittest discover -s .github/scripts -p test_release_tools.py -b + - name: Validate changed release metadata before merge + if: github.event_name == 'pull_request' + run: uv run --no-project --python 3.11 python .github/scripts/release_tools.py validate-pr --event "$GITHUB_EVENT_PATH" --sha "$GITHUB_SHA" + + prepare: + needs: validate + if: github.event_name == 'push' && github.ref == 'refs/heads/master' + runs-on: ubuntu-latest + outputs: + release: ${{ steps.plan.outputs.release }} + tag: ${{ steps.plan.outputs.tag }} + sha: ${{ steps.plan.outputs.sha }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.11" + enable-cache: false + - name: Compare release metadata at the pushed commits + id: plan + run: uv run --no-project --python 3.11 python .github/scripts/release_tools.py prepare --event "$GITHUB_EVENT_PATH" + + tag: + needs: prepare + if: needs.prepare.outputs.release == 'true' + runs-on: ubuntu-latest + concurrency: + group: tag-release-${{ needs.prepare.outputs.tag }} + cancel-in-progress: false + permissions: + contents: write + actions: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ needs.prepare.outputs.sha }} + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.11" + enable-cache: false + - name: Create immutable tag and explicitly dispatch publishing + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ needs.prepare.outputs.tag }} + RELEASE_SHA: ${{ needs.prepare.outputs.sha }} + run: uv run --no-project --python 3.11 python .github/scripts/release_tools.py tag --tag "$RELEASE_TAG" --sha "$RELEASE_SHA" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 01cc4a8a..c8ac9464 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -205,6 +205,69 @@ The Azure pipeline currently treats type checking as optional, so even errors do Note that we have a `baseline.json` file that is used to ignore old type errors, as we gradually add types to the codebase. +## Releases + +Stable releases are automatic when synchronized project versions increase on protected `master`. +This includes merged release-preparation PRs and direct version-bump pushes by administrators. +Ordinary PR merges, dependency-only edits, and changes with unchanged versions do not publish. + +1. Prepare the version bump with `poe bump-version patch` (or `minor`/`major`). + Update the matching `CHANGELOG.md` section and check `uv lock --check`. + The root workspace, both SDKs, quick-start, and their four `uv.lock` records must share the same stable `major.minor.patch` version. +2. Submit the metadata and changelog changes through the normal PR checks and merge them. + Read-only PR validation compares the merge snapshot with the base commit and checks release metadata whenever project versions change. +3. The `prepare release` workflow creates `vX.Y.Z` at the exact pushed commit and explicitly dispatches `release.yml` at that tag. + The `release` workflow builds both SDKs, retains the distributions, publishes to PyPI, and finalizes the GitHub Release. + +The tag-creation job needs `contents: write` and `actions: write` for `GITHUB_TOKEN`; +repository/organization policy must permit these job-scoped permissions. +No personal access token or GitHub App is required. +Explicit dispatch is necessary because tag pushes made with `GITHUB_TOKEN` do not themselves trigger push workflows. +The publishing workflow retains the `release` environment and its PyPI trusted-publisher identity. + +A maintainer's manual push of a matching version tag still starts publishing. +There is no need to manually publish a GitHub Release for the normal automated flow. +If a GitHub Release already exists, finalization preserves its notes and unrelated assets and attaches the missing distributions. +Existing distribution assets must have identical content; conflicting assets are never overwritten. +New releases are published after their assets are uploaded; an existing draft is completed and published. +Recovered releases for stable version tags have their prerelease flag cleared without replacing notes or assets. +Finalization finds drafts through the paginated release list. +Only incomplete zero-byte `starter` upload placeholders are deleted and re-uploaded during recovery; completed assets are preserved. + +If a tag exists but no publishing run started, dispatch the tagged workflow: + +```shell +gh workflow run release.yml --repo Azure/azure-kusto-python --ref vX.Y.Z +``` + +Only dispatch a tag containing the updated workflow, and inspect existing runs first. +Dispatches on branches fail validation rather than publish. +Updating `master` does not update workflow definitions in older tags or existing runs. + +### Recovering a release + +If `prepare` fails after merge before creating a tag, correct the release metadata through a PR. +A metadata-only repair with unchanged versions will not start a release. +After validating the corrected `master` commit, manually create and push the missing version tag at that commit. +Do not rerun the original failed preparation job: it still validates the original broken commit. +If that version tag already exists, do not move it; reconcile the release state with a maintainer instead. + +Check individual jobs, not only the overall workflow status. +If `publish` succeeded but `github-release` failed, the packages are already on PyPI. +Choose **Re-run failed jobs**, or use `gh run rerun RUN_ID --failed --repo Azure/azure-kusto-python`. +This retries GitHub finalization using the retained original distributions without rebuilding or republishing them. +Do not rerun the entire workflow, move the version tag, or overwrite published assets. + +If PyPI publication failed, inspect the upload logs for partial publication before retrying. +Keep the original build artifact and have a maintainer reconcile any partial uploads. +If the artifact has expired, do not silently rebuild or substitute distributions for already-published files. + +The release tooling uses Python 3.11 and standard-library-only tests, independently of the SDK Python support matrix: + +```shell +uv run --no-project --python 3.11 python -m unittest discover -s .github/scripts -p test_release_tools.py -b +``` + ## PRs We welcome contributions. In order to make the PR process efficient, please follow the below checklist: diff --git a/pyproject.toml b/pyproject.toml index 3a753532..9297929a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -86,6 +86,10 @@ args = { bump = { help = "Bump version [possible values: major, minor, patch, st [tool.basedpyright] pythonVersion = "3.9" +executionEnvironments = [ + { root = ".github/scripts", pythonVersion = "3.11" }, + { root = "." }, +] reportUnnecessaryTypeIgnoreComment = false reportExplicitAny = false reportAny = false