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

from __future__ import division

__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.
"""

Andreas Klöckner's avatar
Andreas Klöckner committed
from django.conf import settings
from django.utils.translation import ugettext as _
Andreas Klöckner's avatar
Andreas Klöckner committed

import re
import datetime
import six
Andreas Klöckner's avatar
Andreas Klöckner committed

from django.utils.timezone import now
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core.urlresolvers import NoReverseMatch
Andreas Klöckner's avatar
Andreas Klöckner committed

from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor

from six.moves import html_parser
from jinja2 import BaseLoader as BaseTemplateLoader, TemplateNotFound

Andreas Klöckner's avatar
Andreas Klöckner committed
from relate.utils import dict_to_struct
# {{{ repo blob getting
class SubdirRepoWrapper(object):
    def __init__(self, repo, subdir):
        self.repo = repo

        # This wrapper should only get used if there is a subdir to be had.
        assert subdir
        self.subdir = subdir

    def controldir(self):
        return self.repo.controldir()

    def close(self):
        self.repo.close()

def get_course_repo_path(course):
    from os.path import join
    return join(settings.GIT_ROOT, course.identifier)


def get_course_repo(course):
    repo = Repo(get_course_repo_path(course))

    if course.course_root_path:
        return SubdirRepoWrapper(repo, course.course_root_path)
    else:
        return repo
Andreas Klöckner's avatar
Andreas Klöckner committed


def get_repo_blob(repo, full_name, commit_sha):
    """
    :arg full_name: A Unicode string indicating the file name.
    :arg commit_sha: A byte string containing the commit hash
    """

    if isinstance(repo, SubdirRepoWrapper):
        # full_name must be non-empty
        full_name = repo.subdir + "/" + full_name
        repo = repo.repo

    names = full_name.split("/")

    # Allow non-ASCII file name
    full_name = full_name.encode('utf-8')

    tree_sha = repo[commit_sha].tree
    tree = repo[tree_sha]

    if not full_name:
        return tree

    try:
        for name in names[:-1]:
            if not name:
                # tolerate empty path components (begrudgingly)
                continue

            mode, blob_sha = tree[name.encode()]
            tree = repo[blob_sha]

        mode, blob_sha = tree[names[-1].encode()]
        return repo[blob_sha]
    except KeyError:
ifaint's avatar
ifaint committed
        raise ObjectDoesNotExist(_("resource '%s' not found") % full_name)
Andreas Klöckner's avatar
Andreas Klöckner committed
def get_repo_blob_data_cached(repo, full_name, commit_sha):
    """
    :arg commit_sha: A byte string containing the commit hash
    """

    if isinstance(commit_sha, six.binary_type):
        from six.moves.urllib.parse import quote_plus
        cache_key = "%%%1".join((
            quote_plus(repo.controldir()),
            quote_plus(full_name),
            commit_sha.decode()))
    else:
        cache_key = None

    try:
        import django.core.cache as cache
    except ImproperlyConfigured:
        cache_key = None

    if cache_key is None:
        return get_repo_blob(repo, full_name, commit_sha).data
Andreas Klöckner's avatar
Andreas Klöckner committed

    def_cache = cache.caches["default"]

    result = None
    # Memcache is apparently limited to 250 characters.
    if len(cache_key) < 240:
        result = def_cache.get(cache_key)
Andreas Klöckner's avatar
Andreas Klöckner committed
    if result is not None:
        return result

    result = get_repo_blob(repo, full_name, commit_sha).data

    if len(result) <= getattr(settings, "RELATE_CACHE_MAX_BYTES", 0):
        def_cache.add(cache_key, result, None)

Andreas Klöckner's avatar
Andreas Klöckner committed
    return result


def is_repo_file_accessible_as(access_kind, repo, commit_sha, path):
    """
    :arg commit_sha: A byte string containing the commit hash
    """
    from os.path import dirname, basename, join
    attributes_path = join(dirname(path), ".attributes.yml")
    from course.content import get_raw_yaml_from_repo
    try:
        attributes = get_raw_yaml_from_repo(
                repo, attributes_path, commit_sha.encode())
    except ObjectDoesNotExist:
        # no attributes file: not public
        return False
    path_basename = basename(path)
    access_patterns = attributes.get(access_kind, [])
    from fnmatch import fnmatch
    if isinstance(access_patterns, list):
        for pattern in access_patterns:
            if isinstance(pattern, six.string_types):
                if fnmatch(path_basename, pattern):
                    return True
# {{{ jinja interaction
JINJA_YAML_RE = re.compile(
    r"^\[JINJA\]\s*$(.*?)^\[\/JINJA\]\s*$",
    re.MULTILINE | re.DOTALL)
YAML_BLOCK_START_SCALAR_RE = re.compile(
    r":\s*[|>](?:[0-9][-+]?|[-+][0-9]?)?(?:\s*\#.*)?$")
GROUP_COMMENT_START = re.compile(r"^\s*#\s*\{\{\{")
LEADING_SPACES_RE = re.compile(r"^( *)")
def process_yaml_for_expansion(yaml_str):
Loading
Loading full blame...