devadmin 0.1.0__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.
Files changed (73) hide show
  1. devadmin/__init__.py +19 -0
  2. devadmin/__main__.py +5 -0
  3. devadmin/adapters/__init__.py +0 -0
  4. devadmin/adapters/base.py +175 -0
  5. devadmin/adapters/tortoise/__init__.py +81 -0
  6. devadmin/adapters/tortoise/introspect.py +209 -0
  7. devadmin/adapters/tortoise/models.py +34 -0
  8. devadmin/adapters/tortoise/queries.py +330 -0
  9. devadmin/adapters/tortoise/related.py +215 -0
  10. devadmin/adapters/tortoise/store.py +156 -0
  11. devadmin/auth/__init__.py +16 -0
  12. devadmin/auth/csrf.py +18 -0
  13. devadmin/auth/ip.py +28 -0
  14. devadmin/auth/login.py +149 -0
  15. devadmin/auth/session.py +94 -0
  16. devadmin/cli.py +314 -0
  17. devadmin/config.py +34 -0
  18. devadmin/core/__init__.py +0 -0
  19. devadmin/core/binding.py +609 -0
  20. devadmin/core/forms.py +475 -0
  21. devadmin/core/listing.py +400 -0
  22. devadmin/core/options.py +99 -0
  23. devadmin/core/paths.py +39 -0
  24. devadmin/core/site.py +288 -0
  25. devadmin/core/values.py +122 -0
  26. devadmin/history/__init__.py +38 -0
  27. devadmin/history/diff.py +109 -0
  28. devadmin/history/encoding.py +120 -0
  29. devadmin/history/records.py +40 -0
  30. devadmin/history/render.py +129 -0
  31. devadmin/history/service.py +256 -0
  32. devadmin/web/__init__.py +0 -0
  33. devadmin/web/app.py +106 -0
  34. devadmin/web/deps.py +275 -0
  35. devadmin/web/guard.py +178 -0
  36. devadmin/web/static/autocomplete.js +231 -0
  37. devadmin/web/static/devadmin.css +1645 -0
  38. devadmin/web/static/devadmin.js +129 -0
  39. devadmin/web/static/htmx.min.js +1 -0
  40. devadmin/web/static/icons/check.svg +1 -0
  41. devadmin/web/static/icons/clock.svg +1 -0
  42. devadmin/web/static/icons/cross.svg +1 -0
  43. devadmin/web/static/icons/down.svg +1 -0
  44. devadmin/web/static/icons/eye.svg +1 -0
  45. devadmin/web/static/icons/lock.svg +1 -0
  46. devadmin/web/static/icons/pencil.svg +1 -0
  47. devadmin/web/static/icons/plus.svg +1 -0
  48. devadmin/web/static/icons/right.svg +1 -0
  49. devadmin/web/static/icons/trash.svg +1 -0
  50. devadmin/web/static/icons/up.svg +1 -0
  51. devadmin/web/templates/_field.html +35 -0
  52. devadmin/web/templates/_history.html +19 -0
  53. devadmin/web/templates/_pagination.html +8 -0
  54. devadmin/web/templates/action_confirm.html +26 -0
  55. devadmin/web/templates/base.html +63 -0
  56. devadmin/web/templates/delete.html +62 -0
  57. devadmin/web/templates/error.html +9 -0
  58. devadmin/web/templates/form.html +34 -0
  59. devadmin/web/templates/history.html +59 -0
  60. devadmin/web/templates/index.html +49 -0
  61. devadmin/web/templates/list.html +88 -0
  62. devadmin/web/templates/login.html +15 -0
  63. devadmin/web/templates/recent.html +25 -0
  64. devadmin/web/views_auth.py +146 -0
  65. devadmin/web/views_delete.py +774 -0
  66. devadmin/web/views_form.py +551 -0
  67. devadmin/web/views_history.py +261 -0
  68. devadmin/web/views_list.py +246 -0
  69. devadmin-0.1.0.dist-info/METADATA +702 -0
  70. devadmin-0.1.0.dist-info/RECORD +73 -0
  71. devadmin-0.1.0.dist-info/WHEEL +4 -0
  72. devadmin-0.1.0.dist-info/entry_points.txt +3 -0
  73. devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
