Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions tooling/extension-bindings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,14 @@ registry data only, and later pushes update the same comment. A second
workflow, `publish-setup-card-comment.yml`, posts it, so pull requests from
forks get the comment too.

The card ends with an **After the merge** table: for each package and registry
the merge regenerates, the newest version on the registry now, the version in
packages.yaml after the merge, and what happens: it publishes the new version,
it is a first release, or the version is older than the registry's newest and
needs a bump. Packages whose version is already published are folded into a
list below it. The comment also appears when the merge only publishes new
versions, so the table is seen.

Maven Central uploads are published by hand in the Portal unless
`maven_auto_publish` (or `auto_publish` on `binding-publish-maven.yml`) is set.
Then each upload is published once it passes validation, and the workflow waits
Expand Down
124 changes: 120 additions & 4 deletions tooling/extension-bindings/ci/publish_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
card lists the values to type in. The first upload turns it into the
project's trusted publisher, so a project that exists needs nothing.

The card ends with a table of every package the merge regenerates, in every
language: the newest version its registry has now, the version in
packages.yaml after the merge, and whether the merge publishes it.

Go and Maven Central need no setup. Everything here reads public registry
data, so the check needs no token. It parses YAML and runs git, and never runs
code from the pull request's packages.
Expand All @@ -27,6 +31,7 @@

import argparse
import json
import re
import time
import urllib.error
import urllib.request
Expand All @@ -37,7 +42,7 @@

import yaml

from generation import CATALOG_FILE, automatic_targets, write_outputs
from generation import CATALOG_FILE, _yaml_at, automatic_targets, write_outputs

MARKER = "<!-- publish-setup-card -->"
OWNER, REPOSITORY = "runtimeconditions", "extensions"
Expand Down Expand Up @@ -147,6 +152,111 @@ def packages(root: Path, base: str, head: str) -> list[Package]:
return found


REGISTRIES = {"go": "Go", "python": "PyPI", "typescript": "npm", "java": "Maven Central"}
LANGUAGE_ORDER = list(REGISTRIES)


@dataclass(frozen=True)
class Change:
"""What one package's registry looks like now, and the version the merge leads to."""

target: str
language: str
name: str
version: str # in packages.yaml after the merge
latest: str | None # newest version on the registry now, or None when it has none
published: bool # the registry already has this version


def changes(root: Path, base: str, head: str) -> list[Package]:
"""Every package, in every language, that the pull request would regenerate."""
chosen, _ = automatic_targets(root, base, head)
catalog = yaml.safe_load((root / CATALOG_FILE).read_text(encoding="utf-8"))["packages"]
found = []
for target in chosen:
key, language = target.split(":")
config = catalog[key]["languages"][language]
found.append(Package(target, language, str(config["coordinate"]), str(config["version"])))
return sorted(found, key=lambda item: (item.target.split(":")[0], LANGUAGE_ORDER.index(item.language)))


def version_order(version: str) -> tuple:
return tuple(int(part) if part.isdigit() else -1 for part in re.split(r"[.-]", version))


def newest(versions: set[str]) -> str | None:
return max(versions, key=version_order) if versions else None


def registry_versions(package: Package, get: Fetch) -> set[str]:
"""The versions a package's registry lists, without a leading v; empty when the package is not there."""
if package.language == "go":
body = get(f"https://proxy.golang.org/{package.name}/@v/list")
return {line.strip().removeprefix("v") for line in (body or b"").decode().splitlines() if line.strip()}
if package.language == "python":
body = get(f"https://pypi.org/pypi/{package.name}/json")
return set(json.loads(body).get("releases", {})) if body else set()
if package.language == "typescript":
body = get("https://registry.npmjs.org/" + package.name.replace("/", "%2F"))
return set(json.loads(body).get("versions", {})) - {STAGE_PLACEHOLDER} if body else set()
group, artifact = package.name.split(":")
body = get(f"https://repo1.maven.org/maven2/{group.replace('.', '/')}/{artifact}/maven-metadata.xml")
return set(re.findall(r"<version>([^<]+)</version>", body.decode())) if body else set()


def look_up_changes(found: list[Package], get: Fetch = fetch) -> list[Change]:
def change(package: Package) -> Change:
versions = registry_versions(package, get)
return Change(package.target, package.language, package.name, package.version, newest(versions),
package.version in versions)

return gather(found, change)


def older(change: Change) -> bool:
"""The version is not published, but the registry already has a newer one, so the version needs a bump."""
return not change.published and change.latest is not None and \
version_order(change.version) < version_order(change.latest)


def what_happens(change: Change) -> str:
if change.published:
return "already published; nothing to publish"
if older(change):
return f"⚠️ older than {change.latest} on the registry; bump the version in packages.yaml"
if change.latest is None:
staged = ", staged for approval on npmjs.com" if change.language == "typescript" else ""
return f"first release{staged}"
return f"publishes {change.version}"


def changes_table(found: list[Change]) -> list[str]:
"""New versions in a table; packages whose version is already out are folded away, since a change to shared
tooling regenerates every package."""
key = lambda item: item.target.split(":")[0] # noqa: E731
lines = ["", "#### After the merge", ""]
publishing = [item for item in found if not item.published]
if publishing:
lines += ["| Package | Registry | Now | After the merge | What happens |", "| --- | --- | --- | --- | --- |"]
lines += [
f"| {key(item)} | {REGISTRIES[item.language]} | {item.latest or '—'} | {item.version} | {what_happens(item)} |"
for item in publishing
]
else:
lines.append("No new versions: every regenerated package keeps a version its registry already has.")
same = [item for item in found if item.published]
if same:
lines += [
"",
f"<details><summary>Regenerated, version already published ({len(same)})</summary>",
"",
*[f"- {key(item)} on {REGISTRIES[item.language]}: {item.version}" for item in same],
"",
"</details>",
]
return lines


