Skip to content
Draft
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
116 changes: 85 additions & 31 deletions .github/scripts/select_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@
have runtimes installed for other (newer) Xcodes, which the active Xcode
rejects as a test destination.

Used by .github/workflows/ios-ci.yml. On success, prints only the simulator
UDID to stdout; all diagnostics go to stderr.
Used by .github/workflows/ios-ci.yml (and shared with googlemaps-samples/a2ui).
On success, prints only the simulator UDID to stdout; all diagnostics go to
stderr.

Exit codes:
0: Success; UDID printed to stdout.
Expand All @@ -32,11 +33,15 @@
traceback on stderr.
"""

from __future__ import annotations

from collections.abc import Mapping, Sequence
import json
import re
import subprocess
import sys
import traceback
from typing import Any

# Preferred model, so the test device stays stable across runner image updates
# as long as the runtime supports it. Falls back to any iPhone otherwise.
Expand All @@ -47,12 +52,18 @@
EXIT_NO_IPHONE_TYPE = 3
EXIT_UNEXPECTED = 4

_SDK_VERSION_RE = re.compile(r"\d+(\.\d+)*")

# Free-form JSON object parsed from `xcrun simctl list -j`.
JsonObject = Mapping[str, Any]

def log(message):

def log(message: str) -> None:
"""Writes a diagnostic message to stderr."""
print(message, file=sys.stderr)


def xcrun(*args):
def xcrun(*args: str) -> str:
"""Runs `xcrun <args>` and returns stdout, exiting 1 on failure."""
cmd = ["xcrun", *args]
try:
Expand All @@ -65,48 +76,81 @@ def xcrun(*args):
sys.exit(EXIT_XCRUN_FAILED)


def simctl(*args):
def simctl(*args: str) -> str:
"""Runs `xcrun simctl <args>` and returns stdout, exiting 1 on failure."""
return xcrun("simctl", *args)


def version_key(version):
# Non-numeric components (e.g. "0b1" in a beta runtime) sort as 0. Beta
# runtimes are not expected on GitHub-hosted runners.
return tuple(int(p) if p.isdigit() else 0 for p in version.split("."))
def version_key(version: str) -> tuple[int, ...]:
"""Parses a dotted version string into a sortable tuple of integers.

Non-numeric components (e.g. "0b1" in a beta runtime) sort as 0. Beta
runtimes are not expected on GitHub-hosted runners.

Args:
version: Dotted version string such as "18.5.1".

Returns:
Tuple of integer components for version comparison.
"""
return tuple(
int(part) if part.isdigit() else 0 for part in version.split(".")
)


def major_minor(version):
def major_minor(version: str) -> tuple[int, int]:
"""Returns the (major, minor) components of a dotted version string."""
return (version_key(version) + (0, 0))[:2]
parts = version_key(version) + (0, 0)
return (parts[0], parts[1])


def is_ios_runtime(runtime):
return runtime.get("isAvailable") and (
def is_ios_runtime(runtime: JsonObject) -> bool:
"""Returns True if the simctl runtime entry is an available iOS runtime."""
name = runtime.get("name", "")
return bool(runtime.get("isAvailable")) and (
runtime.get("platform") == "iOS"
or runtime.get("name", "").startswith("iOS")
or (isinstance(name, str) and name.startswith("iOS"))
)


def pick_existing_device(devices):
"""Returns the preferred available iPhone, else any available iPhone."""
def pick_existing_device(devices: Sequence[JsonObject]) -> JsonObject | None:
"""Picks an available iPhone simulator from existing runtime devices.

Args:
devices: Simulator device entries for a runtime from `simctl list -j`.

Returns:
The preferred available iPhone device if present, otherwise the first
available iPhone device, or None if no available iPhone simulator exists.
"""
iphones = [
d
for d in devices
if d.get("isAvailable") and d.get("name", "").startswith("iPhone")
device
for device in devices
if device.get("isAvailable")
and isinstance(device.get("name"), str)
and device["name"].startswith("iPhone")
]
for device in iphones:
if device.get("name") == PREFERRED_DEVICE_NAME:
return device
return iphones[0] if iphones else None


def pick_device_type(runtime):
"""Returns the preferred iPhone device type, else the last listed one."""
def pick_device_type(runtime: JsonObject) -> JsonObject | None:
"""Picks a supported iPhone device type for creating a new simulator.

