mcms-core 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.
mcms_core/__init__.py ADDED
@@ -0,0 +1,38 @@
1
+ """
2
+ MCMS Core.
3
+
4
+ Shared functionality used throughout the Django MCMS framework.
5
+ """
6
+
7
+ __version__: str = "0.1.0"
8
+
9
+ from .exceptions import (
10
+ MCMSError,
11
+ ConfigurationError,
12
+ RegistryError,
13
+ RegistryItemAlreadyRegisteredError,
14
+ RegistryItemNotFoundError,
15
+ ValidationError,
16
+ SerializationError,
17
+ DiscoveryError,
18
+ DependencyError,
19
+ PackageError,
20
+ )
21
+ from .registry import Registry
22
+ from .settings import mcms_settings
23
+
24
+ __all__ = [
25
+ "MCMSError",
26
+ "ConfigurationError",
27
+ "RegistryError",
28
+ "RegistryItemAlreadyRegisteredError",
29
+ "RegistryItemNotFoundError",
30
+ "ValidationError",
31
+ "SerializationError",
32
+ "RenderingError",
33
+ "DiscoveryError",
34
+ "DependencyError",
35
+ "PackageError",
36
+ "Registry",
37
+ "mcms_settings",
38
+ ]
mcms_core/apps.py ADDED
@@ -0,0 +1,29 @@
1
+ """
2
+ Application configuration for the MCMS Core package.
3
+ """
4
+
5
+ from django.apps import AppConfig
6
+
7
+
8
+ class MCMSCoreConfig(AppConfig):
9
+ """
10
+ Django application configuration for MCMS Core.
11
+
12
+ This application provides the shared abstractions used by every
13
+ MCMS package.
14
+ """
15
+
16
+ default_auto_field = "django.db.models.BigAutoField"
17
+
18
+ name = "mcms_core"
19
+
20
+ verbose_name = "MCMS Core"
21
+
22
+ def ready(self) -> None:
23
+ """
24
+ Perform application startup tasks.
25
+
26
+ Django calls this once the application registry has been fully
27
+ populated.
28
+ """
29
+ from . import checks # noqa: F401
mcms_core/checks.py ADDED
@@ -0,0 +1,180 @@
1
+ """
2
+ Django system checks for django-mcms.
3
+
4
+ These checks validate the framework configuration before the application
5
+ starts, providing early feedback about invalid or deprecated settings.
6
+ """
7
+
8
+ from django.core.checks import CheckMessage
9
+ from django.core.checks import Error
10
+ from django.core.checks import Tags
11
+ from django.core.checks import Warning
12
+ from django.core.checks import register
13
+ from django.core.exceptions import ImproperlyConfigured
14
+
15
+ from mcms_core.constants import CheckIDs
16
+ from mcms_core.constants import MCMS_PREFIX
17
+ from mcms_core.definitions import SETTING_DEFINITIONS
18
+ from mcms_core.definitions import SettingDefinition
19
+ from mcms_core.settings import mcms_settings
20
+
21
+
22
+ def _check_setting(
23
+ name: str,
24
+ definition: SettingDefinition,
25
+ ) -> list[CheckMessage]:
26
+ """
27
+ Validate a single MCMS setting.
28
+
29
+ Parameters
30
+ ----------
31
+ name:
32
+ Name of the setting without the ``MCMS_`` prefix.
33
+
34
+ definition:
35
+ Metadata describing the setting.
36
+
37
+ Returns
38
+ -------
39
+ list[CheckMessage]
40
+ A list of Django check messages.
41
+ """
42
+ messages: list[CheckMessage] = []
43
+
44
+ setting_name = f"{MCMS_PREFIX}_{name}"
45
+
46
+ try:
47
+ value = getattr(mcms_settings, name)
48
+ except ImproperlyConfigured as exc:
49
+ messages.append(
50
+ Error(
51
+ str(exc),
52
+ id=CheckIDs.INVALID_SETTING,
53
+ )
54
+ )
55
+ return messages
56
+
57
+ # ------------------------------------------------------------------
58
+ # Required setting validation
59
+ # ------------------------------------------------------------------
60
+ if definition.required and value in ("", None):
61
+ messages.append(
62
+ Error(
63
+ f"{setting_name} must not be empty.",
64
+ id=CheckIDs.REQUIRED_SETTING,
65
+ )
66
+ )
67
+
68
+ # ------------------------------------------------------------------
69
+ # Deprecation warning
70
+ # ------------------------------------------------------------------
71
+ if definition.deprecated:
72
+ message = f"{setting_name} is deprecated"
73
+
74
+ if definition.since:
75
+ message += f" since version {definition.since}"
76
+
77
+ if definition.removed_in:
78
+ message += f" and will be removed in version {definition.removed_in}"
79
+
80
+ message += "."
81
+
82
+ messages.append(
83
+ Warning(
84
+ message,
85
+ id=CheckIDs.DEPRECATED_SETTING,
86
+ )
87
+ )
88
+
89
+ return messages
90
+
91
+
92
+ @register(Tags.compatibility)
93
+ def check_settings(
94
+ app_configs: list | None = None,
95
+ **kwargs: object,
96
+ ) -> list[CheckMessage]:
97
+ """
98
+ Validate all MCMS settings.
99
+
100
+ This check iterates over every setting defined by the framework and
101
+ validates its configured value.
102
+
103
+ Parameters
104
+ ----------
105
+ app_configs:
106
+ Django application configurations.
107
+
108
+ **kwargs:
109
+ Additional keyword arguments supplied by Django.
110
+
111
+ Returns
112
+ -------
113
+ list[CheckMessage]
114
+ Validation errors and warnings.
115
+ """
116
+ messages: list[CheckMessage] = []
117
+
118
+ for name, definition in SETTING_DEFINITIONS.items():
119
+ if not definition.check:
120
+ continue
121
+
122
+ messages.extend(
123
+ _check_setting(
124
+ name,
125
+ definition,
126
+ )
127
+ )
128
+
129
+ return messages
130
+
131
+
132
+ @register(Tags.compatibility)
133
+ def check_environment(
134
+ app_configs: list | None = None,
135
+ **kwargs: object,
136
+ ) -> list[CheckMessage]:
137
+ """
138
+ Validate the runtime environment.
139
+
140
+ Parameters
141
+ ----------
142
+ app_configs:
143
+ Django application configurations.
144
+
145
+ **kwargs:
146
+ Additional keyword arguments supplied by Django.
147
+
148
+ Returns
149
+ -------
150
+ list[CheckMessage]
151
+ Environment-related issues.
152
+ """
153
+ return []
154
+
155
+
156
+ @register(Tags.compatibility)
157
+ def check_framework(
158
+ app_configs: list | None = None,
159
+ **kwargs: object,
160
+ ) -> list[CheckMessage]:
161
+ """
162
+ Validate internal framework state.
163
+
164
+ Future versions of this check will validate framework registries,
165
+ plugin compatibility, and other runtime configuration.
166
+
167
+ Parameters
168
+ ----------
169
+ app_configs:
170
+ Django application configurations.
171
+
172
+ **kwargs:
173
+ Additional keyword arguments supplied by Django.
174
+
175
+ Returns
176
+ -------
177
+ list[CheckMessage]
178
+ Framework-related issues.
179
+ """
180
+ return []
mcms_core/constants.py ADDED
@@ -0,0 +1,25 @@
1
+ """
2
+ Framework-wide constants.
3
+ """
4
+
5
+ from typing import Final
6
+
7
+ # Core Settings
8
+ PACKAGE_NAME: str = "django-mcms"
9
+
10
+ DEFAULT_LANGUAGE: str = "en"
11
+
12
+ DEFAULT_TIMEZONE: str = "Africa/Nairobi"
13
+
14
+ MCMS_PREFIX: Final[str] = "MCMS"
15
+
16
+
17
+ # Check Codes
18
+ class CheckIDs:
19
+ # Error Codes
20
+ CHECK_INVALID_SETTING: Final = "mcms.E001"
21
+ CHECK_UNKNOWN_SETTING: Final = "mcms.E002"
22
+ CHECK_EMPTY_SITE_NAME: Final = "mcms.E003"
23
+
24
+ # Warning Codes
25
+ CHECK_CACHE_DISABLED: Final = "mcms.W001"
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Callable
5
+ from types import MappingProxyType
6
+
7
+ from mcms_core.validators import validate_bool, validate_int, validate_str
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class SettingDefinition:
12
+ """
13
+ Defines a single MCMS setting.
14
+ """
15
+
16
+ default: Any
17
+ validator: Callable[[str, Any], Any]
18
+ description: str
19
+ since: str
20
+
21
+ required: bool = False
22
+
23
+ deprecated: bool = False
24
+ removed_in: str | None = None
25
+
26
+ check: bool = True
27
+
28
+
29
+ SETTING_DEFINITIONS = MappingProxyType(
30
+ {
31
+ "SITE_NAME": SettingDefinition(
32
+ default="MCMS",
33
+ validator=validate_str,
34
+ description="Name of the website.",
35
+ since="0.1.0",
36
+ required=True,
37
+ ),
38
+ "ENABLE_CACHE": SettingDefinition(
39
+ default=True,
40
+ validator=validate_bool,
41
+ since="0.1.0",
42
+ description="Enable framework caching.",
43
+ ),
44
+ "JSON_INDENT": SettingDefinition(
45
+ default=4,
46
+ validator=lambda n, v: validate_int(
47
+ n,
48
+ v,
49
+ minimum=0,
50
+ ),
51
+ since="0.1.0",
52
+ description="Indentation used when exporting JSON.",
53
+ ),
54
+ }
55
+ )
@@ -0,0 +1,109 @@
1
+ """
2
+ Editor event collection and callback dispatch.
3
+ """
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ import logging
9
+
10
+ from mcms_core.events import MCMSEvent, Severity
11
+
12
+
13
+ EventCallback = Callable[[MCMSEvent], None]
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ class MCMSEventCollector:
18
+ """Collect editor events and notify interested subscribers."""
19
+
20
+ def __init__(self) -> None:
21
+ self._events: list[MCMSEvent] = []
22
+ self._callbacks: list[EventCallback] = []
23
+
24
+ def count(self) -> int:
25
+ return len(self._events)
26
+
27
+ def subscribe(self, callback: EventCallback) -> None:
28
+ """Subscribe a callback to newly recorded events."""
29
+ if callback not in self._callbacks:
30
+ self._callbacks.append(callback)
31
+
32
+ def unsubscribe(self, callback: EventCallback) -> None:
33
+ """Remove a previously registered callback."""
34
+ if callback in self._callbacks:
35
+ self._callbacks.remove(callback)
36
+
37
+ def clear(self) -> None:
38
+ """Clear the collected events and reset the subscriber list."""
39
+ self._events.clear()
40
+ self._callbacks.clear()
41
+
42
+ def emit(
43
+ self,
44
+ *,
45
+ severity: Severity,
46
+ code: str,
47
+ message: str,
48
+ operation: str,
49
+ details: str | None = None,
50
+ traceback: str | None = None,
51
+ ) -> MCMSEvent:
52
+ """Record an event and notify subscribers."""
53
+ event = MCMSEvent(
54
+ severity=severity,
55
+ code=code,
56
+ message=message,
57
+ operation=operation,
58
+ details=details,
59
+ traceback=traceback,
60
+ )
61
+
62
+ self._events.append(event)
63
+
64
+ for callback in tuple(self._callbacks):
65
+ try:
66
+ callback(event)
67
+ except Exception:
68
+ # A broken subscriber must not interrupt the operation.
69
+ # Production code should also log this failure.
70
+ pass
71
+
72
+ if severity == Severity.ERROR:
73
+ self.report_editor_error(
74
+ message=message,
75
+ operation=operation,
76
+ traceback=traceback or "No traceback available.",
77
+ )
78
+
79
+ return event
80
+
81
+ def report_editor_error(
82
+ self,
83
+ message: str,
84
+ operation: str,
85
+ traceback: str,
86
+ ) -> None:
87
+ """
88
+ Log an exception normally and record an editor-facing error event.
89
+
90
+ The exception is not re-raised by this helper. Callers should only
91
+ use this behavior when they have deliberately decided the failure
92
+ is recoverable.
93
+ """
94
+ logger.error("%s failed: %s\n%s", operation, message, traceback)
95
+
96
+ @property
97
+ def events(self) -> tuple[MCMSEvent, ...]:
98
+ """Return an immutable snapshot of collected events."""
99
+ return tuple(self._events)
100
+
101
+ def serialize(
102
+ self,
103
+ *,
104
+ include_traceback: bool = False,
105
+ ) -> list[dict[str, Any]]:
106
+ """Serialize the collected events for an editor response."""
107
+ return [
108
+ event.to_dict(include_traceback=include_traceback) for event in self._events
109
+ ]
mcms_core/events.py ADDED
@@ -0,0 +1,76 @@
1
+ """
2
+ Structured events for MCMS editor operations.
3
+
4
+ Events provide a consistent interface for reporting operation outcomes
5
+ to editor interfaces without replacing Python's logging system.
6
+ """
7
+
8
+ from dataclasses import asdict, dataclass, field
9
+ from datetime import datetime, timezone
10
+ from enum import StrEnum
11
+ from traceback import format_exception
12
+ from typing import Any
13
+ from uuid import uuid4
14
+
15
+
16
+ class Severity(StrEnum):
17
+ """Severity levels supported by MCMS editor events."""
18
+
19
+ DEBUG = "debug"
20
+ INFO = "info"
21
+ SUCCESS = "success"
22
+ WARNING = "warning"
23
+ ERROR = "error"
24
+ FATAL = "fatal"
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class MCMSEvent:
29
+ """A structured diagnostic event produced by an MCMS operation."""
30
+
31
+ severity: Severity
32
+ code: str
33
+ message: str
34
+ operation: str
35
+
36
+ id: str = field(default_factory=lambda: str(uuid4()))
37
+ timestamp: datetime = field(
38
+ default_factory=lambda: datetime.now(timezone.utc),
39
+ )
40
+ details: str | None = None
41
+ traceback: str | None = None
42
+
43
+ def to_dict(
44
+ self,
45
+ *,
46
+ include_traceback: bool = False,
47
+ ) -> dict[str, Any]:
48
+ """
49
+ Return a JSON-compatible event representation.
50
+
51
+ Tracebacks are excluded unless explicitly authorized by the
52
+ caller. The frontend should never receive raw exception details
53
+ by default.
54
+ """
55
+ event = asdict(self)
56
+
57
+ event["severity"] = self.severity.value
58
+ event["timestamp"] = self.timestamp.isoformat()
59
+
60
+ if not include_traceback:
61
+ event["traceback"] = None
62
+
63
+ return event
64
+
65
+
66
+ def format_exception_traceback(
67
+ exception: BaseException,
68
+ ) -> str:
69
+ """Format an exception using Python's standard traceback format."""
70
+ return "".join(
71
+ format_exception(
72
+ type(exception),
73
+ exception,
74
+ exception.__traceback__,
75
+ )
76
+ )
@@ -0,0 +1,54 @@
1
+ """
2
+ Framework-wide exception hierarchy for django-mcms.
3
+
4
+ All framework packages should inherit from these exceptions rather
5
+ than raising generic Python exceptions.
6
+ """
7
+
8
+
9
+ # Base Exception
10
+ class MCMSError(Exception):
11
+ """Base exception for all django-mcms errors."""
12
+
13
+
14
+ # Configuration Errors
15
+ class ConfigurationError(MCMSError):
16
+ """Raised when the framework configuration is invalid."""
17
+
18
+
19
+ # Registry Errors
20
+ class RegistryError(MCMSError):
21
+ """Raised when an error occurs while interacting with a registry."""
22
+
23
+
24
+ class RegistryItemAlreadyRegisteredError(RegistryError):
25
+ """Raised when attempting to register an item that is already registered."""
26
+
27
+
28
+ class RegistryItemNotFoundError(RegistryError):
29
+ """Raised when attempting to access an item that is not registered."""
30
+
31
+
32
+ # Validation Errors
33
+ class ValidationError(MCMSError):
34
+ """Raised when framework-level validation fails."""
35
+
36
+
37
+ # Validation Errors
38
+ class SerializationError(MCMSError):
39
+ """Raised when serialization or deserialization fails."""
40
+
41
+
42
+ # Discovery Errors
43
+ class DiscoveryError(MCMSError):
44
+ """Raised when automatic discovery of framework resources fails."""
45
+
46
+
47
+ # Dependency Errors
48
+ class DependencyError(MCMSError):
49
+ """Raised when a required dependency is unavailable or incompatible."""
50
+
51
+
52
+ # Package Errors
53
+ class PackageError(MCMSError):
54
+ """Raised when a package cannot be loaded or initialized."""
@@ -0,0 +1,20 @@
1
+ """
2
+ Public model API for MCMS Core.
3
+ """
4
+
5
+ from .base import BaseModel
6
+ from .ordered import OrderedModel
7
+ from .published import PublishedModel
8
+ from .timestamped import TimestampedModel
9
+
10
+ # from .trackable import TrackableModel
11
+ from .uuid import UUIDModel
12
+
13
+ __all__ = [
14
+ "BaseModel",
15
+ "OrderedModel",
16
+ "PublishedModel",
17
+ "TimestampedModel",
18
+ # "TrackableModel",
19
+ "UUIDModel",
20
+ ]
@@ -0,0 +1,25 @@
1
+ """
2
+ Base model definitions for django-mcms.
3
+
4
+ This module contains the root abstract model from which all
5
+ framework model mixins inherit.
6
+ """
7
+
8
+ from django.db import models
9
+
10
+
11
+ class BaseModel(models.Model):
12
+ """
13
+ Root abstract model for all MCMS models.
14
+
15
+ This class intentionally provides no fields.
16
+
17
+ It exists to provide a common inheritance point for all
18
+ framework models and allows shared behaviour to be introduced
19
+ in one place in the future without modifying every model.
20
+ """
21
+
22
+ class Meta:
23
+ """Django model metadata."""
24
+
25
+ abstract = True
@@ -0,0 +1,22 @@
1
+ """
2
+ Ordering model mixin.
3
+ """
4
+
5
+ from django.db import models
6
+
7
+ from .base import BaseModel
8
+
9
+
10
+ class OrderedModel(BaseModel):
11
+ """
12
+ Adds a sortable integer field.
13
+ """
14
+
15
+ order: models.PositiveIntegerField = models.PositiveIntegerField(
16
+ default=0,
17
+ db_index=True,
18
+ help_text="Defines the display order.",
19
+ )
20
+
21
+ class Meta:
22
+ abstract = True
@@ -0,0 +1,30 @@
1
+ """
2
+ Publishing model mixins.
3
+ """
4
+
5
+ from django.db import models
6
+
7
+ from .base import BaseModel
8
+
9
+
10
+ class PublishedModel(BaseModel):
11
+ """
12
+ Adds publication metadata.
13
+ """
14
+
15
+ is_published: models.BooleanField = models.BooleanField(
16
+ default=False,
17
+ )
18
+
19
+ published_at: models.DateTimeField = models.DateTimeField(
20
+ null=True,
21
+ blank=True,
22
+ )
23
+
24
+ unpublished_at: models.DateTimeField = models.DateTimeField(
25
+ null=True,
26
+ blank=True,
27
+ )
28
+
29
+ class Meta:
30
+ abstract = True
@@ -0,0 +1,26 @@
1
+ """
2
+ Timestamp model mixins.
3
+ """
4
+
5
+ from django.db import models
6
+
7
+ from .base import BaseModel
8
+
9
+
10
+ class TimestampedModel(BaseModel):
11
+ """
12
+ Automatically tracks creation and modification timestamps.
13
+ """
14
+
15
+ created_at: models.DateTimeField = models.DateTimeField(
16
+ auto_now_add=True,
17
+ help_text="The date and time this record was created.",
18
+ )
19
+
20
+ updated_at: models.DateTimeField = models.DateTimeField(
21
+ auto_now=True,
22
+ help_text="The date and time this record was last modified.",
23
+ )
24
+
25
+ class Meta:
26
+ abstract = True
@@ -0,0 +1,35 @@
1
+ # """
2
+ # Audit tracking model mixins.
3
+ # """
4
+
5
+ # from django.conf import settings
6
+ # from django.db import models
7
+
8
+ # from .timestamped import TimestampedModel
9
+
10
+
11
+ # class TrackableModel(TimestampedModel):
12
+ # """
13
+ # Tracks the users responsible for creating and updating a record.
14
+ # """
15
+
16
+ # created_by = models.ForeignKey(
17
+ # settings.AUTH_USER_MODEL,
18
+ # null=True,
19
+ # blank=True,
20
+ # editable=False,
21
+ # related_name="%(class)s_created",
22
+ # on_delete=models.SET_NULL,
23
+ # )
24
+
25
+ # updated_by = models.ForeignKey(
26
+ # settings.AUTH_USER_MODEL,
27
+ # null=True,
28
+ # blank=True,
29
+ # editable=False,
30
+ # related_name="%(class)s_updated",
31
+ # on_delete=models.SET_NULL,
32
+ # )
33
+
34
+ # class Meta:
35
+ # abstract = True
@@ -0,0 +1,27 @@
1
+ """
2
+ UUID model mixin.
3
+ """
4
+
5
+ import uuid
6
+
7
+ from django.db import models
8
+
9
+ from .base import BaseModel
10
+
11
+
12
+ class UUIDModel(BaseModel):
13
+ """
14
+ Adds a UUID primary key.
15
+
16
+ This mixin should be used whenever a globally unique identifier
17
+ is preferred over Django's default auto-incrementing integer.
18
+ """
19
+
20
+ id: models.UUIDField = models.UUIDField(
21
+ primary_key=True,
22
+ default=uuid.uuid4,
23
+ editable=False,
24
+ )
25
+
26
+ class Meta:
27
+ abstract = True
mcms_core/py.typed ADDED
File without changes
mcms_core/registry.py ADDED
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Generic, Iterator, TypeVar
4
+
5
+ from mcms_core.exceptions import (
6
+ RegistryItemAlreadyRegisteredError,
7
+ RegistryItemNotFoundError,
8
+ )
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ class Registry(Generic[T]):
14
+ """
15
+ Generic registry for django-mcms.
16
+ """
17
+
18
+ def __init__(self) -> None:
19
+ self._items: dict[str, T] = {}
20
+
21
+ def register(self, name: str, item: T) -> None:
22
+ if name in self._items:
23
+ raise RegistryItemAlreadyRegisteredError(f"'{name}' is already registered.")
24
+
25
+ self._items[name] = item
26
+
27
+ def get(self, name: str) -> T:
28
+ try:
29
+ return self._items[name]
30
+ except KeyError as exc:
31
+ raise RegistryItemNotFoundError(f"'{name}' is not registered.") from exc
32
+
33
+ def unregister(self, name: str) -> None:
34
+ try:
35
+ deleted_item = self._items[name]
36
+ del self._items[name]
37
+ return deleted_item
38
+ except KeyError as exc:
39
+ raise RegistryItemNotFoundError(f"'{name}' is not registered.") from exc
40
+
41
+ def clear(self) -> None:
42
+ self._items.clear()
43
+
44
+ def update(self, name: str, value: T):
45
+ if name not in self._items.keys():
46
+ raise RegistryItemNotFoundError(f"'{name}' is not registered.")
47
+ self._items[name] = value
48
+
49
+ def keys(self):
50
+ return self._items.keys()
51
+
52
+ def values(self):
53
+ return self._items.values()
54
+
55
+ def items(self):
56
+ return self._items.items()
57
+
58
+ def __str__(self):
59
+ return str(self._items)
60
+
61
+ def __contains__(self, name: object) -> bool:
62
+ return name in self._items
63
+
64
+ def __getitem__(self, name: str) -> T:
65
+ return self.get(name)
66
+
67
+ def __len__(self) -> int:
68
+ return len(self._items)
69
+
70
+ def __iter__(self) -> Iterator[str]:
71
+ return iter(self._items)
72
+
73
+ def __eq__(
74
+ self,
75
+ other: Registry,
76
+ ) -> bool:
77
+ if not isinstance(
78
+ other,
79
+ Registry,
80
+ ):
81
+ return NotImplemented
82
+
83
+ return self._items == other._items
84
+
85
+ def serialize(self) -> dict[str, str]:
86
+ """
87
+ Serialize the registry to a dictionary.
88
+ """
89
+ return {name: item.serialize() for name, item in self._items.items()}
mcms_core/settings.py ADDED
@@ -0,0 +1,63 @@
1
+ """
2
+ Settings wrapper for django-mcms.
3
+
4
+ The wrapper provides a typed interface over Django's settings object,
5
+ falling back to sensible defaults where necessary.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ from django.conf import settings as django_settings
13
+
14
+ from mcms_core.constants import MCMS_PREFIX
15
+
16
+ from mcms_core.definitions import SETTING_DEFINITIONS
17
+
18
+
19
+ class MCMSSettings:
20
+ """
21
+ Provides access to django-mcms settings.
22
+
23
+ Settings are resolved dynamically from Django's global settings,
24
+ allowing Django's ``override_settings()`` utility to work correctly
25
+ during tests.
26
+ """
27
+
28
+ def __getattr__(self, name: str) -> Any:
29
+ """
30
+ Retrieve a setting.
31
+
32
+ Parameters
33
+ ----------
34
+ name:
35
+ Name of the setting without the ``MCMS_`` prefix.
36
+
37
+ Returns
38
+ -------
39
+ Any
40
+ The configured value or its default.
41
+ """
42
+ setting_name = f"{MCMS_PREFIX}_{name}"
43
+
44
+ definition = SETTING_DEFINITIONS.get(name)
45
+
46
+ # Identify unknown settings and raise an exception to prevent typos.
47
+ if definition is None:
48
+ raise AttributeError(f"Unknown MCMS setting '{name}'.")
49
+
50
+ validator = definition.validator
51
+ value = getattr(
52
+ django_settings,
53
+ setting_name,
54
+ definition.default,
55
+ )
56
+
57
+ if validator is not None:
58
+ value = validator(setting_name, value)
59
+
60
+ return value
61
+
62
+
63
+ mcms_settings = MCMSSettings()
@@ -0,0 +1,69 @@
1
+ """
2
+ Validation utilities for django-mcms settings.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Any
8
+
9
+ from django.core.exceptions import ImproperlyConfigured
10
+
11
+
12
+ def validate_bool(name: str, value: Any) -> bool:
13
+ """
14
+ Validate that a setting is a boolean.
15
+
16
+ Parameters
17
+ ----------
18
+ name:
19
+ Setting name.
20
+
21
+ value:
22
+ Value to validate.
23
+
24
+ Returns
25
+ -------
26
+ bool
27
+ The validated value.
28
+
29
+ Raises
30
+ ------
31
+ ImproperlyConfigured
32
+ If the value is not a boolean.
33
+ """
34
+ if not isinstance(value, bool):
35
+ raise ImproperlyConfigured(f"{name} must be a boolean.")
36
+
37
+ return value
38
+
39
+
40
+ def validate_int(
41
+ name: str,
42
+ value: Any,
43
+ *,
44
+ minimum: int | None = None,
45
+ maximum: int | None = None,
46
+ ) -> int:
47
+ """
48
+ Validate an integer setting.
49
+ """
50
+ if not isinstance(value, int):
51
+ raise ImproperlyConfigured(f"{name} must be an integer.")
52
+
53
+ if minimum is not None and value < minimum:
54
+ raise ImproperlyConfigured(f"{name} must be at least {minimum}.")
55
+
56
+ if maximum is not None and value > maximum:
57
+ raise ImproperlyConfigured(f"{name} must be at most {maximum}.")
58
+
59
+ return value
60
+
61
+
62
+ def validate_str(name: str, value: Any) -> str:
63
+ """
64
+ Validate a string setting.
65
+ """
66
+ if not isinstance(value, str):
67
+ raise ImproperlyConfigured(f"{name} must be a string.")
68
+
69
+ return value
@@ -0,0 +1,81 @@
1
+ Metadata-Version: 2.3
2
+ Name: mcms-core
3
+ Version: 0.1.0
4
+ Summary: Provides shared infrastructure and foundational abstractions used across the Modular CMS packages
5
+ Author: MikemathuKE
6
+ Author-email: MikemathuKE <michaelmathu6@gmail.com>
7
+ Requires-Dist: django>=6.0
8
+ Requires-Python: >=3.13
9
+ Description-Content-Type: text/markdown
10
+
11
+ # MCMS Core
12
+
13
+ `mcms_core` provides shared infrastructure and foundational abstractions used across the Modular CMS packages. It is intended to contain cross-cutting primitives rather than features belonging to a specific CMS domain.
14
+
15
+ ## Responsibilities
16
+
17
+ The ADRs establish the following shared concerns:
18
+
19
+ - Common exception hierarchy.
20
+ - Shared registry abstraction and its registration contract.
21
+ - Foundational infrastructure used by higher-level packages.
22
+
23
+ Package-specific behaviour should remain in the package that owns that domain.
24
+
25
+ ## Registry contract
26
+
27
+ MCMS registries follow the shared registration convention:
28
+
29
+ ```python
30
+ registry.register(name, item)
31
+ ```
32
+
33
+ A registry associates a name with an item. Package-specific registries may extend the common registry, but should not introduce incompatible registration conventions or assume singleton behaviour unless a separate decision explicitly establishes it.
34
+
35
+ ## Exception hierarchy
36
+
37
+ The exception ADR defines `MCMSError` as the common MCMS exception base and identifies these categories:
38
+
39
+ | Exception | Purpose |
40
+ |---|---|
41
+ | `MCMSError` | Base exception for MCMS errors |
42
+ | `ConfigurationError` | Invalid or unusable configuration |
43
+ | `RegistryError` | Registry-related failures |
44
+ | `ValidationError` | Invalid domain or input data |
45
+ | `SerializationError` | Serialization and deserialization failures |
46
+ | `DependencyError` | Missing or invalid dependencies |
47
+
48
+ Use the package's actual exported names and constructor signatures as defined by the implementation.
49
+
50
+ ## Architectural integrations
51
+
52
+ `mcms_core` is a foundational package. Other MCMS packages may depend on it for shared abstractions such as registries and exceptions. It should not depend on higher-level packages such as the editor, pages, templates, or rendering implementation.
53
+
54
+ ```text
55
+ Higher-level MCMS packages
56
+ |
57
+ v
58
+ mcms_core
59
+ ```
60
+
61
+ ## Application configuration
62
+
63
+ The ADRs do not define a global application setting or path for `mcms_core`. It should not require the host `apps/` directory merely to use its foundational Python abstractions. Add application-specific references only if the implementation introduces a documented integration.
64
+
65
+ ## Dependencies
66
+
67
+ ### Architectural integrations
68
+
69
+ This package is intended to be a low-level dependency for other MCMS packages. Avoid introducing dependencies on domain-specific packages.
70
+
71
+ ### Python distribution dependencies
72
+
73
+ All MCMS Packages rely on django
74
+
75
+ ## Development
76
+
77
+ ```bash
78
+ uv run pytest packages/mcms-core/tests
79
+ ```
80
+
81
+ Run Ruff and mypy using the repository's configured commands.
@@ -0,0 +1,22 @@
1
+ mcms_core/__init__.py,sha256=1-rdAWVNqYIaw2oA2ei5MfEfQcGQo6izuTfhkxQEXr4,806
2
+ mcms_core/apps.py,sha256=XQ3uUdf8FmUGzxS91etOmDjiGyJBNutf44eLetaJczs,660
3
+ mcms_core/checks.py,sha256=4kfksIEdOkLQb7YIHgzqkUykonXM2_eDLZXkZ4t6aac,4524
4
+ mcms_core/constants.py,sha256=Rn9pnk70iqWY9yFIRrL2kWlwd-2s49Jj2sHYT8aWkf4,500
5
+ mcms_core/definitions.py,sha256=PuBjN-R4BTTcsIADEHan_2UCuAfDYnGg4nvPsxiSz2A,1361
6
+ mcms_core/event_collector.py,sha256=5qNfYikWXLjNFcgRIFcQ0nuVAdhGEQ4AFpKnxSUWdmA,3235
7
+ mcms_core/events.py,sha256=B1ky9YqHeL0gnKJPG8EzgG-o89zukBZRZy0Ww_FBivk,1976
8
+ mcms_core/exceptions.py,sha256=t-W1DTlaIpYFEJxaiqhXjrg5CATM9eeX9TF8NF7DucQ,1442
9
+ mcms_core/models/__init__.py,sha256=jRUFvB9YbU1RbEOuKFUXs0pRrwkRqs6fupEemaPoe9c,411
10
+ mcms_core/models/base.py,sha256=8MnKxye8Ya7-ubhlVJMKEQIg5Uhp0BLESsMd7nh6C98,608
11
+ mcms_core/models/ordered.py,sha256=SZ2y8Imo_9Gb0AZIVWLobDPAnFLCUenoPUgPZcqBenA,403
12
+ mcms_core/models/published.py,sha256=2Ypy3rR3S3BfM47dIYxdoGJay4fEMyZVwcwYthtAOeQ,556
13
+ mcms_core/models/timestamped.py,sha256=fsN2LVfCEYsC8jh6NYfawQaZ5hatwpggG9ikfHIpIOY,594
14
+ mcms_core/models/trackable.py,sha256=lNLGpezoeIslN_Z3zn7Un-2JeSS0IDms8ZORiwIhrPQ,836
15
+ mcms_core/models/uuid.py,sha256=FXWjO07j5_W1xhhTHjQpYfPlNguG16D-wPqUP_8bjTU,506
16
+ mcms_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ mcms_core/registry.py,sha256=mY07IVGmVAvFvDDP937VBbkOf8UmXM1G7q9-BiIDzZg,2354
18
+ mcms_core/settings.py,sha256=_Kg8B_aDy9gbdlYBMGbsKrVg6xENUUEwsPu4c_w7Mz0,1571
19
+ mcms_core/validators.py,sha256=2Jyq1cG4u9Fu4RKDR2Mam8CUoglIAlz7I3pHPCG_Fv4,1481
20
+ mcms_core-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
21
+ mcms_core-0.1.0.dist-info/METADATA,sha256=gLsDmhjiHXyuMvCpgA9V0av7fq-dWKCKJmSjyuV_jdM,2895
22
+ mcms_core-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any