Skip to content
validation.py 34.8 KiB
Newer Older
# -*- coding: utf-8 -*-

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's avatar
Andreas Klöckner committed
from relate.utils import Struct

# {{{ validation tools

class ValidationError(RuntimeError):
    pass


ID_RE = re.compile(r"^[\w]+$")


def validate_identifier(ctx, location, s, warning_only=False):
    if not ID_RE.match(s):

        if warning_only:
            msg = (string_concat(
                        _("invalid identifier"),
                        " '%(string)s'")
                    % {'location': location, 'string': s})

            ctx.add_warning(location, msg)
        else:
            msg = (string_concat(
                        "%(location)s: ",
                        _("invalid identifier"),
                        " '%(string)s'")
                    % {'location': location, 'string': s})

            raise ValidationError(msg)


def validate_role(location, role):
    from course.constants import participation_role

    if role not in [
            participation_role.instructor,
            participation_role.teaching_assistant,
            participation_role.student,
            participation_role.unenrolled,
            ]:
                string_concat("%(location)s: ",
                    _("invalid role '%(role)s'"))
                % {'location': location, 'role': role})
def validate_struct(ctx, location, obj, required_attrs, allowed_attrs):
    """
    :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:
                            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.
                    allowed_types = six.string_types
                if not isinstance(val, allowed_types):
                            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))})
                if is_markup:
                    validate_markup(ctx, "%s: attribute %s" % (location, attr), val)

    if present_attrs:
                string_concat("%(location)s: ",
                    _("extraneous attribute(s) '%(attr)s'"))
                % {'location': location, 'attr': ",".join(present_attrs)})
datespec_types = (datetime.date, six.string_types, datetime.datetime)
class ValidationWarning(object):
    def __init__(self, location, text):
        self.location = location
        self.text = text


class ValidationContext(object):
    """
    .. attribute:: repo
    .. attribute:: commit_sha
        A :class:`course.models.Course` instance, or *None*, if no database
        is currently available.
    def __init__(self, repo, commit_sha, course=None):
        self.repo = repo
        self.commit_sha = commit_sha
    def encounter_datespec(self, location, datespec):
        from course.content import parse_date_spec
        parse_date_spec(self.course, datespec, vctx=self, location=location)
    def add_warning(self, *args, **kwargs):
        self.warnings.append(ValidationWarning(*args, **kwargs))


# {{{ course page validation

def validate_markup(ctx, location, markup_str):
    def reverse_func(*args, **kwargs):
        pass

    from course.content import markup_to_html
    try:
        markup_to_html(
                course=None,
                repo=ctx.repo,
Loading
Loading full blame...