Newer
Older
from __future__ import division, print_function
__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 re
import datetime
import six
from django.core.exceptions import ObjectDoesNotExist
from django.utils.html import escape
from django.utils.translation import (
ugettext_lazy as _, ugettext, string_concat)
from course.content import get_repo_blob
Andreas Klöckner
committed
# {{{ mypy
from typing import Any, Tuple, Optional, Text # noqa
if False:
from relate.utils import Repo_ish # noqa
from course.models import Course # noqa
# }}}
# {{{ validation tools
class ValidationError(RuntimeError):
pass
ID_RE = re.compile(r"^[\w]+$")
def validate_identifier(vctx, location, s, warning_only=False):
Andreas Klöckner
committed
# type: (ValidationContext, Text, Text, bool) -> None
Andreas Klöckner
committed
if warning_only:
msg = (string_concat(
_("invalid identifier"),
" '%(string)s'")
% {'location': location, 'string': s})
vctx.add_warning(location, msg)
Andreas Klöckner
committed
else:
msg = (string_concat(
"%(location)s: ",
_("invalid identifier"),
" '%(string)s'")
% {'location': location, 'string': s})
raise ValidationError(msg)
Andreas Klöckner
committed
def validate_role(vctx, location, role):
# type: (ValidationContext, Text, Text) -> 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, location, facility):
Andreas Klöckner
committed
# type: (ValidationContext, Text, Text) -> 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),
})
Andreas Klöckner
committed
def validate_struct(
vctx, # type: ValidationContext
location, # type: Text
obj, # type: Any
required_attrs, # type: List[Tuple[Text, Any]]
allowed_attrs, # type: List[Tuple[Text, Any]]
):
# type: (...) -> None
"""
: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(
"%s: not a key-value map" % location)
present_attrs = set(name for name in dir(obj) if not name.startswith("_"))
for required, attr_list in [
(True, required_attrs),
(False, allowed_attrs),
]:
for attr_rec in attr_list:
if isinstance(attr_rec, tuple):
attr, allowed_types = attr_rec
else:
attr = attr_rec
allowed_types = None
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
if allowed_types == str:
# Love you, too, Python 2.
if not isinstance(val, allowed_types):
raise ValidationError(
string_concat("%(location)s: ",
_("attribute '%(attr)s' has "
"wrong type: got '%(name)s', "
"expected '%(allowed)s'"))
% {
'location': location,
'attr': attr,
'name': type(val).__name__,
'allowed': escape(str(allowed_types))})
validate_markup(vctx, "%s: attribute %s" % (location, attr), val)
raise ValidationError(
string_concat("%(location)s: ",
_("extraneous attribute(s) '%(attr)s'"))
% {'location': location, 'attr': ",".join(present_attrs)})
datespec_types = (datetime.date, six.string_types, datetime.datetime)
Andreas Klöckner
committed
class ValidationWarning(object):
def __init__(self, location, text):
Andreas Klöckner
committed
# type: (Optional[Text], Text) -> None
Andreas Klöckner
committed
self.location = location
self.text = text
Loading
Loading full blame...