devadmin/core/site.py ADDED
@@ -0,0 +1,288 @@
1
+ import importlib
2
+ import inspect
3
+ import re
4
+ from collections import Counter
5
+ from collections.abc import Callable, Mapping
6
+ from typing import TYPE_CHECKING, Any, TypeVar
7
+
8
+ from devadmin.adapters.base import FieldInfo, FieldType, ModelInfo
9
+ from devadmin.config import AdminConfig
10
+ from devadmin.core.binding import ActionSpec, BoundAdmin, Column, bind_admin, list_problem
11
+ from devadmin.core.options import ConfigError, ModelAdmin
12
+
13
+ if TYPE_CHECKING:
14
+ from starlette.requests import Request
15
+
16
+ __all__ = ["ActionSpec", "BoundAdmin", "Column", "Site", "model_label", "plural_label", "register"]
17
+
18
+ T = TypeVar("T")
19
+
20
+ HISTORY_TABLES = frozenset({"devadmin_action", "devadmin_change"})
21
+ _EXCEPTION_TEXT_LIMIT = 100
22
+
23
+ _registry: list[tuple[str, Any]] = []
24
+
25
+ _WORD_BREAK = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
26
+
27
+
28
+ def _registration_identity(key: str, cls: Any) -> tuple[str, str | None, str | None]:
29
+ return key, getattr(cls, "__module__", None), getattr(cls, "__qualname__", None)
30
+
31
+
32
+ def register(key: str) -> Callable[[T], T]:
33
+ def decorator(cls: T) -> T:
34
+ identity = _registration_identity(key, cls)
35
+ for index, (existing_key, existing) in enumerate(_registry):
36
+ if existing_key == key and existing is cls:
37
+ return cls
38
+ if None not in identity and _registration_identity(existing_key, existing) == identity:
39
+ _registry[index] = (key, cls)
40
+ return cls
41
+ _registry.append((key, cls))
42
+ return cls
43
+
44
+ return decorator
45
+
46
+
47
+ def _registrations_under(entries: list[str]) -> list[tuple[str, Any]]:
48
+ found: list[tuple[str, Any]] = []
49
+ for entry in entries:
50
+ for key, cls in _registry:
51
+ module = getattr(cls, "__module__", None) or ""
52
+ if (module == entry or module.startswith(entry + ".")) and (key, cls) not in found:
53
+ found.append((key, cls))
54
+ return found
55
+
56
+
57
+ def model_label(name: str) -> str:
58
+ first, *rest = _WORD_BREAK.sub(" ", name).split(" ")
59
+ return " ".join([first, *(word if len(word) > 1 and word.isupper() else word.lower() for word in rest)])
60
+
61
+
62
+ def plural_label(label: str) -> str:
63
+ if label.endswith(("s", "x", "z", "ch", "sh")):
64
+ return label + "es"
65
+ if label.endswith("y") and len(label) > 1 and label[-2].lower() not in "aeiou":
66
+ return label[:-1] + "ies"
67
+ return label + "s"
68
+
69
+
70
+ def _default_group(module: str) -> str:
71
+ return module.rsplit(".", 1)[-1].replace("_", " ").capitalize()
72
+
73
+
74
+ def _is_positive_int(value: Any) -> bool:
75
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
76
+
77
+
78
+ def _name_list(config: AdminConfig, option: str, errors: list[str]) -> list[str]:
79
+ value = getattr(config, option)
80
+ if isinstance(value, (list, tuple)) and all(isinstance(item, str) for item in value):
81
+ return list(value)
82
+ errors.append(f"AdminConfig.{option}: {list_problem(value)}")
83
+ return []
84
+
85
+
86
+ def _sensitive_patterns(config: AdminConfig, errors: list[str]) -> list[str] | None:
87
+ value = config.sensitive_patterns
88
+ if isinstance(value, str):
89
+ errors.append(
90
+ "AdminConfig.sensitive_patterns: must be a tuple of strings, not a string;"
91
+ f" write a single pattern as ({value!r},)"
92
+ )
93
+ return None
94
+ if not isinstance(value, (list, tuple)) or not all(isinstance(item, str) and item for item in value):
95
+ errors.append("AdminConfig.sensitive_patterns: must be a tuple of non-empty strings")
96
+ return None
97
+ return [pattern.lower() for pattern in value]
98
+
99
+
100
+ def _groups(config: AdminConfig, errors: list[str]) -> dict[str, list[str]]:
101
+ value = config.groups
102
+ if value is None:
103
+ return {}
104
+ if not isinstance(value, dict) or not all(isinstance(name, str) for name in value):
105
+ errors.append("AdminConfig.groups: must be a dict of group name to a list of model keys")
106
+ return {}
107
+ groups = {}
108
+ for name, keys in value.items():
109
+ if isinstance(keys, (list, tuple)) and all(isinstance(key, str) for key in keys):
110
+ groups[name] = list(keys)
111
+ else:
112
+ errors.append(f"AdminConfig.groups: {name!r} {list_problem(keys)}")
113
+ return groups
114
+
115
+
116
+ class Site:
117
+ def __init__(self, config: AdminConfig, overrides: Mapping[str, type[ModelAdmin]] | None = None) -> None:
118
+ self.config = config
119
+ self._overrides: list[tuple[str, Any]] = list((overrides or {}).items())
120
+ self._admins: dict[str, BoundAdmin] = {}
121
+ self._sensitive: dict[str, set[str]] = {}
122
+
123
+ def register(self, key: str) -> Callable[[T], T]:
124
+ def decorator(cls: T) -> T:
125
+ self._overrides.append((key, cls))
126
+ return cls
127
+
128
+ return decorator
129
+
130
+ def build(self) -> None:
131
+ config = self.config
132
+ errors: list[str] = []
133
+ patterns = _sensitive_patterns(config, errors)
134
+ exclude_models = _name_list(config, "exclude_models", errors)
135
+ read_only_models = _name_list(config, "read_only_models", errors)
136
+ admin_modules = _name_list(config, "admin_modules", errors)
137
+ _name_list(config, "allowed_ips", errors)
138
+ models = config.adapter.list_models()
139
+ schema = {info.key: {field.name: field for field in config.adapter.describe(info.model)} for info in models}
140
+ sensitive = {
141
+ key: {name for name in fields if patterns and any(pattern in name.lower() for pattern in patterns)}
142
+ for key, fields in schema.items()
143
+ }
144
+ config.adapter.hide_from_names(sensitive)
145
+ errors.extend(_config_errors(config, schema))
146
+ for key in exclude_models:
147
+ if key not in schema:
148
+ errors.append(f"AdminConfig.exclude_models: unknown model {key!r}")
149
+ registered = {
150
+ info.key: info for info in models if info.key not in exclude_models and info.table not in HISTORY_TABLES
151
+ }
152
+ for key in read_only_models:
153
+ if key not in registered:
154
+ errors.append(f"AdminConfig.read_only_models: unknown or excluded model {key!r}")
155
+ overrides = self._collect_overrides(registered, admin_modules, errors)
156
+ shared = Counter(overrides.values())
157
+ groups = self._group_names(registered, _groups(config, errors), errors)
158
+ admins = {}
159
+ for key, info in registered.items():
160
+ override = overrides.get(key, ModelAdmin)
161
+ note = f"[{key}] " if shared[override] > 1 else ""
162
+ try:
163
+ options = override()
164
+ except Exception as exc:
165
+ if _needs_arguments(override):
166
+ problem = f"cannot be instantiated without arguments ({type(exc).__name__}: {exc})"
167
+ else:
168
+ problem = f"could not be instantiated ({_exception_text(exc)})"
169
+ errors.append(f"{override.__name__}: {note}{problem}")
170
+ continue
171
+ label = model_label(info.name)
172
+ admins[key] = bind_admin(
173
+ info,
174
+ schema,
175
+ sensitive,
176
+ options,
177
+ errors,
178
+ read_only=key in read_only_models,
179
+ group=groups[key],
180
+ label=label,
181
+ label_plural=plural_label(label),
182
+ shared=shared[override] > 1,
183
+ )
184
+ if errors:
185
+ raise ConfigError("\n".join(errors))
186
+ self._sensitive = sensitive
187
+ self._admins = admins
188
+
189
+ def get(self, key: str) -> BoundAdmin:
190
+ return self._admins[key]
191
+
192
+ def sensitive_fields(self, key: str) -> set[str]:
193
+ return set(self._sensitive[key])
194
+
195
+ def groups(self, request: "Request | None") -> list[tuple[str, list[BoundAdmin]]]:
196
+ grouped: dict[str, list[BoundAdmin]] = {}
197
+ for admin in self._admins.values():
198
+ if admin.options.has_view_permission(request):
199
+ grouped.setdefault(admin.group, []).append(admin)
200
+ configured = list(self.config.groups or {})
201
+ position = {name: index for index, name in enumerate(configured)}
202
+ ordered = sorted(grouped.items(), key=lambda item: (position.get(item[0], len(position)), item[0]))
203
+ return [(name, sorted(admins, key=lambda admin: admin.info.name)) for name, admins in ordered]
204
+
205
+ def _collect_overrides(
206
+ self, registered: Mapping[str, ModelInfo], admin_modules: list[str], errors: list[str]
207
+ ) -> dict[str, type[ModelAdmin]]:
208
+ for module in admin_modules:
209
+ importlib.import_module(module)
210
+ overrides: dict[str, type[ModelAdmin]] = {}
211
+ for key, cls in [*_registrations_under(admin_modules), *self._overrides]:
212
+ owner = getattr(cls, "__name__", repr(cls))
213
+ if not (isinstance(cls, type) and issubclass(cls, ModelAdmin)):
214
+ errors.append(f"{owner}.register: must be a subclass of ModelAdmin")
215
+ elif key not in registered:
216
+ errors.append(f"{owner}.register: unknown or excluded model {key!r}")
217
+ elif key in overrides and overrides[key] is not cls:
218
+ errors.append(f"{owner}.register: {key} is already registered with {overrides[key].__name__}")
219
+ else:
220
+ overrides[key] = cls
221
+ return overrides
222
+
223
+ def _group_names(
224
+ self, registered: Mapping[str, ModelInfo], configured: dict[str, list[str]], errors: list[str]
225
+ ) -> dict[str, str]:
226
+ groups = {key: _default_group(info.module) for key, info in registered.items()}
227
+ assigned: set[str] = set()
228
+ for name, keys in configured.items():
229
+ for key in keys:
230
+ if key not in registered:
231
+ errors.append(f"AdminConfig.groups: unknown or excluded model {key!r}")
232
+ elif key in assigned:
233
+ errors.append(f"AdminConfig.groups: {key} is in more than one group")
234
+ else:
235
+ assigned.add(key)
236
+ groups[key] = name
237
+ return groups
238
+
239
+
240
+ def _exception_text(exc: BaseException) -> str:
241
+ lines = str(exc).strip().splitlines()
242
+ first = lines[0].strip()[:_EXCEPTION_TEXT_LIMIT] if lines else ""
243
+ return f"{type(exc).__name__}: {first}" if first else type(exc).__name__
244
+
245
+
246
+ def _needs_arguments(cls: Any) -> bool:
247
+ try:
248
+ inspect.signature(cls).bind()
249
+ except TypeError:
250
+ return True
251
+ except ValueError:
252
+ return False
253
+ return False
254
+
255
+
256
+ def _config_errors(config: AdminConfig, schema: Mapping[str, Mapping[str, FieldInfo]]) -> list[str]:
257
+ errors = []
258
+ names = {"user_model": config.user_model}
259
+ names.update({option: getattr(config, option) for option in ("login_field", "password_field", "access_flag")})
260
+ for option, value in names.items():
261
+ if not isinstance(value, str):
262
+ errors.append(f"AdminConfig.{option}: must be a string")
263
+ user_fields = schema.get(config.user_model) if isinstance(config.user_model, str) else None
264
+ if isinstance(config.user_model, str) and user_fields is None:
265
+ errors.append(f"AdminConfig.user_model: unknown model {config.user_model!r}")
266
+ if user_fields is not None:
267
+ expected_types = {"login_field": FieldType.STR, "password_field": None, "access_flag": FieldType.BOOL}
268
+ for option, expected in expected_types.items():
269
+ name = names[option]
270
+ if not isinstance(name, str):
271
+ continue
272
+ field = user_fields.get(name)
273
+ if field is None:
274
+ errors.append(f"AdminConfig.{option}: {config.user_model} has no field {name!r}")
275
+ elif expected is not None and field.type is not expected:
276
+ errors.append(
277
+ f"AdminConfig.{option}: must be a {expected} field, {config.user_model}.{name} is {field.type}"
278
+ )
279
+ if not isinstance(config.secret_key, str) or len(config.secret_key) < 16:
280
+ errors.append("AdminConfig.secret_key: must be a string of at least 16 characters")
281
+ for option in ("session_seconds", "exact_count_threshold", "max_cascade_rows"):
282
+ if not _is_positive_int(getattr(config, option)):
283
+ errors.append(f"AdminConfig.{option}: must be a positive integer")
284
+ for option in ("startup", "shutdown"):
285
+ hook = getattr(config, option)
286
+ if hook is not None and not callable(hook):
287
+ errors.append(f"AdminConfig.{option}: must be a callable or None")
288
+ return errors
@@ -0,0 +1,122 @@
1
+ import re
2
+ import uuid
3
+ from decimal import Decimal
4
+ from typing import Any
5
+
6
+ from devadmin.adapters.base import FieldInfo, FieldType
7
+
8
+ BELOW_MIN = "below_min"
9
+ ABOVE_MAX = "above_max"
10
+ TOO_MANY_DECIMAL_PLACES = "too_many_decimal_places"
11
+ TOO_LARGE = "too_large"
12
+ MAX_INTEGER_DIGITS = 20
13
+ MAX_SIGNIFICANT_DIGITS = 40
14
+
15
+ _INTEGER = re.compile(r"-?[0-9]+")
16
+ _DECIMAL = re.compile(r"-?[0-9]{1,40}(\.[0-9]{1,40})?")
17
+ _INT64_MIN = -(2**63)
18
+ _INT64_MAX = 2**63 - 1
19
+ _NOT_A_WHOLE_NUMBER = "not a whole number"
20
+ _PROBLEMS = {
21
+ BELOW_MIN: "the number is below the minimum",
22
+ ABOVE_MAX: "the number is above the maximum",
23
+ TOO_MANY_DECIMAL_PLACES: "the number has too many decimal places",
24
+ TOO_LARGE: "the number has too many digits",
25
+ }
26
+ _UUID = re.compile(r"[0-9a-fA-F]{32}|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
27
+
28
+
29
+ def parse_scalar(field: FieldInfo, text: str) -> Any:
30
+ if field.type in (FieldType.STR, FieldType.TEXT):
31
+ return _text(field, text)
32
+ if field.type is FieldType.INT:
33
+ return _integer(field, text)
34
+ if field.type is FieldType.DECIMAL:
35
+ return _decimal(field, text)
36
+ if field.type is FieldType.UUID:
37
+ if _UUID.fullmatch(text) is None:
38
+ raise ValueError(f"{field.name}: {text!r} is not a UUID")
39
+ return uuid.UUID(text)
40
+ raise ValueError(f"{field.name}: a {field.type} value cannot be read from text")
41
+
42
+
43
+ def _text(field: FieldInfo, text: str) -> str:
44
+ if "\x00" in text:
45
+ raise ValueError(f"{field.name}: the text contains a NUL character")
46
+ try:
47
+ text.encode("utf-8")
48
+ except UnicodeEncodeError:
49
+ raise ValueError(f"{field.name}: the text is not valid UTF-8") from None
50
+ if field.type is FieldType.STR and field.max_length is not None and len(text) > field.max_length:
51
+ raise ValueError(f"{field.name}: the text is longer than {field.max_length} characters")
52
+ return text
53
+
54
+
55
+ def whole_number(text: str) -> int | None:
56
+ if _INTEGER.fullmatch(text) is None:
57
+ raise ValueError(_NOT_A_WHOLE_NUMBER)
58
+ digits = text.lstrip("-").lstrip("0") or "0"
59
+ if len(digits) > MAX_INTEGER_DIGITS:
60
+ return None
61
+ return -int(digits) if text.startswith("-") else int(digits)
62
+
63
+
64
+ def integer_problem(field: FieldInfo, value: int | None) -> str | None:
65
+ if value is None:
66
+ return TOO_LARGE
67
+ low = _INT64_MIN if field.min_value is None else field.min_value
68
+ high = _INT64_MAX if field.max_value is None else field.max_value
69
+ if value < low:
70
+ return BELOW_MIN
71
+ if value > high:
72
+ return ABOVE_MAX
73
+ return None
74
+
75
+
76
+ def _significant_digits_and_places(value: Decimal) -> tuple[int, int]:
77
+ _, digits, exponent = value.as_tuple()
78
+ if not isinstance(exponent, int):
79
+ return MAX_SIGNIFICANT_DIGITS + 1, 0
80
+ end = len(digits)
81
+ while end > 0 and digits[end - 1] == 0 and exponent < 0:
82
+ end -= 1
83
+ exponent += 1
84
+ start = 0
85
+ while start < end and digits[start] == 0:
86
+ start += 1
87
+ if start == end:
88
+ return 0, 0
89
+ return end - start + max(exponent, 0), max(-exponent, 0)
90
+
91
+
92
+ def decimal_problem(field: FieldInfo, value: Decimal) -> str | None:
93
+ significant, places = _significant_digits_and_places(value)
94
+ if field.decimal_places is not None and places > field.decimal_places:
95
+ return TOO_MANY_DECIMAL_PLACES
96
+ if significant > MAX_SIGNIFICANT_DIGITS:
97
+ return TOO_LARGE
98
+ if field.min_value is not None and value < field.min_value:
99
+ return BELOW_MIN
100
+ if field.max_value is not None and value > field.max_value:
101
+ return ABOVE_MAX
102
+ return None
103
+
104
+
105
+ def _integer(field: FieldInfo, text: str) -> int:
106
+ if _INTEGER.fullmatch(text) is None:
107
+ raise ValueError(f"{field.name}: {_NOT_A_WHOLE_NUMBER}")
108
+ value = whole_number(text)
109
+ problem = integer_problem(field, value)
110
+ if problem is not None:
111
+ raise ValueError(f"{field.name}: {_PROBLEMS[problem]}")
112
+ return value
113
+
114
+
115
+ def _decimal(field: FieldInfo, text: str) -> Decimal:
116
+ if _DECIMAL.fullmatch(text) is None:
117
+ raise ValueError(f"{field.name}: not a decimal number")
118
+ value = Decimal(text)
119
+ problem = decimal_problem(field, value)
120
+ if problem is not None:
121
+ raise ValueError(f"{field.name}: {_PROBLEMS[problem]}")
122
+ return value
@@ -0,0 +1,38 @@
1
+ from contextlib import AbstractAsyncContextManager
2
+ from typing import TYPE_CHECKING, Any
3
+
4
+ if TYPE_CHECKING:
5
+ from devadmin.history.service import ActionCollector, History
6
+
7
+ _bound: "History | None" = None
8
+
9
+
10
+ def bind(history: "History | None") -> None:
11
+ global _bound
12
+ _bound = history
13
+
14
+
15
+ def bound() -> "History | None":
16
+ return _bound
17
+
18
+
19
+ def _configured() -> "History":
20
+ if _bound is None:
21
+ raise RuntimeError("devadmin is not configured")
22
+ return _bound
23
+
24
+
25
+ def action(
26
+ *,
27
+ actor: Any | None,
28
+ summary: str,
29
+ kind: str = "custom",
30
+ source: str = "code",
31
+ ip: str | None = None,
32
+ meta: dict | None = None,
33
+ ) -> "AbstractAsyncContextManager[ActionCollector]":
34
+ return _configured().action(actor=actor, summary=summary, kind=kind, source=source, ip=ip, meta=meta)
35
+
36
+
37
+ def snapshot(obj: Any) -> dict:
38
+ return _configured().snapshot(obj)
@@ -0,0 +1,109 @@
1
+ from typing import Any
2
+
3
+ from devadmin.adapters.base import FieldInfo, ModelInfo
4
+ from devadmin.history.encoding import encode_row, encode_value, is_nan, safe_text, tracked_fields
5
+ from devadmin.history.records import ChangeRecord
6
+
7
+ CHANGED = {"changed": True}
8
+
9
+
10
+ def build_change(
11
+ op: str,
12
+ info: ModelInfo,
13
+ pk: Any,
14
+ repr: str,
15
+ before: dict | None,
16
+ after: dict | None,
17
+ fields: list[FieldInfo],
18
+ sensitive: set[str],
19
+ fk_reprs_before: dict[str, str],
20
+ fk_reprs_after: dict[str, str],
21
+ ) -> ChangeRecord | None:
22
+ if op not in ("create", "update", "delete"):
23
+ raise ValueError(f"unknown op {op!r}")
24
+ if op in ("create", "update") and after is None:
25
+ raise ValueError(f"{op} needs the row after the change")
26
+ if op in ("update", "delete") and before is None:
27
+ raise ValueError(f"{op} needs the row before the change")
28
+
29
+ if op == "create":
30
+ changes = _created(after, fields, sensitive, fk_reprs_after)
31
+ elif op == "update":
32
+ changes = _updated(before, after, fields, sensitive, fk_reprs_before, fk_reprs_after)
33
+ if not changes:
34
+ return None
35
+ else:
36
+ changes = {}
37
+
38
+ if op == "delete":
39
+ snapshot = encode_row(before, fields, sensitive, fk_reprs_before)
40
+ else:
41
+ snapshot = encode_row(after, fields, sensitive, fk_reprs_after)
42
+ field_labels = {
43
+ field.name: _field_label(field, sensitive) for field in fields if field.name in snapshot
44
+ }
45
+ return ChangeRecord(
46
+ model_key=info.key,
47
+ object_pk=safe_text(pk),
48
+ object_repr=safe_text(repr),
49
+ op=op,
50
+ changes=changes,
51
+ snapshot=snapshot,
52
+ field_labels=field_labels,
53
+ )
54
+
55
+
56
+ def _field_label(field: FieldInfo, sensitive: set[str]) -> dict[str, Any]:
57
+ label: dict[str, Any] = {"label": field.label, "type": field.type.value}
58
+ if field.name in sensitive:
59
+ label["sensitive"] = True
60
+ return label
61
+
62
+
63
+ def _created(
64
+ after: dict, fields: list[FieldInfo], sensitive: set[str], fk_reprs: dict[str, str]
65
+ ) -> dict[str, Any]:
66
+ changes = {}
67
+ for field in tracked_fields(fields):
68
+ value = after.get(field.column)
69
+ if value is None:
70
+ continue
71
+ if field.name in sensitive:
72
+ changes[field.name] = dict(CHANGED)
73
+ else:
74
+ changes[field.name] = {"old": None, "new": encode_value(value, field, fk_reprs.get(field.name))}
75
+ return changes
76
+
77
+
78
+ def _updated(
79
+ before: dict,
80
+ after: dict,
81
+ fields: list[FieldInfo],
82
+ sensitive: set[str],
83
+ fk_reprs_before: dict[str, str],
84
+ fk_reprs_after: dict[str, str],
85
+ ) -> dict[str, Any]:
86
+ changes = {}
87
+ for field in tracked_fields(fields):
88
+ if field.column not in before or field.column not in after:
89
+ continue
90
+ old, new = before[field.column], after[field.column]
91
+ if _same(old, new, field):
92
+ continue
93
+ if field.name in sensitive:
94
+ changes[field.name] = dict(CHANGED)
95
+ else:
96
+ changes[field.name] = {
97
+ "old": encode_value(old, field, fk_reprs_before.get(field.name)),
98
+ "new": encode_value(new, field, fk_reprs_after.get(field.name)),
99
+ }
100
+ return changes
101
+
102
+
103
+ def _same(old: Any, new: Any, field: FieldInfo) -> bool:
104
+ if is_nan(old) or is_nan(new):
105
+ return is_nan(old) and is_nan(new)
106
+ try:
107
+ return bool(old == new)
108
+ except Exception:
109
+ return encode_value(old, field) == encode_value(new, field)
@@ -0,0 +1,120 @@
1
+ import math
2
+ from datetime import date, datetime, time, timedelta
3
+ from decimal import Decimal
4
+ from enum import Enum
5
+ from typing import Any
6
+ from uuid import UUID
7
+
8
+ from devadmin.adapters.base import FieldInfo, FieldType
9
+
10
+ UNREPRESENTABLE = "<unrepresentable>"
11
+ SENSITIVE = {"sensitive": True}
12
+
13
+
14
+ def safe_repr(value: Any) -> str:
15
+ try:
16
+ return repr(value)
17
+ except Exception:
18
+ return UNREPRESENTABLE
19
+
20
+
21
+ def safe_text(value: Any) -> str:
22
+ try:
23
+ return str(value)
24
+ except Exception:
25
+ return UNREPRESENTABLE
26
+
27
+
28
+ def encode_value(value: Any, field: FieldInfo, fk_repr: str | None = None) -> Any:
29
+ try:
30
+ return _encode_for_field(value, field, fk_repr)
31
+ except Exception:
32
+ return safe_repr(value)
33
+
34
+
35
+ def encode_row(
36
+ raw: dict[str, Any], fields: list[FieldInfo], sensitive: set[str], fk_reprs: dict[str, str]
37
+ ) -> dict[str, Any]:
38
+ encoded = {}
39
+ for field in tracked_fields(fields):
40
+ if field.column not in raw:
41
+ continue
42
+ if field.name in sensitive:
43
+ encoded[field.name] = dict(SENSITIVE)
44
+ else:
45
+ encoded[field.name] = encode_value(raw[field.column], field, fk_reprs.get(field.name))
46
+ return encoded
47
+
48
+
49
+ def tracked_fields(fields: list[FieldInfo]) -> list[FieldInfo]:
50
+ return [field for field in fields if field.type is not FieldType.M2M]
51
+
52
+
53
+ def _encode_for_field(value: Any, field: FieldInfo, fk_repr: str | None) -> Any:
54
+ if value is None:
55
+ return None
56
+ if field.type is FieldType.FK:
57
+ return {"pk": _encode(value, ()), "repr": fk_repr}
58
+ if field.type is FieldType.ENUM and not isinstance(value, (Enum, bool)) and isinstance(value, (str, int)):
59
+ return {"value": _encode(value, ()), "label": _choice_label(value, field.choices or [])}
60
+ return _encode(value, ())
61
+
62
+
63
+ def is_nan(value: Any) -> bool:
64
+ if isinstance(value, float):
65
+ return math.isnan(value)
66
+ if isinstance(value, Decimal):
67
+ return value.is_nan()
68
+ return False
69
+
70
+
71
+ def _has_decimal_text(value: int) -> bool:
72
+ try:
73
+ int.__repr__(value)
74
+ except ValueError:
75
+ return False
76
+ return True
77
+
78
+
79
+ def _choice_label(value: Any, choices: list[tuple[Any, str]]) -> str:
80
+ for choice, label in choices:
81
+ if choice == value:
82
+ return safe_text(label)
83
+ return safe_text(value)
84
+
85
+
86
+ def _encode(value: Any, ancestors: tuple[int, ...]) -> Any:
87
+ if value is None:
88
+ return None
89
+ if isinstance(value, Enum):
90
+ label = value.name if isinstance(value.name, str) else safe_text(value)
91
+ return {"value": _encode(value.value, ancestors), "label": label}
92
+ if isinstance(value, int) and not isinstance(value, bool):
93
+ return value if _has_decimal_text(value) else str(Decimal(value))
94
+ if isinstance(value, (bool, str)):
95
+ return value
96
+ if isinstance(value, float):
97
+ return value if math.isfinite(value) else repr(value)
98
+ if isinstance(value, Decimal):
99
+ return str(value)
100
+ if isinstance(value, (datetime, date, time)):
101
+ return value.isoformat()
102
+ if isinstance(value, timedelta):
103
+ return value.total_seconds()
104
+ if isinstance(value, UUID):
105
+ return str(value)
106
+ if isinstance(value, (bytes, bytearray)):
107
+ return {"bytes": len(value)}
108
+ if isinstance(value, memoryview):
109
+ return {"bytes": value.nbytes}
110
+ if isinstance(value, (dict, list, tuple)):
111
+ if id(value) in ancestors:
112
+ return safe_repr(value)
113
+ inner = (*ancestors, id(value))
114
+ if isinstance(value, dict):
115
+ return {
116
+ key if isinstance(key, str) else safe_text(key): _encode(item, inner)
117
+ for key, item in value.items()
118
+ }
119
+ return [_encode(item, inner) for item in value]
120
+ return safe_repr(value)