Args:
runtime: Runtime entry from `simctl list -j`.

Returns:
The preferred iPhone device type if supported by the runtime, otherwise the
last listed iPhone device type (typically the newest model), or None if the
runtime has no supported iPhone device types.
"""
iphones = [
dt
for dt in runtime.get("supportedDeviceTypes", [])
if dt.get("productFamily") == "iPhone"
device_type
for device_type in runtime.get("supportedDeviceTypes", [])
if device_type.get("productFamily") == "iPhone"
]
for device_type in iphones:
if device_type.get("name") == PREFERRED_DEVICE_NAME:
Expand All @@ -116,22 +160,30 @@ def pick_device_type(runtime):
return iphones[-1] if iphones else None


def main():
def main() -> int:
"""Selects or creates a compatible iPhone simulator and prints its UDID.

Returns:
Process exit code (0 on success, or an EXIT_* error code).

Raises:
ValueError: If xcrun reports an unexpected iOS Simulator SDK version.
"""
sdk_version = xcrun("--sdk", "iphonesimulator", "--show-sdk-version").strip()
if not re.fullmatch(r"\d+(\.\d+)*", sdk_version):
if not _SDK_VERSION_RE.fullmatch(sdk_version):
raise ValueError(f"Unexpected iOS Simulator SDK version: {sdk_version!r}")
max_version = major_minor(sdk_version)
log(f"Active Xcode iOS Simulator SDK: {sdk_version}")

data = json.loads(simctl("list", "-j"))
runtimes = sorted(
(
r
for r in data.get("runtimes", [])
if is_ios_runtime(r)
and major_minor(r.get("version", "0")) <= max_version
runtime
for runtime in data.get("runtimes", [])
if is_ios_runtime(runtime)
and major_minor(runtime.get("version", "0")) <= max_version
),
key=lambda r: version_key(r.get("version", "0")),
key=lambda runtime: version_key(runtime.get("version", "0")),
reverse=True,
)
if not runtimes:
Expand Down Expand Up @@ -175,6 +227,8 @@ def main():
if __name__ == "__main__":
try:
sys.exit(main())
# Catch all unexpected failures at the CLI boundary so ios-ci.yml always
# receives EXIT_UNEXPECTED and a diagnostic traceback on stderr.
except Exception: # pylint: disable=broad-exception-caught
traceback.print_exc()
sys.exit(EXIT_UNEXPECTED)
46 changes: 46 additions & 0 deletions agent/python_agent/shared/schema/maps_catalog_extension.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,52 @@
}
],
"unevaluatedProperties": false
},
"AdvancedPlaceList": {
"description": "Renders a Google Maps Places UI Kit advanced place list (<gmp-advanced-place-list>) displaying multiple places.",
"type": "object",
"allOf": [
{
"$ref": "common_types.json#/$defs/ComponentCommon"
},
{
"$ref": "#/$defs/CatalogComponentCommon"
},
{
"type": "object",
"properties": {
"component": {
"const": "AdvancedPlaceList"
},
"places": {
"$ref": "common_types.json#/$defs/DynamicStringList",
"description": "An array of place resource names or place IDs to display."
},
"orientation": {
"type": "string",
"enum": [
"horizontal",
"vertical"
],
"default": "vertical",
"description": "The orientation of the place list. Defaults to vertical."
},
"selectable": {
"$ref": "common_types.json#/$defs/DynamicBoolean",
"description": "Whether or not the list items are selectable buttons."
},
"truncationPreferred": {
"$ref": "common_types.json#/$defs/DynamicBoolean",
"description": "Whether or not text fields in list items are truncated."
}
},
"required": [
"component",
"places"
]
}
],
"unevaluatedProperties": false
}
},
"$defs": {
Expand Down
Loading
Loading