Newer
Older
from __future__ import annotations
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import datetime
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, Literal, TypeAlias
from django.core.exceptions import ObjectDoesNotExist
from django.utils.html import escape
from django.utils.translation import gettext as _
ATTRIBUTES_FILENAME,
DEFAULT_ACCESS_KINDS,
FLOW_SESSION_EXPIRATION_MODE_CHOICES,
from relate.utils import Struct, string_concat
Andreas Klöckner
committed
# {{{ mypy
if TYPE_CHECKING:
from course.models import Course
from relate.utils import Repo_ish
Andreas Klöckner
committed
# }}}
__doc__ = """
.. autoclass:: ValidationContext
.. autofunction:: validate_struct
Stub Docs
=========
.. class:: Course
.. class:: Repo_ish
"""
# {{{ validation tools
class ValidationError(RuntimeError):
pass
ID_RE = re.compile(r"^[\w]+$")
def validate_identifier(
vctx: ValidationContext, location: str, s: str, warning_only: bool = False
) -> None:
Andreas Klöckner
committed
if warning_only:
msg = (string_concat(
_("invalid identifier"),
" '%(string)s'")
% {"location": location, "string": s})
Andreas Klöckner
committed
vctx.add_warning(location, msg)
Andreas Klöckner
committed
else:
msg = (string_concat(
"%(location)s: ",
_("invalid identifier"),
" '%(string)s'")
% {"location": location, "string": s})
Andreas Klöckner
committed
raise ValidationError(msg)
def validate_role(vctx: ValidationContext, location: str, role: str) -> None:
Andreas Klöckner
committed
if vctx.course is not None:
from course.models import ParticipationRole
roles = ParticipationRole.objects.filter(course=vctx.course).values_list(
"identifier", flat=True)
if role not in roles:
raise ValidationError(
string_concat("%(location)s: ",
_("invalid role '%(role)s'"))
% {"location": location, "role": role})
def validate_facility(
vctx: ValidationContext, location: str, facility: str) -> None:
from course.utils import get_facilities_config
facilities = get_facilities_config()
if facilities is None:
return
if facility not in facilities:
vctx.add_warning(location, _(
"Name of facility not recognized: '%(fac_name)s'. "
"Known facility names: '%(known_fac_names)s'")
% {
"fac_name": facility,
"known_fac_names": ", ".join(facilities),
})
def validate_participationtag(
vctx: ValidationContext, location: str, participationtag: str) -> None:
if vctx.course is not None:
from pytools import memoize_in
@memoize_in(vctx, "available_participation_tags")
def get_ptag_list(vctx: ValidationContext) -> list[str]:
from course.models import ParticipationTag
return list(
ParticipationTag.objects.filter(course=vctx.course)
.values_list("name", flat=True))
ptag_list = get_ptag_list(vctx)
if participationtag not in ptag_list:
vctx.add_warning(
location,
_(
"Name of participation tag not recognized: '%(ptag_name)s'. "
"Known participation tag names: '%(known_ptag_names)s'")
% {
"ptag_name": participationtag,
"known_ptag_names": ", ".join(ptag_list),
})
AttrSpec: TypeAlias = Sequence[tuple[str, type | tuple[type, ...] | Literal["markup"]]]
Andreas Klöckner
committed
def validate_struct(
vctx: ValidationContext,
location: str,
obj: Any,
required_attrs: AttrSpec,
allowed_attrs: AttrSpec,
) -> None:
Andreas Klöckner
committed
"""
:arg required_attrs: an attribute validation list (see below)
:arg allowed_attrs: an attribute validation list (see below)
An attribute validation list is a list of elements, where each element is
either a string (the name of the attribute), in which case the type of each
attribute is not checked, or a tuple *(name, type)*, where type is valid
as a second argument to :func:`isinstance`.
"""
if not isinstance(obj, Struct):
raise ValidationError(
f"{location}: not a key-value map")
present_attrs = {name for name in dir(obj) if not name.startswith("_")}
for required, attr_list in [
(True, required_attrs),
(False, allowed_attrs),
]:
if attr not in present_attrs:
if required:
raise ValidationError(
string_concat("%(location)s: ",
_("attribute '%(attr)s' missing"))
% {"location": location, "attr": attr})
else:
present_attrs.remove(attr)
val = getattr(obj, attr)
is_markup = False
if allowed_types == "markup":
allowed_types = str
is_markup = True
Loading
Loading full blame...