Init Project Flexly CMS
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
"""ContentService: безопасная запись файлов сайта (ADR-004).
|
||||
|
||||
Путь записи: блокировка сайта → проверка if_match → проверка синтаксиса → история →
|
||||
атомарная запись. Права (scope) ограничиваются `allowed_prefixes`: для роли editor и
|
||||
агента это `pages/`, `content/`, `data/`, `menus/`, `assets/`; код (`fragments/`,
|
||||
`layouts/`, схемы) им недоступен.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ..errors import ConflictError, EngineError, Report, UnsafePathError
|
||||
from ..parsing import frontmatter
|
||||
from ..parsing.yamlio import YamlError, load_yaml
|
||||
from ..storage.fs import atomic_write, etag_of, file_etag, safe_join
|
||||
from ..storage.history import save_previous
|
||||
from ..storage.locks import SiteLock
|
||||
|
||||
CONTENT_PREFIXES = ("pages/", "content/", "data/", "menus/", "assets/")
|
||||
ABSENT = "absent" # if_match для создания нового файла
|
||||
|
||||
|
||||
class ContentService:
|
||||
def __init__(self, root: Path, allowed_prefixes: tuple[str, ...] | None = None):
|
||||
self.root = Path(root)
|
||||
self.allowed_prefixes = allowed_prefixes
|
||||
|
||||
def _resolve(self, rel: str) -> Path:
|
||||
path = safe_join(self.root, rel)
|
||||
if self.allowed_prefixes is not None and not rel.startswith(self.allowed_prefixes):
|
||||
raise UnsafePathError(f"запись в «{rel}» не разрешена для этой роли")
|
||||
return path
|
||||
|
||||
def read(self, rel: str) -> tuple[str, str]:
|
||||
"""(текст, etag)."""
|
||||
path = safe_join(self.root, rel)
|
||||
data = path.read_bytes()
|
||||
return data.decode("utf-8"), etag_of(data)
|
||||
|
||||
@staticmethod
|
||||
def _check_syntax(rel: str, text: str) -> None:
|
||||
try:
|
||||
if rel.endswith(".md"):
|
||||
frontmatter.parse(text)
|
||||
elif rel.endswith((".yaml", ".yml")):
|
||||
load_yaml(text)
|
||||
except YamlError as exc:
|
||||
report = Report()
|
||||
report.add("E_YAML", str(exc), rel)
|
||||
raise EngineError(f"{rel}: синтаксическая ошибка", report) from exc
|
||||
|
||||
def write(self, rel: str, text: str, if_match: str) -> str:
|
||||
"""Записывает файл; возвращает новый etag. Конфликт версий → ConflictError (HTTP 409)."""
|
||||
path = self._resolve(rel)
|
||||
self._check_syntax(rel, text)
|
||||
with SiteLock(self.root):
|
||||
current = file_etag(path)
|
||||
expected = current if current is not None else ABSENT
|
||||
if if_match != expected:
|
||||
raise ConflictError(f"{rel}: файл изменился (ожидали {if_match}, сейчас {expected})", expected)
|
||||
save_previous(self.root, rel)
|
||||
atomic_write(path, text)
|
||||
return etag_of(text.encode("utf-8"))
|
||||
Reference in New Issue
Block a user