scim2-models 0.5.2__py3-none-any.whl → 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scim2_models/__init__.py +32 -0
- scim2_models/attributes.py +5 -1
- scim2_models/base.py +52 -8
- scim2_models/exceptions.py +265 -0
- scim2_models/messages/bulk.py +3 -7
- scim2_models/messages/error.py +184 -15
- scim2_models/messages/list_response.py +2 -5
- scim2_models/messages/message.py +4 -4
- scim2_models/messages/patch_op.py +127 -261
- scim2_models/messages/search_request.py +9 -57
- scim2_models/path.py +733 -0
- scim2_models/reference.py +139 -48
- scim2_models/resources/enterprise_user.py +10 -8
- scim2_models/resources/group.py +9 -7
- scim2_models/resources/resource.py +116 -29
- scim2_models/resources/resource_type.py +15 -14
- scim2_models/resources/schema.py +15 -20
- scim2_models/resources/service_provider_config.py +10 -13
- scim2_models/resources/user.py +13 -10
- scim2_models/scim_object.py +84 -1
- scim2_models/utils.py +0 -140
- {scim2_models-0.5.2.dist-info → scim2_models-0.6.1.dist-info}/METADATA +2 -2
- scim2_models-0.6.1.dist-info/RECORD +30 -0
- scim2_models/urn.py +0 -126
- scim2_models-0.5.2.dist-info/RECORD +0 -29
- {scim2_models-0.5.2.dist-info → scim2_models-0.6.1.dist-info}/WHEEL +0 -0
scim2_models/path.py
ADDED
|
@@ -0,0 +1,733 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import UserString
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from inspect import isclass
|
|
5
|
+
from typing import TYPE_CHECKING
|
|
6
|
+
from typing import Any
|
|
7
|
+
from typing import Generic
|
|
8
|
+
from typing import NamedTuple
|
|
9
|
+
from typing import TypeVar
|
|
10
|
+
|
|
11
|
+
from pydantic import GetCoreSchemaHandler
|
|
12
|
+
from pydantic_core import core_schema
|
|
13
|
+
|
|
14
|
+
from .base import BaseModel
|
|
15
|
+
from .utils import _find_field_name
|
|
16
|
+
from .utils import _to_camel
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from .annotations import Mutability
|
|
20
|
+
from .annotations import Required
|
|
21
|
+
from .resources.resource import Resource
|
|
22
|
+
|
|
23
|
+
from .exceptions import InvalidPathException
|
|
24
|
+
from .exceptions import PathNotFoundException
|
|
25
|
+
|
|
26
|
+
ResourceT = TypeVar("ResourceT", bound="Resource[Any]")
|
|
27
|
+
|
|
28
|
+
_VALID_PATH_PATTERN = re.compile(r'^[a-zA-Z][a-zA-Z0-9._:\-\[\]"=\s]*$')
|
|
29
|
+
_PATH_CACHE: dict[tuple[type, type], type] = {}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _to_comparable(value: Any) -> Any:
|
|
33
|
+
"""Convert a value to a comparable form (dict for BaseModel)."""
|
|
34
|
+
return value.model_dump() if isinstance(value, BaseModel) else value
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _values_match(value1: Any, value2: Any) -> bool:
|
|
38
|
+
"""Check if two values match, handling BaseModel comparison."""
|
|
39
|
+
return bool(_to_comparable(value1) == _to_comparable(value2))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _value_in_list(current_list: list[Any], new_value: Any) -> bool:
|
|
43
|
+
"""Check if a value exists in a list, handling BaseModel comparison."""
|
|
44
|
+
return any(_values_match(item, new_value) for item in current_list)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _require_field(model: type[BaseModel], name: str) -> str:
|
|
48
|
+
"""Find field name or raise PathNotFoundException."""
|
|
49
|
+
if (field_name := _find_field_name(model, name)) is None:
|
|
50
|
+
raise PathNotFoundException(path=name, field=name)
|
|
51
|
+
return field_name
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class _Resolution(NamedTuple):
|
|
55
|
+
"""Result of instance path resolution."""
|
|
56
|
+
|
|
57
|
+
target: "BaseModel"
|
|
58
|
+
path_str: str
|
|
59
|
+
is_explicit_schema_path: bool = False
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class URN(str):
|
|
63
|
+
"""URN string type with validation."""
|
|
64
|
+
|
|
65
|
+
def __new__(cls, urn: str) -> "URN":
|
|
66
|
+
cls.check_syntax(urn)
|
|
67
|
+
return super().__new__(cls, urn)
|
|
68
|
+
|
|
69
|
+
@classmethod
|
|
70
|
+
def __get_pydantic_core_schema__(
|
|
71
|
+
cls,
|
|
72
|
+
_source: type[Any],
|
|
73
|
+
_handler: GetCoreSchemaHandler,
|
|
74
|
+
) -> core_schema.CoreSchema:
|
|
75
|
+
return core_schema.no_info_after_validator_function(
|
|
76
|
+
cls,
|
|
77
|
+
core_schema.str_schema(),
|
|
78
|
+
serialization=core_schema.plain_serializer_function_ser_schema(
|
|
79
|
+
str,
|
|
80
|
+
),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def check_syntax(cls, path: str) -> None:
|
|
85
|
+
"""Validate URN-based path format.
|
|
86
|
+
|
|
87
|
+
:param path: The URN path to validate
|
|
88
|
+
:raises ValueError: If the URN format is invalid
|
|
89
|
+
"""
|
|
90
|
+
if not path.startswith("urn:"):
|
|
91
|
+
raise ValueError("The URN does not start with urn:")
|
|
92
|
+
|
|
93
|
+
urn_segments = path.split(":")
|
|
94
|
+
if len(urn_segments) < 3:
|
|
95
|
+
raise ValueError("URNs must have at least 3 parts")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Path(UserString, Generic[ResourceT]):
|
|
99
|
+
__scim_model__: type[BaseModel] | None = None
|
|
100
|
+
|
|
101
|
+
def __class_getitem__(cls, model: type[ResourceT]) -> type["Path[ResourceT]"]:
|
|
102
|
+
"""Create a Path class bound to a specific model type."""
|
|
103
|
+
if not isclass(model) or not hasattr(model, "model_fields"):
|
|
104
|
+
return super().__class_getitem__(model) # type: ignore[misc,no-any-return]
|
|
105
|
+
|
|
106
|
+
cache_key = (cls, model)
|
|
107
|
+
if cache_key in _PATH_CACHE:
|
|
108
|
+
return _PATH_CACHE[cache_key]
|
|
109
|
+
|
|
110
|
+
new_class = type(f"Path[{model.__name__}]", (cls,), {"__scim_model__": model})
|
|
111
|
+
_PATH_CACHE[cache_key] = new_class
|
|
112
|
+
return new_class
|
|
113
|
+
|
|
114
|
+
@classmethod
|
|
115
|
+
def __get_pydantic_core_schema__(
|
|
116
|
+
cls,
|
|
117
|
+
_source_type: type[Any],
|
|
118
|
+
_handler: GetCoreSchemaHandler,
|
|
119
|
+
) -> core_schema.CoreSchema:
|
|
120
|
+
def validate_path(value: Any) -> "Path[Any]":
|
|
121
|
+
if isinstance(value, Path):
|
|
122
|
+
return cls(str(value))
|
|
123
|
+
if isinstance(value, str):
|
|
124
|
+
return cls(value)
|
|
125
|
+
raise ValueError(f"Expected str or Path, got {type(value).__name__}")
|
|
126
|
+
|
|
127
|
+
return core_schema.no_info_plain_validator_function(
|
|
128
|
+
validate_path,
|
|
129
|
+
serialization=core_schema.plain_serializer_function_ser_schema(str),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def __init__(self, path: "str | Path[Any]"):
|
|
133
|
+
if isinstance(path, Path):
|
|
134
|
+
path = str(path)
|
|
135
|
+
self.check_syntax(path)
|
|
136
|
+
self.data = path
|
|
137
|
+
|
|
138
|
+
@classmethod
|
|
139
|
+
def check_syntax(cls, path: str) -> None:
|
|
140
|
+
"""Check if path syntax is valid according to RFC 7644 simplified rules.
|
|
141
|
+
|
|
142
|
+
An empty string is valid and represents the resource root.
|
|
143
|
+
|
|
144
|
+
:param path: The path to validate
|
|
145
|
+
:raises ValueError: If the path syntax is invalid
|
|
146
|
+
"""
|
|
147
|
+
if not path:
|
|
148
|
+
return
|
|
149
|
+
|
|
150
|
+
if path[0].isdigit():
|
|
151
|
+
raise ValueError("Paths cannot start with a digit")
|
|
152
|
+
|
|
153
|
+
if ".." in path:
|
|
154
|
+
raise ValueError("Paths cannot contain double dots")
|
|
155
|
+
|
|
156
|
+
if not _VALID_PATH_PATTERN.match(path):
|
|
157
|
+
raise ValueError("The path contains invalid characters")
|
|
158
|
+
|
|
159
|
+
if path.endswith(":"):
|
|
160
|
+
raise ValueError("Paths cannot end with a colon")
|
|
161
|
+
|
|
162
|
+
if ":" in path:
|
|
163
|
+
urn = path.rsplit(":", 1)[0]
|
|
164
|
+
try:
|
|
165
|
+
URN(urn.lower())
|
|
166
|
+
except ValueError as exc:
|
|
167
|
+
raise ValueError(f"The path is not a valid URN: {exc}") from exc
|
|
168
|
+
|
|
169
|
+
@property
|
|
170
|
+
def schema(self) -> str | None:
|
|
171
|
+
"""The schema URN portion of the path.
|
|
172
|
+
|
|
173
|
+
For paths like "urn:...:User:userName", returns "urn:...:User".
|
|
174
|
+
For simple paths like "userName", returns None.
|
|
175
|
+
"""
|
|
176
|
+
if ":" not in self.data:
|
|
177
|
+
return None
|
|
178
|
+
return self.data.rsplit(":", 1)[0]
|
|
179
|
+
|
|
180
|
+
@property
|
|
181
|
+
def attr(self) -> str:
|
|
182
|
+
"""The attribute portion of the path.
|
|
183
|
+
|
|
184
|
+
For paths like "urn:...:User:userName", returns "userName".
|
|
185
|
+
For simple paths like "userName", returns "userName".
|
|
186
|
+
For schema-only paths like "urn:...:User", returns "".
|
|
187
|
+
"""
|
|
188
|
+
if ":" not in self.data:
|
|
189
|
+
return self.data
|
|
190
|
+
return self.data.rsplit(":", 1)[1]
|
|
191
|
+
|
|
192
|
+
@property
|
|
193
|
+
def parts(self) -> tuple[str, ...]:
|
|
194
|
+
"""The attribute path segments split by '.'.
|
|
195
|
+
|
|
196
|
+
For "name.familyName", returns ("name", "familyName").
|
|
197
|
+
For "userName", returns ("userName",).
|
|
198
|
+
For "", returns ().
|
|
199
|
+
"""
|
|
200
|
+
attr = self.attr
|
|
201
|
+
if not attr:
|
|
202
|
+
return ()
|
|
203
|
+
return tuple(attr.split("."))
|
|
204
|
+
|
|
205
|
+
def is_prefix_of(self, other: "str | Path[Any]") -> bool:
|
|
206
|
+
"""Check if this path is a prefix of another path.
|
|
207
|
+
|
|
208
|
+
A path is a prefix if the other path starts with this path
|
|
209
|
+
followed by a separator ("." or ":").
|
|
210
|
+
|
|
211
|
+
Examples::
|
|
212
|
+
|
|
213
|
+
Path("emails").is_prefix_of("emails.value") # True
|
|
214
|
+
Path("emails").is_prefix_of("emails") # False (equal, not prefix)
|
|
215
|
+
Path("urn:...:User").is_prefix_of("urn:...:User:name") # True
|
|
216
|
+
"""
|
|
217
|
+
other_str = str(other).lower()
|
|
218
|
+
self_str = self.data.lower()
|
|
219
|
+
|
|
220
|
+
if self_str == other_str:
|
|
221
|
+
return False
|
|
222
|
+
|
|
223
|
+
return other_str.startswith(f"{self_str}.") or other_str.startswith(
|
|
224
|
+
f"{self_str}:"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
def has_prefix(self, prefix: "str | Path[Any]") -> bool:
|
|
228
|
+
"""Check if this path has the given prefix.
|
|
229
|
+
|
|
230
|
+
Examples::
|
|
231
|
+
|
|
232
|
+
Path("emails.value").has_prefix("emails") # True
|
|
233
|
+
Path("emails").has_prefix("emails") # False (equal, not prefix)
|
|
234
|
+
Path("urn:...:User:name").has_prefix("urn:...:User") # True
|
|
235
|
+
"""
|
|
236
|
+
prefix_path = prefix if isinstance(prefix, Path) else Path(str(prefix))
|
|
237
|
+
return prefix_path.is_prefix_of(self)
|
|
238
|
+
|
|
239
|
+
@property
|
|
240
|
+
def model(self) -> type[BaseModel] | None:
|
|
241
|
+
"""The target model type for this path.
|
|
242
|
+
|
|
243
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
244
|
+
Returns None if the path is unbound or invalid.
|
|
245
|
+
|
|
246
|
+
For "name.familyName" on Path[User], returns Name.
|
|
247
|
+
For "userName" on Path[User], returns User.
|
|
248
|
+
"""
|
|
249
|
+
if (result := self._resolve_model()) is None:
|
|
250
|
+
return None
|
|
251
|
+
return result[0]
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def field_name(self) -> str | None:
|
|
255
|
+
"""The Python attribute name (snake_case) for this path.
|
|
256
|
+
|
|
257
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
258
|
+
Returns None if the path is unbound or invalid.
|
|
259
|
+
|
|
260
|
+
For "name.familyName" on Path[User], returns "family_name".
|
|
261
|
+
For "userName" on Path[User], returns "user_name".
|
|
262
|
+
"""
|
|
263
|
+
if (result := self._resolve_model()) is None:
|
|
264
|
+
return None
|
|
265
|
+
return result[1]
|
|
266
|
+
|
|
267
|
+
@property
|
|
268
|
+
def field_type(self) -> type | None:
|
|
269
|
+
"""The Python type of the field this path points to.
|
|
270
|
+
|
|
271
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
272
|
+
Returns None if the path is unbound, invalid, or points to a schema-only path.
|
|
273
|
+
|
|
274
|
+
For "userName" on Path[User], returns str.
|
|
275
|
+
For "name" on Path[User], returns Name.
|
|
276
|
+
For "emails" on Path[User], returns Email.
|
|
277
|
+
"""
|
|
278
|
+
if self.model is None or self.field_name is None:
|
|
279
|
+
return None
|
|
280
|
+
return self.model.get_field_root_type(self.field_name)
|
|
281
|
+
|
|
282
|
+
@property
|
|
283
|
+
def is_multivalued(self) -> bool | None:
|
|
284
|
+
"""Whether this path points to a multi-valued attribute.
|
|
285
|
+
|
|
286
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
287
|
+
Returns None if the path is unbound, invalid, or points to a schema-only path.
|
|
288
|
+
|
|
289
|
+
For "emails" on Path[User], returns True.
|
|
290
|
+
For "userName" on Path[User], returns False.
|
|
291
|
+
"""
|
|
292
|
+
if self.model is None or self.field_name is None:
|
|
293
|
+
return None
|
|
294
|
+
return self.model.get_field_multiplicity(self.field_name)
|
|
295
|
+
|
|
296
|
+
def get_annotation(self, annotation_type: type) -> Any:
|
|
297
|
+
"""Get annotation value for this path's field.
|
|
298
|
+
|
|
299
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
300
|
+
Returns None if the path is unbound, invalid, or points to a schema-only path.
|
|
301
|
+
|
|
302
|
+
:param annotation_type: The annotation class (e.g., Required, Mutability).
|
|
303
|
+
:returns: The annotation value or None.
|
|
304
|
+
|
|
305
|
+
For "userName" on Path[User] with Required, returns Required.true.
|
|
306
|
+
"""
|
|
307
|
+
if self.model is None or self.field_name is None:
|
|
308
|
+
return None
|
|
309
|
+
return self.model.get_field_annotation(self.field_name, annotation_type)
|
|
310
|
+
|
|
311
|
+
@property
|
|
312
|
+
def urn(self) -> str | None:
|
|
313
|
+
"""The fully qualified URN for this path.
|
|
314
|
+
|
|
315
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
316
|
+
Returns None if the path is unbound or invalid.
|
|
317
|
+
|
|
318
|
+
For "userName" on Path[User], returns
|
|
319
|
+
"urn:ietf:params:scim:schemas:core:2.0:User:userName".
|
|
320
|
+
"""
|
|
321
|
+
from .resources.resource import Resource
|
|
322
|
+
|
|
323
|
+
if self.__scim_model__ is None or self.model is None:
|
|
324
|
+
return None
|
|
325
|
+
|
|
326
|
+
schema = self.schema
|
|
327
|
+
if not schema and issubclass(self.__scim_model__, Resource):
|
|
328
|
+
schema = self.__scim_model__.__schema__
|
|
329
|
+
|
|
330
|
+
if not self.attr:
|
|
331
|
+
return schema if schema else None
|
|
332
|
+
return f"{schema}:{self.attr}" if schema else self.attr
|
|
333
|
+
|
|
334
|
+
def _resolve_model(self) -> tuple[type[BaseModel], str | None] | None:
|
|
335
|
+
"""Resolve the path against the bound model type."""
|
|
336
|
+
from .resources.resource import Extension
|
|
337
|
+
from .resources.resource import Resource
|
|
338
|
+
|
|
339
|
+
model = self.__scim_model__
|
|
340
|
+
if model is None:
|
|
341
|
+
return None
|
|
342
|
+
|
|
343
|
+
attr_path = self.attr
|
|
344
|
+
|
|
345
|
+
if ":" in self and isclass(model) and issubclass(model, Resource | Extension):
|
|
346
|
+
path_lower = str(self).lower()
|
|
347
|
+
|
|
348
|
+
if model.__schema__ and path_lower == model.__schema__.lower():
|
|
349
|
+
return model, None
|
|
350
|
+
elif model.__schema__ and path_lower.startswith(model.__schema__.lower()):
|
|
351
|
+
attr_path = str(self)[len(model.__schema__) :].lstrip(":")
|
|
352
|
+
elif issubclass(model, Resource):
|
|
353
|
+
for (
|
|
354
|
+
extension_schema,
|
|
355
|
+
extension_model,
|
|
356
|
+
) in model.get_extension_models().items():
|
|
357
|
+
schema_lower = extension_schema.lower()
|
|
358
|
+
if path_lower == schema_lower:
|
|
359
|
+
return extension_model, None
|
|
360
|
+
elif path_lower.startswith(schema_lower):
|
|
361
|
+
model = extension_model
|
|
362
|
+
break
|
|
363
|
+
else:
|
|
364
|
+
return None
|
|
365
|
+
|
|
366
|
+
if not attr_path:
|
|
367
|
+
return model, None
|
|
368
|
+
|
|
369
|
+
if "." in attr_path:
|
|
370
|
+
parts = attr_path.split(".")
|
|
371
|
+
current_model = model
|
|
372
|
+
|
|
373
|
+
for part in parts[:-1]:
|
|
374
|
+
if (field_name := _find_field_name(current_model, part)) is None:
|
|
375
|
+
return None
|
|
376
|
+
field_type = current_model.get_field_root_type(field_name)
|
|
377
|
+
if (
|
|
378
|
+
field_type is None
|
|
379
|
+
or not isclass(field_type)
|
|
380
|
+
or not issubclass(field_type, BaseModel)
|
|
381
|
+
):
|
|
382
|
+
return None
|
|
383
|
+
current_model = field_type
|
|
384
|
+
|
|
385
|
+
if (field_name := _find_field_name(current_model, parts[-1])) is None:
|
|
386
|
+
return None
|
|
387
|
+
return current_model, field_name
|
|
388
|
+
|
|
389
|
+
if (field_name := _find_field_name(model, attr_path)) is None:
|
|
390
|
+
return None
|
|
391
|
+
return model, field_name
|
|
392
|
+
|
|
393
|
+
def _resolve_instance(
|
|
394
|
+
self, resource: BaseModel, *, create: bool = False
|
|
395
|
+
) -> _Resolution | None:
|
|
396
|
+
"""Resolve the target object and remaining path.
|
|
397
|
+
|
|
398
|
+
:param resource: The resource to resolve against.
|
|
399
|
+
:param create: If True, create extension instance if it doesn't exist.
|
|
400
|
+
:returns: Resolution with target object and path, or None if target doesn't exist.
|
|
401
|
+
:raises InvalidPathException: If the path references an unknown extension.
|
|
402
|
+
"""
|
|
403
|
+
from .resources.resource import Extension
|
|
404
|
+
from .resources.resource import Resource
|
|
405
|
+
|
|
406
|
+
path_str = str(self)
|
|
407
|
+
|
|
408
|
+
if ":" not in path_str:
|
|
409
|
+
return _Resolution(resource, path_str)
|
|
410
|
+
|
|
411
|
+
model_schema = getattr(type(resource), "__schema__", "") or ""
|
|
412
|
+
path_lower = path_str.lower()
|
|
413
|
+
|
|
414
|
+
if isinstance(resource, Resource | Extension) and path_lower.startswith(
|
|
415
|
+
model_schema.lower()
|
|
416
|
+
):
|
|
417
|
+
is_explicit = path_lower == model_schema.lower()
|
|
418
|
+
normalized = path_str[len(model_schema) :].lstrip(":")
|
|
419
|
+
return _Resolution(resource, normalized, is_explicit)
|
|
420
|
+
|
|
421
|
+
if isinstance(resource, Resource):
|
|
422
|
+
for ext_schema, ext_model in resource.get_extension_models().items():
|
|
423
|
+
ext_schema_lower = ext_schema.lower()
|
|
424
|
+
if path_lower == ext_schema_lower:
|
|
425
|
+
return _Resolution(resource, ext_model.__name__)
|
|
426
|
+
if path_lower.startswith(ext_schema_lower):
|
|
427
|
+
sub_path = path_str[len(ext_schema) :].lstrip(":")
|
|
428
|
+
ext_obj = getattr(resource, ext_model.__name__)
|
|
429
|
+
if create and ext_obj is None:
|
|
430
|
+
ext_obj = ext_model()
|
|
431
|
+
setattr(resource, ext_model.__name__, ext_obj)
|
|
432
|
+
if ext_obj is None:
|
|
433
|
+
return None
|
|
434
|
+
return _Resolution(ext_obj, sub_path)
|
|
435
|
+
|
|
436
|
+
raise InvalidPathException(path=str(self))
|
|
437
|
+
|
|
438
|
+
return None
|
|
439
|
+
|
|
440
|
+
def _walk_to_target(
|
|
441
|
+
self, obj: BaseModel, path_str: str
|
|
442
|
+
) -> tuple[BaseModel, str] | None:
|
|
443
|
+
"""Navigate to the target object and field.
|
|
444
|
+
|
|
445
|
+
:returns: (target_obj, field_name) or None if an intermediate is None.
|
|
446
|
+
"""
|
|
447
|
+
if "." not in path_str:
|
|
448
|
+
return obj, _require_field(type(obj), path_str)
|
|
449
|
+
|
|
450
|
+
parts = path_str.split(".")
|
|
451
|
+
current_obj = obj
|
|
452
|
+
|
|
453
|
+
for part in parts[:-1]:
|
|
454
|
+
field_name = _require_field(type(current_obj), part)
|
|
455
|
+
if (current_obj := getattr(current_obj, field_name)) is None:
|
|
456
|
+
return None
|
|
457
|
+
|
|
458
|
+
return current_obj, _require_field(type(current_obj), parts[-1])
|
|
459
|
+
|
|
460
|
+
def _get(self, resource: ResourceT) -> Any:
|
|
461
|
+
"""Get the value at this path from a resource."""
|
|
462
|
+
if (resolution := self._resolve_instance(resource)) is None:
|
|
463
|
+
return None
|
|
464
|
+
|
|
465
|
+
if not resolution.path_str:
|
|
466
|
+
return resolution.target
|
|
467
|
+
|
|
468
|
+
if (
|
|
469
|
+
result := self._walk_to_target(resolution.target, resolution.path_str)
|
|
470
|
+
) is None:
|
|
471
|
+
return None
|
|
472
|
+
|
|
473
|
+
obj, field_name = result
|
|
474
|
+
return getattr(obj, field_name)
|
|
475
|
+
|
|
476
|
+
def get(self, resource: ResourceT, *, strict: bool = True) -> Any:
|
|
477
|
+
"""Get the value at this path from a resource.
|
|
478
|
+
|
|
479
|
+
:param resource: The resource to get the value from.
|
|
480
|
+
:param strict: If True, raise exceptions for invalid paths.
|
|
481
|
+
:returns: The value at this path, or None if the value is absent.
|
|
482
|
+
:raises PathNotFoundException: If strict and the path references a non-existent field.
|
|
483
|
+
:raises InvalidPathException: If strict and the path references an unknown extension.
|
|
484
|
+
"""
|
|
485
|
+
try:
|
|
486
|
+
return self._get(resource)
|
|
487
|
+
except InvalidPathException:
|
|
488
|
+
if strict:
|
|
489
|
+
raise
|
|
490
|
+
return None
|
|
491
|
+
|
|
492
|
+
def _set(self, resource: ResourceT, value: Any, *, is_add: bool = False) -> bool:
|
|
493
|
+
"""Set a value at this path on a resource."""
|
|
494
|
+
if (resolution := self._resolve_instance(resource, create=True)) is None:
|
|
495
|
+
return False
|
|
496
|
+
|
|
497
|
+
obj = resolution.target
|
|
498
|
+
path_str = resolution.path_str
|
|
499
|
+
is_explicit_schema_path = resolution.is_explicit_schema_path
|
|
500
|
+
|
|
501
|
+
if not path_str:
|
|
502
|
+
if not isinstance(value, dict):
|
|
503
|
+
if is_explicit_schema_path:
|
|
504
|
+
raise InvalidPathException(path=str(self))
|
|
505
|
+
return False
|
|
506
|
+
filtered_value = {
|
|
507
|
+
k: v
|
|
508
|
+
for k, v in value.items()
|
|
509
|
+
if _find_field_name(type(obj), k) is not None
|
|
510
|
+
}
|
|
511
|
+
if not filtered_value:
|
|
512
|
+
return False
|
|
513
|
+
old_data = obj.model_dump()
|
|
514
|
+
updated_data = {**old_data, **filtered_value}
|
|
515
|
+
if updated_data == old_data:
|
|
516
|
+
return False
|
|
517
|
+
updated_obj = type(obj).model_validate(updated_data)
|
|
518
|
+
obj.__dict__.update(updated_obj.__dict__)
|
|
519
|
+
return True
|
|
520
|
+
|
|
521
|
+
if "." not in path_str:
|
|
522
|
+
field_name = _require_field(type(obj), path_str)
|
|
523
|
+
return self._set_field_value(obj, field_name, value, is_add)
|
|
524
|
+
|
|
525
|
+
parts = path_str.split(".")
|
|
526
|
+
current_obj = obj
|
|
527
|
+
|
|
528
|
+
for part in parts[:-1]:
|
|
529
|
+
field_name = _require_field(type(current_obj), part)
|
|
530
|
+
if (sub_obj := getattr(current_obj, field_name)) is None:
|
|
531
|
+
field_type = type(current_obj).get_field_root_type(field_name)
|
|
532
|
+
if field_type is None or field_type is Any or not isclass(field_type):
|
|
533
|
+
return False
|
|
534
|
+
sub_obj = field_type()
|
|
535
|
+
setattr(current_obj, field_name, sub_obj)
|
|
536
|
+
elif isinstance(sub_obj, list):
|
|
537
|
+
return False
|
|
538
|
+
current_obj = sub_obj
|
|
539
|
+
|
|
540
|
+
field_name = _require_field(type(current_obj), parts[-1])
|
|
541
|
+
return self._set_field_value(current_obj, field_name, value, is_add)
|
|
542
|
+
|
|
543
|
+
def set(
|
|
544
|
+
self,
|
|
545
|
+
resource: ResourceT,
|
|
546
|
+
value: Any,
|
|
547
|
+
*,
|
|
548
|
+
is_add: bool = False,
|
|
549
|
+
strict: bool = True,
|
|
550
|
+
) -> bool:
|
|
551
|
+
"""Set a value at this path on a resource.
|
|
552
|
+
|
|
553
|
+
:param resource: The resource to set the value on.
|
|
554
|
+
:param value: The value to set.
|
|
555
|
+
:param is_add: If True and the target is multi-valued, append to the
|
|
556
|
+
list instead of replacing. Duplicates are not added.
|
|
557
|
+
:param strict: If True, raise exceptions for invalid paths.
|
|
558
|
+
:returns: True if the value was set/added, False if unchanged.
|
|
559
|
+
:raises InvalidPathException: If strict and the path does not exist or is invalid.
|
|
560
|
+
"""
|
|
561
|
+
try:
|
|
562
|
+
return self._set(resource, value, is_add=is_add)
|
|
563
|
+
except InvalidPathException:
|
|
564
|
+
if strict:
|
|
565
|
+
raise
|
|
566
|
+
return False
|
|
567
|
+
|
|
568
|
+
@staticmethod
|
|
569
|
+
def _set_field_value(
|
|
570
|
+
obj: BaseModel, field_name: str, value: Any, is_add: bool
|
|
571
|
+
) -> bool:
|
|
572
|
+
"""Set or add a value to a field."""
|
|
573
|
+
is_multivalued = obj.get_field_multiplicity(field_name)
|
|
574
|
+
|
|
575
|
+
if is_add and is_multivalued:
|
|
576
|
+
current_list = getattr(obj, field_name) or []
|
|
577
|
+
if isinstance(value, list):
|
|
578
|
+
new_values = [v for v in value if not _value_in_list(current_list, v)]
|
|
579
|
+
if not new_values:
|
|
580
|
+
return False
|
|
581
|
+
setattr(obj, field_name, current_list + new_values)
|
|
582
|
+
else:
|
|
583
|
+
if _value_in_list(current_list, value):
|
|
584
|
+
return False
|
|
585
|
+
current_list.append(value)
|
|
586
|
+
setattr(obj, field_name, current_list)
|
|
587
|
+
return True
|
|
588
|
+
|
|
589
|
+
if is_multivalued and not isinstance(value, list) and value is not None:
|
|
590
|
+
value = [value]
|
|
591
|
+
|
|
592
|
+
old_value = getattr(obj, field_name)
|
|
593
|
+
if old_value == value:
|
|
594
|
+
return False
|
|
595
|
+
|
|
596
|
+
setattr(obj, field_name, value)
|
|
597
|
+
return True
|
|
598
|
+
|
|
599
|
+
def _delete(self, resource: ResourceT, value: Any | None = None) -> bool:
|
|
600
|
+
"""Delete a value at this path from a resource."""
|
|
601
|
+
if (resolution := self._resolve_instance(resource)) is None:
|
|
602
|
+
return False
|
|
603
|
+
|
|
604
|
+
if not resolution.path_str:
|
|
605
|
+
raise InvalidPathException(path=str(self))
|
|
606
|
+
|
|
607
|
+
if (
|
|
608
|
+
result := self._walk_to_target(resolution.target, resolution.path_str)
|
|
609
|
+
) is None:
|
|
610
|
+
return False
|
|
611
|
+
|
|
612
|
+
obj, field_name = result
|
|
613
|
+
if (current_value := getattr(obj, field_name)) is None:
|
|
614
|
+
return False
|
|
615
|
+
|
|
616
|
+
if value is not None:
|
|
617
|
+
if not isinstance(current_value, list):
|
|
618
|
+
return False
|
|
619
|
+
new_list = [
|
|
620
|
+
item for item in current_value if not _values_match(item, value)
|
|
621
|
+
]
|
|
622
|
+
if len(new_list) == len(current_value):
|
|
623
|
+
return False
|
|
624
|
+
setattr(obj, field_name, new_list if new_list else None)
|
|
625
|
+
return True
|
|
626
|
+
|
|
627
|
+
setattr(obj, field_name, None)
|
|
628
|
+
return True
|
|
629
|
+
|
|
630
|
+
def delete(
|
|
631
|
+
self, resource: ResourceT, value: Any | None = None, *, strict: bool = True
|
|
632
|
+
) -> bool:
|
|
633
|
+
"""Delete a value at this path from a resource.
|
|
634
|
+
|
|
635
|
+
If value is None, the entire attribute is set to None.
|
|
636
|
+
If value is provided and the attribute is multi-valued,
|
|
637
|
+
only matching values are removed from the list.
|
|
638
|
+
|
|
639
|
+
:param resource: The resource to delete the value from.
|
|
640
|
+
:param value: Optional specific value to remove from a list.
|
|
641
|
+
:param strict: If True, raise exceptions for invalid paths.
|
|
642
|
+
:returns: True if a value was deleted, False if unchanged.
|
|
643
|
+
:raises InvalidPathException: If strict and the path does not exist or is invalid.
|
|
644
|
+
"""
|
|
645
|
+
try:
|
|
646
|
+
return self._delete(resource, value)
|
|
647
|
+
except InvalidPathException:
|
|
648
|
+
if strict:
|
|
649
|
+
raise
|
|
650
|
+
return False
|
|
651
|
+
|
|
652
|
+
@classmethod
|
|
653
|
+
def iter_paths(
|
|
654
|
+
cls,
|
|
655
|
+
include_subattributes: bool = True,
|
|
656
|
+
include_extensions: bool = True,
|
|
657
|
+
required: "list[Required] | None" = None,
|
|
658
|
+
mutability: "list[Mutability] | None" = None,
|
|
659
|
+
) -> "Iterator[Path[ResourceT]]":
|
|
660
|
+
"""Iterate over all paths for the bound model and its extensions.
|
|
661
|
+
|
|
662
|
+
Requires the Path to be bound to a model type via ``Path[Model]``.
|
|
663
|
+
|
|
664
|
+
:param include_subattributes: Whether to include sub-attribute paths.
|
|
665
|
+
:param include_extensions: Whether to include extension attributes.
|
|
666
|
+
:param required: Filter by Required annotation values (e.g., [Required.true]).
|
|
667
|
+
:param mutability: Filter by Mutability annotation values (e.g., [Mutability.read_write]).
|
|
668
|
+
:yields: Path instances for each attribute matching the filters.
|
|
669
|
+
"""
|
|
670
|
+
from .annotations import Mutability
|
|
671
|
+
from .annotations import Required
|
|
672
|
+
from .attributes import ComplexAttribute
|
|
673
|
+
from .resources.resource import Extension
|
|
674
|
+
from .resources.resource import Resource
|
|
675
|
+
|
|
676
|
+
model = cls.__scim_model__
|
|
677
|
+
if model is None:
|
|
678
|
+
raise TypeError("iter_paths requires a bound Path type: Path[Model]")
|
|
679
|
+
|
|
680
|
+
def matches_filters(target_model: type[BaseModel], field_name: str) -> bool:
|
|
681
|
+
if required is not None:
|
|
682
|
+
field_required = target_model.get_field_annotation(field_name, Required)
|
|
683
|
+
if field_required not in required:
|
|
684
|
+
return False
|
|
685
|
+
if mutability is not None:
|
|
686
|
+
field_mutability = target_model.get_field_annotation(
|
|
687
|
+
field_name, Mutability
|
|
688
|
+
)
|
|
689
|
+
if field_mutability not in mutability:
|
|
690
|
+
return False
|
|
691
|
+
return True
|
|
692
|
+
|
|
693
|
+
def iter_model_paths(
|
|
694
|
+
target_model: type[Resource[Any] | Extension],
|
|
695
|
+
) -> "Iterator[Path[ResourceT]]":
|
|
696
|
+
for field_name in target_model.model_fields:
|
|
697
|
+
if field_name in ("meta", "id", "schemas"):
|
|
698
|
+
continue
|
|
699
|
+
|
|
700
|
+
if not matches_filters(target_model, field_name):
|
|
701
|
+
continue
|
|
702
|
+
|
|
703
|
+
field_type = target_model.get_field_root_type(field_name)
|
|
704
|
+
|
|
705
|
+
urn: str
|
|
706
|
+
if isclass(field_type) and issubclass(field_type, Extension):
|
|
707
|
+
if not include_extensions:
|
|
708
|
+
continue
|
|
709
|
+
urn = field_type.__schema__ or ""
|
|
710
|
+
elif isclass(target_model) and issubclass(target_model, Extension):
|
|
711
|
+
urn = target_model().get_attribute_urn(field_name)
|
|
712
|
+
else:
|
|
713
|
+
urn = _to_camel(field_name)
|
|
714
|
+
|
|
715
|
+
yield cls(urn)
|
|
716
|
+
|
|
717
|
+
is_complex = (
|
|
718
|
+
field_type is not None
|
|
719
|
+
and isclass(field_type)
|
|
720
|
+
and issubclass(field_type, ComplexAttribute)
|
|
721
|
+
)
|
|
722
|
+
if include_subattributes and is_complex:
|
|
723
|
+
for sub_field_name in field_type.model_fields: # type: ignore[union-attr]
|
|
724
|
+
if not matches_filters(field_type, sub_field_name): # type: ignore[arg-type]
|
|
725
|
+
continue
|
|
726
|
+
sub_urn = f"{urn}.{_to_camel(sub_field_name)}"
|
|
727
|
+
yield cls(sub_urn)
|
|
728
|
+
|
|
729
|
+
yield from iter_model_paths(model) # type: ignore[arg-type]
|
|
730
|
+
|
|
731
|
+
if include_extensions and isclass(model) and issubclass(model, Resource):
|
|
732
|
+
for extension_model in model.get_extension_models().values():
|
|
733
|
+
yield from iter_model_paths(extension_model)
|