Repository navigation
Expand file tree
/
Copy pathcontent.py
More file actions
1478 lines (1081 loc) · 42.3 KB
/
Copy pathcontent.py
File metadata and controls
1478 lines (1081 loc) · 42.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
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
995
996
997
998
999
1000
# -*- 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.
"""
from django.conf import settings
from django.utils.translation import ugettext as _
import re
import datetime
import six
import sys
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 six.moves import html_parser
from jinja2 import (
BaseLoader as BaseTemplateLoader, TemplateNotFound, FileSystemLoader)
from relate.utils import dict_to_struct, Struct, SubdirRepoWrapper
from course.constants import ATTRIBUTES_FILENAME
from yaml import load as load_yaml
if sys.version_info >= (3,):
CACHE_KEY_ROOT = "py3"
else:
CACHE_KEY_ROOT = "py2"
# {{{ mypy
from typing import ( # noqa
cast, Union, Any, List, Tuple, Optional, Callable, Text, Dict)
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 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]
html_content = None # type: Text
class StaticPageDesc(Struct):
chunks = None # type: List[ChunkDesc]
content = None # type: Text
class CourseDesc(StaticPageDesc):
pass
class FlowSessionStartRuleDesc(Struct):
if_after = None # type: Date_ish
if_before = None # type: Date_ish
if_has_role = None # type: list
if_in_facility = None # type: Text
if_has_in_progress_session = None # type: bool
if_has_session_tagged = None # type: Optional[Text]
if_has_fewer_sessions_than = None # type: int
if_has_fewer_tagged_sessions_than = None # type: int
if_signed_in_with_matching_exam_ticket = None # type: bool
tag_session = None # type: Optional[Text]
may_start_new_session = None # type: bool
may_list_existing_sessions = None # type: bool
lock_down_as_exam_session = None # type: bool
default_expiration_mode = None # type: Text
class FlowSessionAccessRuleDesc(Struct):
permissions = None # type: list
if_after = None # type: Date_ish
if_before = None # type: Date_ish
if_started_before = None # type: Date_ish
if_has_role = None # type: List[Text]
if_in_facility = None # type: Text
if_has_tag = None # type: Optional[Text]
if_in_progress = None # type: bool
if_completed_before = None # type: Date_ish
if_expiration_mode = None # type: Text
if_session_duration_shorter_than_minutes = None # type: float
if_signed_in_with_matching_exam_ticket = None # type: bool
message = None # type: Text
class FlowSessionGradingRuleDesc(Struct):
grade_identifier = None # type: Optional[Text]
grade_aggregation_strategy = None # type: Optional[Text]
class FlowRulesDesc(Struct):
start = None # type: List[FlowSessionStartRuleDesc]
access = None # type: List[FlowSessionAccessRuleDesc]
grading = None # type: List[FlowSessionGradingRuleDesc]
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):
# 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):
# type: (Course) -> Text
from os.path import join
return join(settings.GIT_ROOT, course.identifier)
def get_course_repo(course):
# type: (Course) -> Repo_ish
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):
# 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
"""
dul_repo, full_name = get_true_repo_and_path(repo, full_name)
names = full_name.split("/")
# Allow non-ASCII file name
full_name_bytes = full_name.encode('utf-8')
try:
tree_sha = dul_repo[commit_sha].tree
except KeyError:
raise ObjectDoesNotExist(
_("commit sha '%s' not found") % commit_sha.decode())
tree = dul_repo[tree_sha]
def access_directory_content(maybe_tree, name):
# type: (Any, Text) -> Any
try:
mode_and_blob_sha = tree[name.encode()]
except TypeError:
raise ObjectDoesNotExist(_("resource '%s' is a file, "
"not a directory") % full_name)
mode, blob_sha = mode_and_blob_sha
return mode_and_blob_sha
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)
tree = dul_repo[blob_sha]
mode, blob_sha = access_directory_content(tree, names[-1])
result = dul_repo[blob_sha]
if not allow_tree and not hasattr(result, "data"):
raise ObjectDoesNotExist(
_("resource '%s' is a directory, not a file") % full_name)
return result
except KeyError:
raise ObjectDoesNotExist(_("resource '%s' not found") % full_name)
def get_repo_blob_data_cached(repo, full_name, commit_sha):
# 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]),
)) # type: Optional[Text]
else:
cache_key = None
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.
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:
(result,) = result
assert isinstance(result, six.binary_type), cache_key
return result
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)
return result
def is_repo_file_accessible_as(access_kinds, repo, commit_sha, path):
# type: (List[Text], Repo_ish, bytes, Text) -> bool
"""
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'.
:arg commit_sha: A byte string containing the commit hash
"""
# set the path to .attributes.yml
from os.path import dirname, basename, join
attributes_path = join(dirname(path), ATTRIBUTES_FILENAME)
# retrieve the .attributes.yml structure
try:
attributes = get_raw_yaml_from_repo(repo, attributes_path,
commit_sha)
except ObjectDoesNotExist:
# no attributes file: not accessible
return False
path_basename = basename(path)
# "public" is a deprecated alias for "unenrolled".
access_patterns = [] # type: List[Text]
for kind in access_kinds:
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
return False
# }}}
# {{{ 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*[|>])"
"(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):
# type: (Text) -> Text
lines = yaml_str.split("\n")
jinja_lines = []
i = 0
line_count = len(lines)
while i < line_count:
l = lines[i]
yaml_block_scalar_match = YAML_BLOCK_START_SCALAR_RE.search(l)
if yaml_block_scalar_match is not None:
unprocessed_block_lines = []
allow_jinja = bool(yaml_block_scalar_match.group(2))
l = YAML_BLOCK_START_SCALAR_RE.sub(
r"\1\3", l)
unprocessed_block_lines.append(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():
unprocessed_block_lines.append(l)
i += 1
continue
line_indent = len(LEADING_SPACES_RE.match(l).group(1))
if line_indent <= block_start_indent:
break
else:
unprocessed_block_lines.append(l)
i += 1
if not allow_jinja:
jinja_lines.append("{% raw %}")
jinja_lines.extend(unprocessed_block_lines)
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 %}")
i += 1
else:
jinja_lines.append(l)
i += 1
return "\n".join(jinja_lines)
class GitTemplateLoader(BaseTemplateLoader):
def __init__(self, repo, commit_sha):
# 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):
# 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):
# 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(),
))
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
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):
# type: (Repo_ish, Text, bytes, bool) -> Any
"""Return decoded, struct-ified YAML data structure from
the given file in *repo* at *commit_sha*.
See :class:`relate.utils.Struct` for more on
struct-ification.
"""
if cached:
from six.moves.urllib.parse import quote_plus
cache_key = "%%%2".join(
(CACHE_KEY_ROOT,
quote_plus(repo.controldir()), quote_plus(full_name),
commit_sha.decode()))
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)
return result
# }}}
# {{{ 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):
html_parser.HTMLParser.__init__(self)
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(
_attr_to_string(k, v) for k, v in six.iteritems(attrs))))
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
class LinkFixerTreeprocessor(Treeprocessor):
def __init__(self, md, course, commit_sha, reverse_func):
Treeprocessor.__init__(self)
self.md = md
self.course = course
self.commit_sha = commit_sha
self.reverse_func = reverse_func
def reverse(self, viewname, args):
frag = None
new_args = []
for arg in args:
if isinstance(arg, PreserveFragment):
s = arg.s
frag_index = s.find("#")
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
def process_url(self, url):
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,
PreserveFragment(path)))
elif url.startswith("repocur:"):
path = url[8:]
return self.reverse("relate-get_current_repo_file",
args=(
self.get_course_identifier(),
PreserveFragment(path)))
elif url.strip() == "calendar:":
return self.reverse("relate-view_calendar",
args=(self.get_course_identifier(),))
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)
for child in 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!)
from six.moves import cStringIO
for i, (html, safe) in enumerate(self.md.htmlStash.rawHtmlBlocks):
outf = cStringIO()
parser = TagProcessingHTMLParser(outf, self.process_tag)
parser.feed(html)
self.md.htmlStash.rawHtmlBlocks[i] = (outf.getvalue(), safe)
class LinkFixerExtension(Extension):
def __init__(self, course, commit_sha, reverse_func):
# type: (Optional[Course], bytes, Optional[Callable]) -> None
Extension.__init__(self)
self.course = course
self.commit_sha = commit_sha
self.reverse_func = reverse_func
def extendMarkdown(self, md, md_globals): # noqa
md.treeprocessors["relate_link_fixer"] = \
LinkFixerTreeprocessor(md, self.course, self.commit_sha,
reverse_func=self.reverse_func)
def remove_prefix(prefix, s):
# type: (Text, Text) -> Text
if s.startswith(prefix):
return s[len(prefix):]
else:
return s
JINJA_PREFIX = "[JINJA]"
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
use_jinja=True, # type: bool
jinja_env={}, # type: Dict
):
# type: (...) -> Text
if reverse_func is None:
from django.urls import reverse
reverse_func = 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)
return result
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
if use_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)
# }}}
if validate_only:
return ""
from course.mdx_mathjax import MathJaxExtension
import markdown
result = markdown.markdown(text,
extensions=[
LinkFixerExtension(course, commit_sha, reverse_func=reverse_func),
MathJaxExtension(),
"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):
# 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
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*$")
class AtTimePostprocessor(DatespecPostprocessor):
def __init__(self, hour, minute, second=0):
# type: (int, int, int) -> None
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(