forked from home-assistant/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditions.py
More file actions
312 lines (271 loc) · 11.9 KB
/
Copy pathconditions.py
File metadata and controls
312 lines (271 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
"""Validate conditions."""
import contextlib
import json
import pathlib
import re
from typing import Any
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.const import CONF_SELECTOR
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import condition, config_validation as cv, selector
from homeassistant.util.yaml import load_yaml_dict
from .model import Config, Integration
def exists(value: Any) -> Any:
"""Check if value exists."""
if value is None:
raise vol.Invalid("Value cannot be None")
return value
def validate_field_schema(condition_schema: dict[str, Any]) -> dict[str, Any]:
"""Validate a field schema including context references."""
for field_name, field_schema in condition_schema.get("fields", {}).items():
# Validate context if present
if "context" in field_schema:
if CONF_SELECTOR not in field_schema:
raise vol.Invalid(
f"Context defined without a selector in '{field_name}'"
)
context = field_schema["context"]
if not isinstance(context, dict):
raise vol.Invalid(f"Context must be a dictionary in '{field_name}'")
# Determine which selector type is being used
selector_config = field_schema[CONF_SELECTOR]
selector_class = selector.selector(selector_config)
for context_key, field_ref in context.items():
# Check if context key is allowed for this selector type
allowed_keys = selector_class.allowed_context_keys
if context_key not in allowed_keys:
allowed = (
", ".join(sorted(allowed_keys)) if allowed_keys else "none"
)
raise vol.Invalid(
f"Invalid context key '{context_key}'"
f" for selector type"
f" '{selector_class.selector_type}'."
f" Allowed keys: {allowed}"
)
# Check if the referenced field exists in condition schema or target
if not isinstance(field_ref, str):
raise vol.Invalid(
f"Context value for '{context_key}'"
" must be a string field reference"
)
# Check if field exists in condition schema fields or target
condition_fields = condition_schema["fields"]
field_exists = field_ref in condition_fields
if field_exists and "selector" in condition_fields[field_ref]:
# Check if the selector type is allowed for this context key
field_selector_config = condition_fields[field_ref][CONF_SELECTOR]
field_selector_class = selector.selector(field_selector_config)
if field_selector_class.selector_type not in allowed_keys.get(
context_key, set()
):
allowed_types = ", ".join(allowed_keys.get(context_key, set()))
sel_type = field_selector_class.selector_type
raise vol.Invalid(
f"The context '{context_key}' for"
f" '{field_name}' references"
f" '{field_ref}', but"
f" '{context_key}' does not allow"
f" selectors of type '{sel_type}'."
f" Allowed types: {allowed_types}"
)
if not field_exists and "target" in condition_schema:
# Target is a special field that always exists when defined
field_exists = field_ref == "target"
if field_exists and "target" not in allowed_keys.get(
context_key, set()
):
allowed_types = ", ".join(allowed_keys.get(context_key, set()))
raise vol.Invalid(
f"The context '{context_key}' for"
f" '{field_name}' references"
f" 'target', but '{context_key}'"
" does not allow 'target'."
f" Allowed types: {allowed_types}"
)
if not field_exists:
raise vol.Invalid(
f"Context reference '{field_ref}'"
f" for key '{context_key}' does"
" not exist in condition schema"
" fields or target"
)
return condition_schema
FIELD_SCHEMA = vol.Schema(
{
vol.Optional("example"): exists,
vol.Optional("default"): exists,
vol.Optional("required"): bool,
vol.Optional(CONF_SELECTOR): selector.validate_selector,
# key is context key, value is field name in schema
# Validated in validate_field_schema
vol.Optional("context"): {str: str},
}
)
CONDITION_SCHEMA = vol.Any(
vol.All(
vol.Schema(
{
vol.Optional("target"): selector.TargetSelector.CONFIG_SCHEMA,
vol.Optional("fields"): vol.Schema({str: FIELD_SCHEMA}),
}
),
validate_field_schema,
),
None,
)
CONDITIONS_SCHEMA = vol.Schema(
{
vol.Remove(vol.All(str, condition.starts_with_dot)): object,
cv.underscore_slug: CONDITION_SCHEMA,
}
)
NON_MIGRATED_INTEGRATIONS = {
"device_automation",
"sun",
"zone",
}
def grep_dir(path: pathlib.Path, glob_pattern: str, search_pattern: str) -> bool:
"""Recursively go through a dir and it's children and find the regex."""
pattern = re.compile(search_pattern)
for fil in path.glob(glob_pattern):
if not fil.is_file():
continue
if pattern.search(fil.read_text()):
return True
return False
def validate_conditions(config: Config, integration: Integration) -> None: # noqa: C901
"""Validate conditions."""
try:
data = load_yaml_dict(str(integration.path / "conditions.yaml"))
except FileNotFoundError:
# Find if integration uses conditions
has_conditions = grep_dir(
integration.path,
"**/condition.py",
r"async_get_conditions",
)
if has_conditions and integration.domain not in NON_MIGRATED_INTEGRATIONS:
integration.add_error(
"conditions", "Registers conditions but has no conditions.yaml"
)
return
except HomeAssistantError:
integration.add_error("conditions", "Invalid conditions.yaml")
return
try:
conditions = CONDITIONS_SCHEMA(data)
except vol.Invalid as err:
integration.add_error(
"conditions", f"Invalid conditions.yaml: {humanize_error(data, err)}"
)
return
icons_file = integration.path / "icons.json"
icons = {}
if icons_file.is_file():
with contextlib.suppress(ValueError):
icons = json.loads(icons_file.read_text())
condition_icons = icons.get("conditions", {})
# Try loading translation strings
if integration.core:
strings_file = integration.path / "strings.json"
else:
# For custom integrations, use the en.json file
strings_file = integration.path / "translations/en.json"
strings = {}
if strings_file.is_file():
with contextlib.suppress(ValueError):
strings = json.loads(strings_file.read_text())
error_msg_suffix = "in the translations file"
if not integration.core:
error_msg_suffix = f"and is not {error_msg_suffix}"
# For each condition in the integration:
# 1. Check if the condition description is set, if not,
# check if it's in the strings file else add an error.
# 2. Check if the condition has an icon set in icons.json.
# raise an error if not.,
for condition_name, condition_schema in conditions.items():
if integration.core and condition_name not in condition_icons:
# This is enforced for Core integrations only
integration.add_error(
"conditions",
f"Condition {condition_name} has no icon in icons.json.",
)
if condition_schema is None:
continue
if "name" not in condition_schema and integration.core:
try:
strings["conditions"][condition_name]["name"]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has no name {error_msg_suffix}",
)
if "description" not in condition_schema and integration.core:
try:
strings["conditions"][condition_name]["description"]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has no description {error_msg_suffix}",
)
# The same check is done for each of the fields of the condition schema,
# except that we don't enforce that fields have a description.
for field_name, field_schema in condition_schema.get("fields", {}).items():
if "fields" in field_schema:
# This is a section
continue
if "name" not in field_schema and integration.core:
try:
strings["conditions"][condition_name]["fields"][field_name]["name"]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has a"
f" field {field_name} with no"
f" name {error_msg_suffix}",
)
if "selector" in field_schema:
with contextlib.suppress(KeyError):
translation_key = field_schema["selector"]["select"][
"translation_key"
]
try:
strings["selector"][translation_key]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name}"
f" has a field"
f" {field_name} with a"
" selector with a"
" translation key"
f" {translation_key}"
" that is not in the"
" translations file",
)
# The same check is done for the description in each of the sections of the
# condition schema.
for section_name, section_schema in condition_schema.get("fields", {}).items():
if "fields" not in section_schema:
# This is not a section
continue
if "name" not in section_schema and integration.core:
try:
strings["conditions"][condition_name]["sections"][section_name][
"name"
]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name}"
f" has a section"
f" {section_name} with no"
f" name {error_msg_suffix}",
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle dependencies for integrations."""
# check conditions.yaml is valid
for integration in integrations.values():
validate_conditions(config, integration)