Newer
Older
from django.conf import settings
import re
import datetime
from markdown.extensions import Extension
from markdown.treeprocessors import Treeprocessor
from django.core.urlresolvers import reverse
# {{{ tools
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
def __init__(self, entries):
for name, val in entries.iteritems():
self.__dict__[name] = dict_to_struct(val)
def __repr__(self):
return repr(self.__dict__)
def dict_to_struct(data):
if isinstance(data, list):
return [dict_to_struct(d) for d in data]
elif isinstance(data, dict):
return Struct(data)
else:
return data
# }}}
# {{{ formatting
class LinkFixerTreeprocessor(Treeprocessor):
def __init__(self, course):
Treeprocessor.__init__(self)
self.course = course
def run(self, root):
if root.tag == "a" and root.attrib["href"].startswith("flow:"):
flow_id = root.attrib["href"][5:]
root.set("href",
reverse("course.views.start_flow",
args=(self.course.identifier, flow_id)))
for child in root:
self.run(child)
class LinkFixerExtension(Extension):
def __init__(self, course):
self.course = course
Extension.__init__(self)
def extendMarkdown(self, md, md_globals):
md.treeprocessors["courseflow_link_fixer"] = \
LinkFixerTreeprocessor(self.course)
def html_body(course, text):
import markdown
return markdown.markdown(text,
extensions=[
LinkFixerExtension(course)
])
# }}}
def get_git_repo(course):
from os.path import join
from gittle import Gittle
return Gittle(join(settings.GIT_ROOT, course.identifier))
def get_repo_blob(repo, full_name, commit_sha=None):
names = full_name.split("/")
tree_sha = repo[commit_sha].tree
tree = repo[tree_sha]
try:
for name in names[:-1]:
mode, blob_sha = tree[name.encode()]
assert mode == repo.MODE_DIRECTORY
tree = repo[blob_sha]
mode, blob_sha = tree[names[-1].encode()]
except KeyError:
# TODO: Proper 404
raise RuntimeError("resource '%s' not found" % full_name)
def get_course_file(course, full_name, commit_sha=None):
repo = get_git_repo(course)
if commit_sha is None:
commit_sha = course.active_git_commit_sha.encode("us-ascii")
return get_repo_blob(repo, full_name, commit_sha).data
def get_course_file_yaml(course, full_name, commit_sha=None):
from yaml import load
return dict_to_struct(
load(get_course_file(course, full_name, commit_sha)))
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
148
149
DATE_RE_MATCH = re.compile(r"^([0-9]+)\-([01][0-9])\-([0-3][0-9])$")
WEEK_RE_MATCH = re.compile(r"^(start|end)\s+week\s+([0-9]+)$")
def parse_absolute_date_spec(date_spec):
match = DATE_RE_MATCH.match(date_spec)
if not match:
raise ValueError("invalid absolute datespec: %s" % date_spec)
return datetime.date(
int(match.group(1)),
int(match.group(2)),
int(match.group(3)))
def parse_date_spec(course_desc, date_spec):
match = DATE_RE_MATCH.match(date_spec)
if match:
return datetime.date(
int(match.group(1)),
int(match.group(2)),
int(match.group(3)))
match = WEEK_RE_MATCH.match(date_spec)
if match:
n = int(match.group(2)) - 1
if match.group(1) == "start":
return course_desc.first_course_week_start + datetime.timedelta(days=n*7)
elif match.group(1) == "end":
return (course_desc.first_course_week_start
+ datetime.timedelta(days=n*7+6))
else:
raise ValueError("invalid datespec: %s" % date_spec)
raise ValueError("invalid datespec: %s" % date_spec)
def compute_chunk_weight_and_shown(course_desc, chunk, role):
for rule in chunk.rules:
if hasattr(rule, "role"):
if role != rule.role:
continue
if hasattr(rule, "start"):
start_date = parse_date_spec(course_desc, rule.start)
if hasattr(rule, "end"):
end_date = parse_date_spec(course_desc, rule.end)
shown = True
if hasattr(rule, "shown"):
shown = rule.shown
return rule.weight, shown
class NoCourseContent(RuntimeError):
pass
def get_course_desc(course):
course_desc = get_course_file_yaml(course, "course.yml")
assert isinstance(course_desc.course_start, datetime.date)
assert isinstance(course_desc.course_end, datetime.date)
# a Monday
course_desc.first_course_week_start = \
course_desc.course_start - datetime.timedelta(
days=course_desc.course_start.weekday())
return course_desc
def get_processed_course_chunks(course, course_desc, role):
for chunk in course_desc.chunks:
chunk.weight, chunk.shown = \
compute_chunk_weight_and_shown(
course_desc, chunk, role)
chunk.html_content = html_body(course, chunk.content)
course_desc.chunks.sort(key=lambda chunk: chunk.weight)
return [mod for mod in course_desc.chunks
if chunk.shown]
def get_flow(course, flow_id, commit_sha):
flow = get_course_file_yaml(course, "flows/%s.yml")
flow.description_html = html_body(course, getattr(flow, "description", None))
return flow
# {{{ validation
class ValidationError(RuntimeError):
def validate_struct(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`.
"""
present_attrs = set(name for name in dir(obj) if not name.startswith("_"))
for required, attr_list in [
(True, required_attrs),
(False, allowed_attrs),
]:
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("%s: attribute '%s' missing"
% (location, attr))
else:
present_attrs.remove(attr)
val = getattr(obj, attr)
if allowed_types is str:
allowed_types = (str, unicode)
if not isinstance(val, allowed_types):
raise ValidationError("%s: attribute '%s' has "
"wrong type: got '%s', expected '%s'"
% (location, attr, type(val).__name__,
allowed_types))
if present_attrs:
raise ValidationError("%s: extraneous attribute(s) '%s'"
% (location, ",".join(present_attrs)))
datespec_types = (datetime.date, str, unicode)
def validate_chunk_rule(chunk_rule):
validate_struct(
"chunk_rule",
chunk_rule,
required_attrs=[
("weight", int),
],
allowed_attrs=[
("start", (str, datetime.date)),
("end", (str, datetime.date)),
("role", str),
("shown", bool),
])
validate_struct(
"chunk",
chunk,
required_attrs=[
("title", str),
("id", str),
("rules", list),
("content", str),
],
allowed_attrs=[]
)
for rule in chunk.rules:
validate_chunk_rule(rule)
def validate_course_desc_struct(course_desc):
validate_struct(
course_desc,
required_attrs=[
("name", str),
("number", str),
("run", str),
("description", str),
("course_start", datetime.date),
("course_end", datetime.date),
("chunks", list),
for chunk in course_desc.chunks:
validate_chunk(chunk)
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def validate_flow_page(location, page):
validate_struct(
location,
page,
required_attrs=[
("type", str),
("id", str),
],
allowed_attrs=[
("content", str),
("prompt", str),
("title", str),
("answers", list),
("choices", list),
("value", (int, float)),
]
)
def validate_flow_group(location, grp):
validate_struct(
location,
grp,
required_attrs=[
("id", str),
("pages", list),
],
allowed_attrs=[]
)
for i, page in enumerate(grp.pages):
validate_flow_page("%s, page %d" % (location, i+1), page)
def validate_role(location, role):
from course.models import participation_role
if role not in [
participation_role.instructor,
participation_role.teaching_assistant,
participation_role.student,
participation_role.unenrolled,
]:
raise ValidationError("%s: invalid role '%s'"
% (location, role))
def validate_flow_access_rule(location, rule):
validate_struct(
location,
rule,
required_attrs=[
("access", str),
],
allowed_attrs=[
("roles", list),
("start", (datetime.date, str)),
("end", (datetime.date, str)),
("credit_percent", (int, float)),
("time_limit", str),
("allowed_visit_count", int),
]
)
if rule.access not in ["allow", "deny", "credit", "review"]:
raise ValidationError("%s: invalid value for 'access'"
% location)
if hasattr(rule, "roles"):
for i, role in enumerate(rule.roles):
validate_role(
"%s, role %d" % (location, i+1),
role)
# TODO: validate time limit
def validate_flow_desc(location, flow_desc):
validate_struct(
location,
flow_desc,
required_attrs=[
("title", str),
("description", str),
("flow_groups", list),
],
allowed_attrs=[
("access_rules", list),
]
)
if hasattr(flow_desc, "access_rules"):
for i, rule in enumerate(flow_desc.access_rules):
validate_flow_access_rule(
"%s, access rule %d" % (location, i+1),
rule)
last_rule = flow_desc.access_rules[-1]
if (
hasattr(last_rule, "roles")
or hasattr(last_rule, "start")
or hasattr(last_rule, "end")
):
raise ValidationError("%s: last access rule must set default access "
"(i.e. have no attributes other than 'access')"
% location)
for i, grp in enumerate(flow_desc.flow_groups):
validate_flow_group("%s, group %d" % (location, i+1), grp)
def validate_course_content(course, validate_sha):
course_desc = get_course_file_yaml(course, "course.yml",
commit_sha=validate_sha)
validate_course_desc_struct(course_desc)
repo = get_git_repo(course)
flows_tree = get_repo_blob(repo, "flows", validate_sha)
for entry in flows_tree.items():
location = "flows/%s" % entry.path
flow_desc = get_course_file_yaml(course, location,
commit_sha=validate_sha)
validate_flow_desc(location, flow_desc)