def npm_state(package: Package, get: Fetch) -> str:
body = get("https://registry.npmjs.org/" + package.name.replace("/", "%2F"))
if body is None:
Expand Down Expand Up @@ -191,7 +301,7 @@ def trust_command(names: list[str]) -> str:
)


def card(findings: list[Finding]) -> str:
def card(findings: list[Finding], after: list[Change] | None = None) -> str:
by_state: dict[str, list[str]] = {}
for finding in findings:
by_state.setdefault(finding.state, []).append(finding.package.name)
Expand Down Expand Up @@ -270,6 +380,8 @@ def card(findings: list[Finding]) -> str:
if rest:
lines += ["", f"<details><summary>No setup needed ({len(rest)})</summary>", "", *rest, "", "</details>"]
lines += ["", "Go and Maven Central need no setup."]
if after:
lines += changes_table(after)
return "\n".join(lines) + "\n"


Expand All @@ -281,8 +393,12 @@ def main(argv: list[str] | None = None) -> None:
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args(argv)
findings = inspect(packages(args.root, args.base, args.head))
args.output.write_text(card(findings), encoding="utf-8")
needed = any(finding.state in ACTION or finding.state == NPM_NEW for finding in findings)
after = look_up_changes(changes(args.root, args.base, args.head))
args.output.write_text(card(findings, after), encoding="utf-8")
# The comment also appears when the merge only publishes new versions, so the table is seen.
needed = any(finding.state in ACTION or finding.state == NPM_NEW for finding in findings) or any(
not item.published for item in after
)
write_outputs(needed=str(needed).lower())
print(args.output.read_text(encoding="utf-8"))

Expand Down
52 changes: 52 additions & 0 deletions tooling/extension-bindings/ci/test_publish_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,58 @@ def test_it_gives_up_after_the_one_by_one_round(self) -> None:
self.run_rounds({5: 3})


class ChangesTests(unittest.TestCase):
def package(self, language: str, name: str, version: str) -> Package:
return Package(f"queue:{language}", language, name, version)

def test_each_registry_lists_its_versions(self) -> None:
bodies = {
"https://proxy.golang.org/example.com/x/queue/@v/list": b"v0.1.0\nv0.2.0\n",
"https://pypi.org/pypi/example-queue/json": json.dumps({"releases": {"0.1.0": []}}).encode(),
"https://registry.npmjs.org/@example%2Fqueue": npm_document({"0.0.0-stage": {}, "0.1.0": {}}, "0.1.0"),
"https://repo1.maven.org/maven2/io/example/queue/maven-metadata.xml":
b"<metadata><versioning><versions><version>0.1.0</version></versions></versioning></metadata>",
}
get = Registries(bodies)
self.assertEqual(script.registry_versions(self.package("go", "example.com/x/queue", "0.2.0"), get),
{"0.1.0", "0.2.0"})
self.assertEqual(script.registry_versions(self.package("python", "example-queue", "0.2.0"), get), {"0.1.0"})
self.assertEqual(script.registry_versions(self.package("typescript", "@example/queue", "0.2.0"), get),
{"0.1.0"})
self.assertEqual(script.registry_versions(self.package("java", "io.example:queue", "0.2.0"), get), {"0.1.0"})
self.assertEqual(script.registry_versions(self.package("python", "example-missing", "0.1.0"), get), set())

def test_the_newest_version_is_compared_by_number(self) -> None:
self.assertEqual(script.newest({"0.9.0", "0.10.0", "0.2.1"}), "0.10.0")
self.assertIsNone(script.newest(set()))

def test_the_table_says_what_the_merge_does(self) -> None:
after = [
script.Change("env:go", "go", "example.com/x/env", "0.4.0", "0.3.0", False),
script.Change("env:python", "python", "example-env", "0.3.0", "0.3.0", True),
script.Change("gpu:typescript", "typescript", "@example/gpu", "0.2.0", None, False),
script.Change("gpu:java", "java", "io.example:gpu", "0.2.0", None, False),
script.Change("queue:go", "go", "example.com/x/queue", "0.1.0", "0.10.0", False),
]
text = script.card([], after)
self.assertIn("#### After the merge", text)
self.assertIn("| env | Go | 0.3.0 | 0.4.0 | publishes 0.4.0 |", text)
self.assertIn("| gpu | npm | — | 0.2.0 | first release, staged for approval on npmjs.com |", text)
self.assertIn("| gpu | Maven Central | — | 0.2.0 | first release |", text)
self.assertIn("| queue | Go | 0.10.0 | 0.1.0 | ⚠️ older than 0.10.0 on the registry; bump the version", text)
# Versions already out are folded away.
self.assertNotIn("| env | PyPI", text)
self.assertIn("Regenerated, version already published (1)", text)
self.assertIn("- env on PyPI: 0.3.0", text)

def test_only_published_versions_say_so(self) -> None:
text = script.card([], [script.Change("env:python", "python", "example-env", "0.3.0", "0.3.0", True)])
self.assertIn("No new versions", text)

def test_no_table_without_changes(self) -> None:
self.assertNotIn("After the merge", script.card([]))


class CardTests(unittest.TestCase):
def test_one_package_gets_one_trust_command_and_several_get_a_loop(self) -> None:
one = script.trust_command(["@example/a"])
Expand Down
Loading