Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. "Misc. utility functions/classes for admin documentation generator."
  2. import re
  3. from email.errors import HeaderParseError
  4. from email.parser import HeaderParser
  5. from inspect import cleandoc
  6. from django.urls import reverse
  7. from django.utils.regex_helper import _lazy_re_compile
  8. from django.utils.safestring import mark_safe
  9. try:
  10. import docutils.core
  11. import docutils.nodes
  12. import docutils.parsers.rst.roles
  13. except ImportError:
  14. docutils_is_available = False
  15. else:
  16. docutils_is_available = True
  17. def get_view_name(view_func):
  18. if hasattr(view_func, "view_class"):
  19. klass = view_func.view_class
  20. return f"{klass.__module__}.{klass.__qualname__}"
  21. mod_name = view_func.__module__
  22. view_name = getattr(view_func, "__qualname__", view_func.__class__.__name__)
  23. return mod_name + "." + view_name
  24. def parse_docstring(docstring):
  25. """
  26. Parse out the parts of a docstring. Return (title, body, metadata).
  27. """
  28. if not docstring:
  29. return "", "", {}
  30. docstring = cleandoc(docstring)
  31. parts = re.split(r"\n{2,}", docstring)
  32. title = parts[0]
  33. if len(parts) == 1:
  34. body = ""
  35. metadata = {}
  36. else:
  37. parser = HeaderParser()
  38. try:
  39. metadata = parser.parsestr(parts[-1])
  40. except HeaderParseError:
  41. metadata = {}
  42. body = "\n\n".join(parts[1:])
  43. else:
  44. metadata = dict(metadata.items())
  45. if metadata:
  46. body = "\n\n".join(parts[1:-1])
  47. else:
  48. body = "\n\n".join(parts[1:])
  49. return title, body, metadata
  50. def parse_rst(text, default_reference_context, thing_being_parsed=None):
  51. """
  52. Convert the string from reST to an XHTML fragment.
  53. """
  54. overrides = {
  55. "doctitle_xform": True,
  56. "initial_header_level": 3,
  57. "default_reference_context": default_reference_context,
  58. "link_base": reverse("django-admindocs-docroot").rstrip("/"),
  59. "raw_enabled": False,
  60. "file_insertion_enabled": False,
  61. }
  62. thing_being_parsed = thing_being_parsed and "<%s>" % thing_being_parsed
  63. # Wrap ``text`` in some reST that sets the default role to ``cmsreference``,
  64. # then restores it.
  65. source = """
  66. .. default-role:: cmsreference
  67. %s
  68. .. default-role::
  69. """
  70. parts = docutils.core.publish_parts(
  71. source % text,
  72. source_path=thing_being_parsed,
  73. destination_path=None,
  74. writer_name="html",
  75. settings_overrides=overrides,
  76. )
  77. return mark_safe(parts["fragment"])
  78. #
  79. # reST roles
  80. #
  81. ROLES = {
  82. "model": "%s/models/%s/",
  83. "view": "%s/views/%s/",
  84. "template": "%s/templates/%s/",
  85. "filter": "%s/filters/#%s",
  86. "tag": "%s/tags/#%s",
  87. }
  88. def create_reference_role(rolename, urlbase):
  89. def _role(name, rawtext, text, lineno, inliner, options=None, content=None):
  90. if options is None:
  91. options = {}
  92. node = docutils.nodes.reference(
  93. rawtext,
  94. text,
  95. refuri=(
  96. urlbase
  97. % (
  98. inliner.document.settings.link_base,
  99. text.lower(),
  100. )
  101. ),
  102. **options,
  103. )
  104. return [node], []
  105. docutils.parsers.rst.roles.register_canonical_role(rolename, _role)
  106. def default_reference_role(
  107. name, rawtext, text, lineno, inliner, options=None, content=None
  108. ):
  109. if options is None:
  110. options = {}
  111. context = inliner.document.settings.default_reference_context
  112. node = docutils.nodes.reference(
  113. rawtext,
  114. text,
  115. refuri=(
  116. ROLES[context]
  117. % (
  118. inliner.document.settings.link_base,
  119. text.lower(),
  120. )
  121. ),
  122. **options,
  123. )
  124. return [node], []
  125. if docutils_is_available:
  126. docutils.parsers.rst.roles.register_canonical_role(
  127. "cmsreference", default_reference_role
  128. )
  129. for name, urlbase in ROLES.items():
  130. create_reference_role(name, urlbase)
  131. # Match the beginning of a named, unnamed, or non-capturing groups.
  132. named_group_matcher = _lazy_re_compile(r"\(\?P(<\w+>)")
  133. unnamed_group_matcher = _lazy_re_compile(r"\(")
  134. non_capturing_group_matcher = _lazy_re_compile(r"\(\?\:")
  135. def replace_metacharacters(pattern):
  136. """Remove unescaped metacharacters from the pattern."""
  137. return re.sub(
  138. r"((?:^|(?<!\\))(?:\\\\)*)(\\?)([?*+^$]|\\[bBAZ])",
  139. lambda m: m[1] + m[3] if m[2] else m[1],
  140. pattern,
  141. )
  142. def _get_group_start_end(start, end, pattern):
  143. # Handle nested parentheses, e.g. '^(?P<a>(x|y))/b' or '^b/((x|y)\w+)$'.
  144. unmatched_open_brackets, prev_char = 1, None
  145. for idx, val in enumerate(pattern[end:]):
  146. # Check for unescaped `(` and `)`. They mark the start and end of a
  147. # nested group.
  148. if val == "(" and prev_char != "\\":
  149. unmatched_open_brackets += 1
  150. elif val == ")" and prev_char != "\\":
  151. unmatched_open_brackets -= 1
  152. prev_char = val
  153. # If brackets are balanced, the end of the string for the current named
  154. # capture group pattern has been reached.
  155. if unmatched_open_brackets == 0:
  156. return start, end + idx + 1
  157. def _find_groups(pattern, group_matcher):
  158. prev_end = None
  159. for match in group_matcher.finditer(pattern):
  160. if indices := _get_group_start_end(match.start(0), match.end(0), pattern):
  161. start, end = indices
  162. if prev_end and start > prev_end or not prev_end:
  163. yield start, end, match
  164. prev_end = end
  165. def replace_named_groups(pattern):
  166. r"""
  167. Find named groups in `pattern` and replace them with the group name. E.g.,
  168. 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$
  169. 2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$
  170. 3. ^(?P<a>\w+)/b/(\w+) ==> ^<a>/b/(\w+)
  171. 4. ^(?P<a>\w+)/b/(?P<c>\w+) ==> ^<a>/b/<c>
  172. """
  173. group_pattern_and_name = [
  174. (pattern[start:end], match[1])
  175. for start, end, match in _find_groups(pattern, named_group_matcher)
  176. ]
  177. for group_pattern, group_name in group_pattern_and_name:
  178. pattern = pattern.replace(group_pattern, group_name)
  179. return pattern
  180. def replace_unnamed_groups(pattern):
  181. r"""
  182. Find unnamed groups in `pattern` and replace them with '<var>'. E.g.,
  183. 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$
  184. 2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$
  185. 3. ^(?P<a>\w+)/b/(\w+) ==> ^(?P<a>\w+)/b/<var>
  186. 4. ^(?P<a>\w+)/b/((x|y)\w+) ==> ^(?P<a>\w+)/b/<var>
  187. """
  188. final_pattern, prev_end = "", None
  189. for start, end, _ in _find_groups(pattern, unnamed_group_matcher):
  190. if prev_end:
  191. final_pattern += pattern[prev_end:start]
  192. final_pattern += pattern[:start] + "<var>"
  193. prev_end = end
  194. return final_pattern + pattern[prev_end:]
  195. def remove_non_capturing_groups(pattern):
  196. r"""
  197. Find non-capturing groups in the given `pattern` and remove them, e.g.
  198. 1. (?P<a>\w+)/b/(?:\w+)c(?:\w+) => (?P<a>\\w+)/b/c
  199. 2. ^(?:\w+(?:\w+))a => ^a
  200. 3. ^a(?:\w+)/b(?:\w+) => ^a/b
  201. """
  202. group_start_end_indices = _find_groups(pattern, non_capturing_group_matcher)
  203. final_pattern, prev_end = "", None
  204. for start, end, _ in group_start_end_indices:
  205. final_pattern += pattern[prev_end:start]
  206. prev_end = end
  207. return final_pattern + pattern[prev_end:]