Extract shared helpers used by hassfest and Core scripts (#186958)

This commit is contained in:
Paulus Schoutsen
2026-10-17 13:48:20 +02:00
committed by GitHub
parent 63e9f9bf2e
commit aff03b66d7
17 changed files with 186 additions and 120 deletions
+1 -1
View File
@@ -79,7 +79,7 @@ repos:
pass_filenames: false
language: script
types: [text]
files: ^(homeassistant/.+/manifest\.json|homeassistant/brands/.+\.json|pyproject\.toml|\.pre-commit-config\.yaml|script/gen_requirements_all\.py)$
files: ^(homeassistant/.+/manifest\.json|homeassistant/brands/.+\.json|pyproject\.toml|\.pre-commit-config\.yaml|script/gen_requirements_all\.py|script/hassfest/requirements_util\.py)$
- id: gen_copilot_instructions
name: gen_copilot_instructions
entry: script/run-in-env.sh python3 -m script.gen_copilot_instructions
+4 -31
View File
@@ -6,7 +6,6 @@ import importlib
from operator import itemgetter
from pathlib import Path
import pkgutil
import re
import sys
import tomllib
from typing import Any
@@ -16,17 +15,10 @@ from packaging.utils import canonicalize_name
from homeassistant.util.yaml.loader import load_yaml
from script.hassfest.model import Config, Integration
# Requirements which can't be installed on all systems because they
# rely on additional system packages. Requirements listed in
# EXCLUDED_REQUIREMENTS_ALL will be commented-out in
# requirements_all.txt.
EXCLUDED_REQUIREMENTS_ALL = {
"atenpdu", # depends on pysnmp which is not maintained at this time
"beewi-smartclim", # depends on bluepy
"bluepy",
"evdev",
}
from script.hassfest.requirements_util import (
EXCLUDED_REQUIREMENTS_ALL,
normalize_package_name,
)
# Requirements excluded by EXCLUDED_REQUIREMENTS_ALL which should be included when
# building integration wheels for all architectures.
@@ -291,8 +283,6 @@ IGNORE_PRE_COMMIT_HOOK_ID = (
"ruff-format", # it's just ruff
)
PACKAGE_REGEX = re.compile(r"^(?:--.+\s)?([-_\.\w\d]+).*==.+$")
def explore_module(package: str, explore_children: bool) -> list[str]:
"""Explore the modules."""
@@ -337,23 +327,6 @@ def gather_recursive_requirements(
return reqs
def _normalize_package_name(package_name: str) -> str:
"""Normalize a package name."""
# pipdeptree needs lowercase and dash instead of underscore or period as separator
return package_name.lower().replace("_", "-").replace(".", "-")
def normalize_package_name(requirement: str) -> str:
"""Return a normalized package name from a requirement string."""
# This function is also used in hassfest.
match = PACKAGE_REGEX.search(requirement)
if not match:
return ""
# pipdeptree needs lowercase and dash instead of underscore or period as separator
return _normalize_package_name(match.group(1))
def comment_requirement(req: str) -> bool:
"""Comment out requirement. Some don't install on all systems."""
return normalize_package_name(req) in EXCLUDED_REQUIREMENTS_ALL
+1 -1
View File
@@ -18,9 +18,9 @@ from probatio.humanize import humanize_error
from homeassistant.const import Platform
from homeassistant.helpers import config_validation as cv
from homeassistant.loader import LORAWAN_SCHEMA
from script.util import sort_manifest as util_sort_manifest
from .icons import integration_category_keys
from .manifest_util import sort_manifest as util_sort_manifest
from .model import Config, Integration, IntegrationType, ScaledQualityScaleTiers
DOCUMENTATION_URL_SCHEMA = "https"
+22
View File
@@ -0,0 +1,22 @@
"""Shared manifest sorting helpers."""
from typing import Any
_MANIFEST_SORT_KEYS = {"domain": ".domain", "name": ".name"}
def _sort_manifest_keys(key: str) -> str:
"""Sort manifest keys."""
return _MANIFEST_SORT_KEYS.get(key, key)
def sort_manifest(manifest: dict[str, Any]) -> bool:
"""Sort manifest."""
keys = list(manifest)
if (keys_sorted := sorted(keys, key=_sort_manifest_keys)) != keys:
sorted_manifest = {key: manifest[key] for key in keys_sorted}
manifest.clear()
manifest.update(sorted_manifest)
return True
return False
+1 -4
View File
@@ -21,12 +21,9 @@ from packaging.version import InvalidVersion, Version
from tqdm import tqdm
import homeassistant.util.package as pkg_util
from script.gen_requirements_all import (
EXCLUDED_REQUIREMENTS_ALL,
normalize_package_name,
)
from .model import Config, Integration
from .requirements_util import EXCLUDED_REQUIREMENTS_ALL, normalize_package_name
PACKAGE_CHECK_VERSION_RANGE = {
"aiohttp": "SemVer",
+32
View File
@@ -0,0 +1,32 @@
"""Shared requirement policies and package-name normalization."""
import re
# Requirements which can't be installed on all systems because they
# rely on additional system packages. Requirements listed in
# EXCLUDED_REQUIREMENTS_ALL will be commented-out in
# requirements_all.txt.
EXCLUDED_REQUIREMENTS_ALL = {
"atenpdu", # depends on pysnmp which is not maintained at this time
"beewi-smartclim", # depends on bluepy
"bluepy",
"evdev",
}
PACKAGE_REGEX = re.compile(r"^(?:--.+\s)?([-_\.\w\d]+).*==.+$")
def _normalize_package_name(package_name: str) -> str:
"""Normalize a package name."""
# pipdeptree needs lowercase and dash instead of underscore or period as separator
return package_name.lower().replace("_", "-").replace(".", "-")
def normalize_package_name(requirement: str) -> str:
"""Return a normalized package name from a requirement string."""
match = PACKAGE_REGEX.search(requirement)
if not match:
return ""
# pipdeptree needs lowercase and dash instead of underscore or period as separator
return _normalize_package_name(match.group(1))
+49
View File
@@ -0,0 +1,49 @@
"""Shared translation data loading."""
import json
from pathlib import Path
from typing import Any
class JSONDecodeErrorWithPath(json.JSONDecodeError):
"""Subclass of JSONDecodeError with additional properties.
Additional properties:
path: Path to the JSON document being parsed
"""
def __init__(self, msg, doc, pos, path):
"""Initialize."""
lineno = doc.count("\n", 0, pos) + 1
colno = pos - doc.rfind("\n", 0, pos)
errmsg = f"{msg}: file: {path} line {lineno} column {colno} (char {pos})"
ValueError.__init__(self, errmsg)
self.msg = msg
self.doc = doc
self.pos = pos
self.lineno = lineno
self.colno = colno
self.path = path
def __reduce__(self):
"""Reduce."""
return self.__class__, (self.msg, self.doc, self.pos, self.path)
def load_json_from_path(path: Path) -> Any:
"""Load JSON from path."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as err:
raise JSONDecodeErrorWithPath(err.msg, err.doc, err.pos, path) from err
def generate_upload_data(core_path: Path) -> dict[str, Any]:
"""Collect Core and integration translation strings."""
integrations_dir = core_path / "homeassistant/components"
translations = load_json_from_path(integrations_dir.parent / "strings.json")
translations["component"] = {
path.parent.name: load_json_from_path(path)
for path in integrations_dir.glob("*/strings.json")
}
return translations
+2 -2
View File
@@ -13,9 +13,9 @@ from probatio.humanize import humanize_error
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.issue_registry import FRONTEND_HANDLED_ISSUES
from script.translations import upload
from .model import Config, Integration, IntegrationType
from .translation_data import generate_upload_data
UNDEFINED = 0
REQUIRED = 1
@@ -822,7 +822,7 @@ def validate(integrations: dict[str, Integration], config: Config) -> None:
if config.specific_integrations:
all_strings = None
else:
all_strings = upload.generate_upload_data() # type: ignore[no-untyped-call]
all_strings = generate_upload_data(config.root)
for integration in integrations.values():
validate_translation_file(config, integration, all_strings)
+1 -1
View File
@@ -6,7 +6,7 @@ from typing import Any
import attr
from script.util import sort_manifest
from script.hassfest.manifest_util import sort_manifest
from .const import COMPONENT_DIR, TESTS_DIR
+2 -2
View File
@@ -5,8 +5,8 @@ import json
from pathlib import Path
from homeassistant.const import Platform
from script.hassfest.translation_data import generate_upload_data
from . import upload
from .util import flatten_translations, get_base_arg_parser, load_json_from_path
@@ -29,7 +29,7 @@ ENTITY_COMPONENT_PREFIX = tuple(f"component::{domain}::" for domain in Platform)
def run():
"""Clean translations."""
args = get_arguments()
translations = upload.generate_upload_data()
translations = generate_upload_data(Path.cwd())
flattened_translations = flatten_translations(translations)
flattened_translations = {
key: value
+4 -2
View File
@@ -6,7 +6,9 @@ import sys
import orjson
from . import download, upload
from script.hassfest.translation_data import generate_upload_data
from . import download
from .const import INTEGRATIONS_DIR
from .util import flatten_translations, get_base_arg_parser, substitute_references
@@ -72,7 +74,7 @@ def run_single(translations, flattened_translations, integration):
def run():
"""Run the script."""
args = get_arguments()
translations = upload.generate_upload_data()
translations = generate_upload_data(Path.cwd())
flattened_translations = flatten_translations(translations)
if args.all:
+3 -26
View File
@@ -1,6 +1,8 @@
"""Errors for translations."""
import json
from script.hassfest.translation_data import (
JSONDecodeErrorWithPath as JSONDecodeErrorWithPath, # noqa: PLC0414
)
class ExitApp(Exception):
@@ -19,28 +21,3 @@ class MissingReference(Exception):
"""Initialize the missing reference exception."""
self.reference_key = reference_key
super().__init__(f"Missing reference key: {reference_key}")
class JSONDecodeErrorWithPath(json.JSONDecodeError):
"""Subclass of JSONDecodeError with additional properties.
Additional properties:
path: Path to the JSON document being parsed
"""
def __init__(self, msg, doc, pos, path):
"""Initialize."""
lineno = doc.count("\n", 0, pos) + 1
colno = pos - doc.rfind("\n", 0, pos)
errmsg = f"{msg}: file: {path} line {lineno} column {colno} (char {pos})"
ValueError.__init__(self, errmsg)
self.msg = msg
self.doc = doc
self.pos = pos
self.lineno = lineno
self.colno = colno
self.path = path
def __reduce__(self):
"""Reduce."""
return self.__class__, (self.msg, self.doc, self.pos, self.path)
+5 -15
View File
@@ -6,9 +6,11 @@ import os
import pathlib
import subprocess
from .const import CLI_2_DOCKER_IMAGE, CORE_PROJECT_ID, INTEGRATIONS_DIR
from script.hassfest.translation_data import generate_upload_data
from .const import CLI_2_DOCKER_IMAGE, CORE_PROJECT_ID
from .error import ExitApp
from .util import get_current_branch, get_lokalise_token, load_json_from_path
from .util import get_current_branch, get_lokalise_token
LOCAL_FILE = pathlib.Path("build/translations-upload.json").absolute()
CONTAINER_FILE = "/opt/src/build/translations-upload.json"
@@ -49,18 +51,6 @@ def run_upload_docker():
raise ExitApp("Failed to download translations")
def generate_upload_data():
"""Generate the data for uploading."""
translations = load_json_from_path(INTEGRATIONS_DIR.parent / "strings.json")
translations["component"] = {
path.parent.name: load_json_from_path(path)
for path in INTEGRATIONS_DIR.glob(f"*{os.sep}strings.json")
}
return translations
def run():
"""Run the script."""
if get_current_branch() != "dev" and os.environ.get("AZURE_BRANCH") != "dev":
@@ -69,7 +59,7 @@ def run():
" script from a clean checkout of dev."
)
translations = generate_upload_data()
translations = generate_upload_data(pathlib.Path.cwd())
LOCAL_FILE.parent.mkdir(parents=True, exist_ok=True)
LOCAL_FILE.write_text(json.dumps(translations, indent=4, sort_keys=True))
+5 -10
View File
@@ -1,14 +1,17 @@
"""Translation utils."""
import argparse
import json
import os
import pathlib
import re
import subprocess
from typing import Any
from .error import ExitApp, JSONDecodeErrorWithPath, MissingReference
from script.hassfest.translation_data import (
load_json_from_path as load_json_from_path, # noqa: PLC0414
)
from .error import ExitApp, MissingReference
def get_base_arg_parser() -> argparse.ArgumentParser:
@@ -61,14 +64,6 @@ def get_current_branch():
)
def load_json_from_path(path: pathlib.Path) -> Any:
"""Load JSON from path."""
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as err:
raise JSONDecodeErrorWithPath(err.msg, err.doc, err.pos, path) from err
def flatten_translations(translations):
"""Flatten all translations."""
stack = [iter(translations.items())]
-21
View File
@@ -1,7 +1,6 @@
"""Utility functions for the scaffold script."""
import argparse
from typing import Any
from .const import COMPONENT_DIR
@@ -14,23 +13,3 @@ def valid_integration(integration):
)
return integration
_MANIFEST_SORT_KEYS = {"domain": ".domain", "name": ".name"}
def _sort_manifest_keys(key: str) -> str:
"""Sort manifest keys."""
return _MANIFEST_SORT_KEYS.get(key, key)
def sort_manifest(manifest: dict[str, Any]) -> bool:
"""Sort manifest."""
keys = list(manifest)
if (keys_sorted := sorted(keys, key=_sort_manifest_keys)) != keys:
sorted_manifest = {key: manifest[key] for key in keys_sorted}
manifest.clear()
manifest.update(sorted_manifest)
return True
return False
+49
View File
@@ -1,6 +1,7 @@
"""Tests for hassfest translations."""
from dataclasses import replace
import json
from pathlib import Path
import probatio
@@ -12,6 +13,54 @@ from script.hassfest.model import Config
from . import get_integration
@pytest.mark.parametrize(
("reference", "expected_errors"),
[
("common::test", []),
(
"common::missing",
[
"strings.json::config::error::cannot_connect contains invalid reference"
"common::missing: Could not find missing"
],
),
],
)
def test_validate_uses_core_path(
config: Config,
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
reference: str,
expected_errors: list[str],
) -> None:
"""Resolve translation references from the configured Core path, not the cwd."""
core_path = tmp_path / "core"
integration_path = core_path / "homeassistant/components/test_integration"
integration_path.mkdir(parents=True)
(core_path / "homeassistant/strings.json").write_text(
json.dumps({"common": {"test": "Test"}})
)
(integration_path / "strings.json").write_text(
json.dumps(
{
"config": {
"step": {"user": {"title": "Test"}},
"error": {"cannot_connect": f"[%key:{reference}%]"},
}
}
)
)
config = replace(config, root=core_path)
integration = replace(
get_integration("test_integration", config), path=integration_path
)
monkeypatch.chdir(tmp_path)
translations.validate({integration.domain: integration}, config)
assert [error.error for error in integration.errors] == expected_errors
def test_string_with_no_placeholders_in_single_quotes() -> None:
"""Test string with no placeholders in single quotes."""
schema = probatio.Schema(translations.string_no_single_quoted_placeholders)
+5 -4
View File
@@ -5,19 +5,20 @@ from unittest.mock import patch
import pytest
from script import gen_requirements_all
from script.hassfest.requirements_util import _normalize_package_name
def test_overrides_normalized() -> None:
"""Test override lists are using normalized package names."""
for req in gen_requirements_all.EXCLUDED_REQUIREMENTS_ALL:
assert req == gen_requirements_all._normalize_package_name(req)
assert req == _normalize_package_name(req)
for req in gen_requirements_all.INCLUDED_REQUIREMENTS_WHEELS:
assert req == gen_requirements_all._normalize_package_name(req)
assert req == _normalize_package_name(req)
for overrides in gen_requirements_all.OVERRIDDEN_REQUIREMENTS_ACTIONS.values():
for req in overrides["exclude"]:
assert req == gen_requirements_all._normalize_package_name(req)
assert req == _normalize_package_name(req)
for req in overrides["include"]:
assert req == gen_requirements_all._normalize_package_name(req)
assert req == _normalize_package_name(req)
def test_include_overrides_subsets() -> None: