Skip to content
validation.py 54 KiB
Newer Older
from __future__ import annotations
Andreas Klöckner's avatar
Andreas Klöckner committed

__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
Andreas Klöckner's avatar
Andreas Klöckner committed
import re
from collections.abc import Sequence
from typing import TYPE_CHECKING, Any, Literal, TypeAlias
import dulwich.objects
from django.core.exceptions import ObjectDoesNotExist
from django.utils.html import escape
from django.utils.translation import gettext as _
Andreas Klöckner's avatar
Andreas Klöckner committed
from course.constants import (
    ATTRIBUTES_FILENAME,
    DEFAULT_ACCESS_KINDS,
    FLOW_SESSION_EXPIRATION_MODE_CHOICES,
Andreas Klöckner's avatar
Andreas Klöckner committed
    participation_permission as pperm,
)
from relate.utils import Struct, string_concat
Andreas Klöckner's avatar
Andreas Klöckner committed

    from course.models import Course
    from relate.utils import Repo_ish
Andreas Klöckner's avatar
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:
    if not ID_RE.match(s):

        if warning_only:
            msg = (string_concat(
                        _("invalid identifier"),
                        " '%(string)s'")
                    % {"location": location, "string": s})
            vctx.add_warning(location, msg)
        else:
            msg = (string_concat(
                        "%(location)s: ",
                        _("invalid identifier"),
                        " '%(string)s'")
                    % {"location": location, "string": s})
def validate_role(vctx: ValidationContext, location: str, role: str) -> None:
    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"]]]


        vctx: ValidationContext,
        location: str,
        obj: Any,
        required_attrs: AttrSpec,
        allowed_attrs: AttrSpec,
    """
    :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),
            ]:
        for attr, allowed_types in attr_list:
            if attr not in present_attrs:
                if required:
                            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...