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
committed
from django.utils.translation import ugettext as _
from django.utils.timezone import now
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.urls import NoReverseMatch
from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor
from jinja2 import (
BaseLoader as BaseTemplateLoader, TemplateNotFound, FileSystemLoader)
Andreas Klöckner
committed
from relate.utils import dict_to_struct, SubdirRepoWrapper
Andreas Klöckner
committed
from yaml import load as load_yaml
if sys.version_info >= (3,):
CACHE_KEY_ROOT = "py3"
else:
CACHE_KEY_ROOT = "py2"
Andreas Klöckner
committed
# {{{ mypy
Andreas Klöckner
committed
from typing import ( # noqa
cast, Union, Any, List, Tuple, Optional, Callable, Text)
Andreas Klöckner
committed
if False:
# for mypy
from course.models import Course, Participation # noqa
import dulwich # noqa
from course.validation import ValidationContext # noqa
from course.page.base import PageBase # noqa
from relate.utils import Struct, Repo_ish # noqa
Date_ish = Union[datetime.datetime, datetime.date]
Datespec = Union[datetime.datetime, datetime.date, Text]
class ChunkRulesDesc(Struct):
if_has_role = None # type: List[Text]
if_before = None # type: Datespec
if_after = None # type: Datespec
if_in_facility = None # type: Text
roles = None # type: List[Text]
start = None # type: Datespec
end = None # type: Datespec
shown = None # type: bool
weight = None # type: float
class ChunkDesc(Struct):
weight = None # type: float
shown = None # type: bool
title = None # type: Optional[Text]
content = None # type: Text
rules = None # type: List[ChunkRulesDesc]
Andreas Klöckner
committed
html_content = None # type: Text
Andreas Klöckner
committed
class StaticPageDesc(Struct):
chunks = None # type: List[ChunkDesc]
content = None # type: Text
class CourseDesc(StaticPageDesc):
pass
class StartRuleDesc(Struct):
pass
Andreas Klöckner
committed
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class AccessRuleDesc(Struct):
pass
class GradingRuleDesc(Struct):
grade_identifier = None # type: Optional[Text]
grade_aggregation_strategy = None # type: Optional[Text]
class FlowRulesDesc(Struct):
start = None # type: List[StartRuleDesc]
access = None # type: List[AccessRuleDesc]
grading = None # type: List[GradingRuleDesc]
grade_identifier = None # type: Optional[Text]
grade_aggregation_strategy = None # type: Optional[Text]
class FlowPageDesc(Struct):
id = None # type: Text
type = None # type: Text
class FlowPageGroupDesc(Struct):
id = None # type: Text
pages = None # type: List[FlowPageDesc]
class FlowDesc(Struct):
title = None # type: Text
rules = None # type: FlowRulesDesc
pages = None # type: List[FlowPageDesc]
groups = None # type: List[FlowPageGroupDesc]
notify_on_submit = None # type: Optional[List[Text]]
# }}}
# {{{ repo blob getting
def get_true_repo_and_path(repo, path):
Andreas Klöckner
committed
# type: (Repo_ish, Text) -> Tuple[dulwich.Repo, Text]
if isinstance(repo, SubdirRepoWrapper):
if path:
path = repo.subdir + "/" + path
else:
path = repo.subdir
return repo.repo, path
else:
return repo, path
def get_course_repo_path(course):
Andreas Klöckner
committed
# type: (Course) -> Text
from os.path import join
return join(settings.GIT_ROOT, course.identifier)
def get_course_repo(course):
Andreas Klöckner
committed
# type: (Course) -> Repo_ish
Andreas Klöckner
committed
from dulwich.repo import Repo
repo = Repo(get_course_repo_path(course))
if course.course_root_path:
return SubdirRepoWrapper(repo, course.course_root_path)
else:
return repo
def get_repo_blob(repo, full_name, commit_sha, allow_tree=True):
Andreas Klöckner
committed
# type: (Repo_ish, Text, bytes, bool) -> dulwich.Blob
:arg full_name: A Unicode string indicating the file name.
:arg commit_sha: A byte string containing the commit hash
:arg allow_tree: Allow the resulting object to be a directory
Andreas Klöckner
committed
dul_repo, full_name = get_true_repo_and_path(repo, full_name)
names = full_name.split("/")
Andreas Klöckner
committed
full_name_bytes = full_name.encode('utf-8')
Andreas Klöckner
committed
tree_sha = dul_repo[commit_sha].tree
tree = dul_repo[tree_sha]
def access_directory_content(maybe_tree, name):
Andreas Klöckner
committed
# type: (Any, Text) -> Any
try:
mode_and_blob_sha = tree[name.encode()]
except TypeError:
raise ObjectDoesNotExist(_("resource '%s' is a file, "
Andreas Klöckner
committed
"not a directory") % full_name)
mode, blob_sha = mode_and_blob_sha
return mode_and_blob_sha
Andreas Klöckner
committed
if not full_name_bytes:
if allow_tree:
return tree
else:
raise ObjectDoesNotExist(
_("repo root is a directory, not a file"))
try:
for name in names[:-1]:
if not name:
# tolerate empty path components (begrudgingly)
continue
mode, blob_sha = access_directory_content(tree, name)
Andreas Klöckner
committed
tree = dul_repo[blob_sha]
mode, blob_sha = access_directory_content(tree, names[-1])
Andreas Klöckner
committed
result = dul_repo[blob_sha]
if not allow_tree and not hasattr(result, "data"):
raise ObjectDoesNotExist(
Andreas Klöckner
committed
_("resource '%s' is a directory, not a file") % full_name)
Andreas Klöckner
committed
raise ObjectDoesNotExist(_("resource '%s' not found") % full_name)
def get_repo_blob_data_cached(repo, full_name, commit_sha):
Andreas Klöckner
committed
# type: (Repo_ish, Text, bytes) -> bytes
"""
: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 = "%s%R%1".join((
CACHE_KEY_ROOT,
quote_plus(repo.controldir()),
quote_plus(full_name),
commit_sha.decode(),
".".join(str(s) for s in sys.version_info[:2]),
Andreas Klöckner
committed
)) # type: Optional[Text]
try:
import django.core.cache as cache
except ImproperlyConfigured:
cache_key = None
if cache_key is None:
result = get_repo_blob(repo, full_name, commit_sha,
allow_tree=False).data
assert isinstance(result, six.binary_type)
return result
# Byte string is wrapped in a tuple to force pickling because memcache's
# python wrapper appears to auto-decode/encode string values, thus trying
# to decode our byte strings. Grr.
result = None
# Memcache is apparently limited to 250 characters.
if len(cache_key) < 240:
result = def_cache.get(cache_key)
(result,) = result
assert isinstance(result, six.binary_type), cache_key
result = get_repo_blob(repo, full_name, commit_sha,
allow_tree=False).data
if len(result) <= getattr(settings, "RELATE_CACHE_MAX_BYTES", 0):
def_cache.add(cache_key, (result,), None)
assert isinstance(result, six.binary_type)
def is_repo_file_accessible_as(access_kind, repo, commit_sha, path):
Andreas Klöckner
committed
# type: (Text, Repo_ish, bytes, Text) -> bool
Andreas Klöckner
committed
Check of a file in a repo directory is accessible. For example,
'instructor' can access anything listed in the attributes.
'student' can access 'student' and 'unenrolled'. The 'unenrolled' role
can only access 'unenrolled'.
Andreas Klöckner
committed
:arg commit_sha: A byte string containing the commit hash
"""
Andreas Klöckner
committed
# set the path to .attributes.yml
from os.path import dirname, basename, join
attributes_path = join(dirname(path), ".attributes.yml")
Andreas Klöckner
committed
# retrieve the .attributes.yml structure
Andreas Klöckner
committed
attributes = get_raw_yaml_from_repo(repo, attributes_path,
# no attributes file: not accessible
path_basename = basename(path)
Andreas Klöckner
committed
# [unenrolled, student, ta, instructor]
Andreas Klöckner
committed
# access_kind hierarchy and who should be allowed in sets:
# in_exam : in_exam
# instructor : [public, unenrolled, student, ta, instructor]
# ta : [public, unenrolled, student, ta]
# student : [public, unenrolled, student]
# unenrolled : [public, unenrolled]
Andreas Klöckner
committed
# "public" is a deprecated alias for "unenrolled".
if access_kind == 'in_exam':
Andreas Klöckner
committed
kind_list = ['in_exam']
elif access_kind == ('unenrolled' or 'public'):
Andreas Klöckner
committed
kind_list = ['public', 'unenrolled']
elif access_kind == 'student':
Andreas Klöckner
committed
kind_list = ['public', 'unenrolled', 'student']
elif access_kind == 'ta':
Andreas Klöckner
committed
kind_list = ['public', 'unenrolled', 'student', 'ta']
elif access_kind == 'instructor':
Andreas Klöckner
committed
kind_list = ['public', 'unenrolled', 'student', 'ta', 'instructor']
Andreas Klöckner
committed
access_patterns = [] # type: List[Text]
Andreas Klöckner
committed
for kind in kind_list:
access_patterns += attributes.get(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_YAML_RE = re.compile(
r"^\[JINJA\]\s*$(.*?)^\[\/JINJA\]\s*$",
re.MULTILINE | re.DOTALL)
YAML_BLOCK_START_SCALAR_RE = re.compile(
Andreas Klöckner
committed
r"(:\s*[|>])"
"(J?)"
"((?:[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):
Andreas Klöckner
committed
# type: (Text) -> Text
lines = yaml_str.split("\n")
jinja_lines = []
i = 0
line_count = len(lines)
while i < line_count:
l = lines[i]
Andreas Klöckner
committed
yaml_block_scalar_match = YAML_BLOCK_START_SCALAR_RE.search(l)
Andreas Klöckner
committed
if yaml_block_scalar_match is not None:
Andreas Klöckner
committed
allow_jinja = bool(yaml_block_scalar_match.group(2))
l = YAML_BLOCK_START_SCALAR_RE.sub(
r"\1\3", l)
block_start_indent = len(LEADING_SPACES_RE.match(l).group(1))
i += 1
while i < line_count:
l = lines[i]
if not l.rstrip():
i += 1
continue
line_indent = len(LEADING_SPACES_RE.match(l).group(1))
if line_indent <= block_start_indent:
break
else:
i += 1
Andreas Klöckner
committed
if not allow_jinja:
jinja_lines.append("{% raw %}")
jinja_lines.extend(unprocessed_block_lines)
Andreas Klöckner
committed
if not allow_jinja:
jinja_lines.append("{% endraw %}")
elif GROUP_COMMENT_START.match(l):
jinja_lines.append("{% raw %}")
jinja_lines.append(l)
jinja_lines.append("{% endraw %}")
Andreas Klöckner
committed
i += 1
else:
i += 1
return "\n".join(jinja_lines)
class GitTemplateLoader(BaseTemplateLoader):
def __init__(self, repo, commit_sha):
Andreas Klöckner
committed
# type: (Repo_ish, bytes) -> None
self.repo = repo
self.commit_sha = commit_sha
def get_source(self, environment, template):
try:
data = get_repo_blob_data_cached(self.repo, template, self.commit_sha)
except ObjectDoesNotExist:
raise TemplateNotFound(template)
source = data.decode('utf-8')
def is_up_to_date():
# There's not much point to caching here, because we create
# a new loader for every request anyhow...
return False
return source, None, is_up_to_date
class YamlBlockEscapingGitTemplateLoader(GitTemplateLoader):
# https://github.com/inducer/relate/issues/130
def get_source(self, environment, template):
source, path, is_up_to_date = \
super(YamlBlockEscapingGitTemplateLoader, self).get_source(
environment, template)
from os.path import splitext
_, ext = splitext(template)
ext = ext.lower()
if ext in [".yml", ".yaml"]:
source = process_yaml_for_expansion(source)
return source, path, is_up_to_date
class YamlBlockEscapingFileSystemLoader(FileSystemLoader):
# https://github.com/inducer/relate/issues/130
def get_source(self, environment, template):
source, path, is_up_to_date = \
super(YamlBlockEscapingFileSystemLoader, self).get_source(
environment, template)
from os.path import splitext
_, ext = splitext(template)
ext = ext.lower()
if ext in [".yml", ".yaml"]:
source = process_yaml_for_expansion(source)
return source, path, is_up_to_date
def expand_yaml_macros(repo, commit_sha, yaml_str):
Andreas Klöckner
committed
# type: (Repo_ish, bytes, Text) -> Text
if isinstance(yaml_str, six.binary_type):
yaml_str = yaml_str.decode("utf-8")
from jinja2 import Environment, StrictUndefined
jinja_env = Environment(
loader=YamlBlockEscapingGitTemplateLoader(repo, commit_sha),
undefined=StrictUndefined)
# {{{ process explicit [JINJA] tags (deprecated)
def compute_replacement(match):
template = jinja_env.from_string(match.group(1))
return template.render()
yaml_str, count = JINJA_YAML_RE.subn(compute_replacement, yaml_str)
if count:
# The file uses explicit [JINJA] tags. Assume that it doesn't
# want anything else processed through YAML.
return yaml_str
# }}}
jinja_str = process_yaml_for_expansion(yaml_str)
template = jinja_env.from_string(jinja_str)
yaml_str = template.render()
return yaml_str
# }}}
# {{{ repo yaml getting
def get_raw_yaml_from_repo(repo, full_name, commit_sha):
Andreas Klöckner
committed
# type: (Repo_ish, Text, bytes) -> Any
"""Return decoded YAML data structure from
the given file in *repo* at *commit_sha*.
:arg commit_sha: A byte string containing the commit hash
from six.moves.urllib.parse import quote_plus
cache_key = "%RAW%%2".join((
CACHE_KEY_ROOT,
quote_plus(repo.controldir()), quote_plus(full_name), commit_sha.decode(),
))
result = None
# Memcache is apparently limited to 250 characters.
if len(cache_key) < 240:
result = def_cache.get(cache_key)
result = load_yaml(
expand_yaml_macros(
repo, commit_sha,
get_repo_blob(repo, full_name, commit_sha,
allow_tree=False).data))
def_cache.add(cache_key, result, None)
return result
def get_yaml_from_repo(repo, full_name, commit_sha, cached=True):
Andreas Klöckner
committed
# type: (Repo_ish, Text, bytes, bool) -> Any
"""Return decoded, struct-ified YAML data structure from
the given file in *repo* at *commit_sha*.
from six.moves.urllib.parse import quote_plus
cache_key = "%%%2".join(
(CACHE_KEY_ROOT,
quote_plus(repo.controldir()), quote_plus(full_name),
import django.core.cache as cache
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)
if result is not None:
return result
expanded = expand_yaml_macros(
repo, commit_sha,
get_repo_blob(repo, full_name, commit_sha,
allow_tree=False).data)
result = dict_to_struct(load_yaml(expanded))
if cached:
def_cache.add(cache_key, result, None)
# }}}
# {{{ markup
def _attr_to_string(key, val):
if val is None:
return key
elif "\"" in val:
return "%s='%s'" % (key, val)
else:
return "%s=\"%s\"" % (key, val)
class TagProcessingHTMLParser(html_parser.HTMLParser):
def __init__(self, out_file, process_tag_func):
self.out_file = out_file
self.process_tag_func = process_tag_func
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
attrs.update(self.process_tag_func(tag, attrs))
self.out_file.write("<%s %s>" % (tag, " ".join(
_attr_to_string(k, v) for k, v in six.iteritems(attrs))))
def handle_endtag(self, tag):
self.out_file.write("</%s>" % tag)
def handle_startendtag(self, tag, attrs):
attrs = dict(attrs)
attrs.update(self.process_tag_func(tag, attrs))
self.out_file.write("<%s %s/>" % (tag, " ".join(
def handle_data(self, data):
self.out_file.write(data)
def handle_entityref(self, name):
self.out_file.write("&%s;" % name)
def handle_charref(self, name):
self.out_file.write("&#%s;" % name)
def handle_comment(self, data):
self.out_file.write("<!--%s-->" % data)
def handle_decl(self, decl):
self.out_file.write("<!%s>" % decl)
def handle_pi(self, data):
raise NotImplementedError(
_("I have no idea what a processing instruction is."))
def unknown_decl(self, data):
self.out_file.write("<![%s]>" % data)
class PreserveFragment(object):
def __init__(self, s):
self.s = s
def __init__(self, md, course, commit_sha, reverse_func):
self.commit_sha = commit_sha
def reverse(self, viewname, args):
frag = None
new_args = []
for arg in args:
if isinstance(arg, PreserveFragment):
s = arg.s
if frag_index != -1:
frag = s[frag_index:]
s = s[:frag_index]
new_args.append(s)
else:
new_args.append(arg)
result = self.reverse_func(viewname, args=new_args)
if frag is not None:
result += frag
return result
def get_course_identifier(self):
if self.course is None:
return "bogus-course-identifier"
else:
return self.course.identifier
try:
if url.startswith("course:"):
course_id = url[7:]
if course_id:
return self.reverse("relate-course_page",
args=(course_id,))
else:
return self.reverse("relate-course_page",
args=(self.get_course_identifier(),))
elif url.startswith("flow:"):
flow_id = url[5:]
return self.reverse("relate-view_start_flow",
args=(self.get_course_identifier(), flow_id))
elif url.startswith("staticpage:"):
page_path = url[11:]
return self.reverse("relate-content_page",
args=(
self.get_course_identifier(),
PreserveFragment(page_path)))
elif url.startswith("media:"):
media_path = url[6:]
return self.reverse("relate-get_media",
args=(
self.get_course_identifier(),
self.commit_sha,
PreserveFragment(media_path)))
elif url.startswith("repo:"):
path = url[5:]
return self.reverse("relate-get_repo_file",
args=(
self.get_course_identifier(),
self.commit_sha,
elif url.startswith("repocur:"):
path = url[8:]
return self.reverse("relate-get_current_repo_file",
args=(
self.get_course_identifier(),
elif url.strip() == "calendar:":
return self.reverse("relate-view_calendar",
except NoReverseMatch:
from base64 import b64encode
message = ("Invalid character in RELATE URL: " + url).encode("utf-8")
return "data:text/plain;base64,"+b64encode(message).decode()
return None
def process_tag(self, tag_name, attrs):
changed_attrs = {}
if tag_name == "table":
changed_attrs["class"] = "table table-condensed"
if tag_name in ["a", "link"] and "href" in attrs:
new_href = self.process_url(attrs["href"])
if new_href is not None:
changed_attrs["href"] = new_href
elif tag_name == "img" and "src" in attrs:
new_src = self.process_url(attrs["src"])
if new_src is not None:
changed_attrs["src"] = new_src
elif tag_name == "object" and "data" in attrs:
new_data = self.process_url(attrs["data"])
if new_data is not None:
changed_attrs["data"] = new_data
return changed_attrs
def process_etree_element(self, element):
changed_attrs = self.process_tag(element.tag, element.attrib)
for key, val in six.iteritems(changed_attrs):
element.set(key, val)
def walk_and_process_tree(self, root):
self.process_etree_element(root)
self.walk_and_process_tree(child)
def run(self, root):
self.walk_and_process_tree(root)
# root through and process Markdown's HTML stash (gross!)
for i, (html, safe) in enumerate(self.md.htmlStash.rawHtmlBlocks):
parser = TagProcessingHTMLParser(outf, self.process_tag)
parser.feed(html)
self.md.htmlStash.rawHtmlBlocks[i] = (outf.getvalue(), safe)
def __init__(self, course, commit_sha, reverse_func):
Andreas Klöckner
committed
# type: (Optional[Course], bytes, Optional[Callable]) -> None
self.course = course
self.commit_sha = commit_sha
LinkFixerTreeprocessor(md, self.course, self.commit_sha,
reverse_func=self.reverse_func)
def remove_prefix(prefix, s):
Andreas Klöckner
committed
# type: (Text, Text) -> Text
if s.startswith(prefix):
return s[len(prefix):]
else:
return s
JINJA_PREFIX = "[JINJA]"
Andreas Klöckner
committed
def markup_to_html(
course, # type: Optional[Course]
repo, # type: Repo_ish
commit_sha, # type: bytes
text, # type: Text
reverse_func=None, # type: Callable
validate_only=False, # type: bool
jinja_env={}, # type: Dict
):
# type: (...) -> Text
from django.urls import reverse
if course is not None and not jinja_env:
try:
import django.core.cache as cache
except ImproperlyConfigured:
cache_key = None
else:
import hashlib
cache_key = ("markup:v6:%s:%d:%s:%s"
% (CACHE_KEY_ROOT, course.id, str(commit_sha),
hashlib.md5(text.encode("utf-8")).hexdigest()))
def_cache = cache.caches["default"]
result = def_cache.get(cache_key)
if result is not None:
assert isinstance(result, six.text_type)
if text.lstrip().startswith(JINJA_PREFIX):
text = remove_prefix(JINJA_PREFIX, text.lstrip())
else:
cache_key = None
if not isinstance(text, six.text_type):
text = six.text_type(text)
# {{{ process through Jinja
from jinja2 import Environment, StrictUndefined
env = Environment(
loader=GitTemplateLoader(repo, commit_sha),
undefined=StrictUndefined)
template = env.from_string(text)
text = template.render(**jinja_env)
Andreas Klöckner
committed
if validate_only:
Andreas Klöckner
committed
return ""
Andreas Klöckner
committed
from course.mdx_mathjax import MathJaxExtension
LinkFixerExtension(course, commit_sha, reverse_func=reverse_func),
"markdown.extensions.extra",
"markdown.extensions.codehilite",
],
output_format="html5")
assert isinstance(result, six.text_type)
if cache_key is not None:
def_cache.add(cache_key, result, None)
return result
TITLE_RE = re.compile(r"^\#+\s*(\w.*)", re.UNICODE)
def extract_title_from_markup(markup_text):
Andreas Klöckner
committed
# type: (Text) -> Optional[Text]
lines = markup_text.split("\n")
for l in lines[:10]:
match = TITLE_RE.match(l)
if match is not None:
return match.group(1)
return None
# {{{ datespec processing
DATE_RE = re.compile(r"^([0-9]+)\-([01][0-9])\-([0-3][0-9])$")
TRAILING_NUMERAL_RE = re.compile(r"^(.*)\s+([0-9]+)$")
END_PREFIX = "end:"
class InvalidDatespec(ValueError):
def __init__(self, datespec):
ValueError.__init__(self, str(datespec))
self.datespec = datespec
Andreas Klöckner
committed
class DatespecPostprocessor(object):
@classmethod
def parse(cls, s):
# type: (Text) -> Tuple[Text, Optional[DatespecPostprocessor]]
raise NotImplementedError()
def apply(self, dtm):
# type: (datetime.datetime) -> datetime.datetime
raise NotImplementedError()
AT_TIME_RE = re.compile(r"^(.*)\s*@\s*([0-2]?[0-9])\:([0-9][0-9])\s*$")
Andreas Klöckner
committed
class AtTimePostprocessor(DatespecPostprocessor):
def __init__(self, hour, minute, second=0):
Andreas Klöckner
committed
# type: (int, int, int) -> None
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
self.hour = hour
self.minute = minute
self.second = second
@classmethod
def parse(cls, s):
match = AT_TIME_RE.match(s)
if match is not None:
hour = int(match.group(2))
minute = int(match.group(3))
if not (0 <= hour < 24):
raise InvalidDatespec(s)
if not (0 <= minute < 60):
raise InvalidDatespec(s)
return match.group(1), AtTimePostprocessor(hour, minute)
else:
return s, None
def apply(self, dtm):
from pytz import timezone
server_tz = timezone(settings.TIME_ZONE)
return dtm.astimezone(server_tz).replace(
hour=self.hour,
minute=self.minute,
second=self.second)
PLUS_DELTA_RE = re.compile(r"^(.*)\s*([+-])\s*([0-9]+)\s+"
"(weeks?|days?|hours?|minutes?)$")
Andreas Klöckner
committed
class PlusDeltaPostprocessor(DatespecPostprocessor):
def __init__(self, count, period):
Andreas Klöckner
committed
# type: (int, Text) -> None
self.count = count
self.period = period