Debian Codegraph @

flask_flatpages/parsers/yaml.py

raw
1 """Module for YAML metadata parser."""
2
3 import operator
4 from itertools import takewhile
5
6 from yaml import (
7 BlockMappingStartToken,
8 BlockSequenceStartToken,
9 DocumentEndToken,
10 DocumentStartToken,
11 FlowMappingStartToken,
12 FlowSequenceStartToken,
13 KeyToken,
14 SafeLoader,
15 ScalarToken,
16 )
17
18 from ..utils import NamedStringIO
19
20
21 START_TOKENS = (
22 BlockMappingStartToken,
23 BlockSequenceStartToken,
24 DocumentStartToken,
25 FlowMappingStartToken,
26 FlowSequenceStartToken,
27 KeyToken,
28 )
29
30
31 def _check_continue_parsing_tokens(token):
32 return not (
33 isinstance(token, (DocumentStartToken, DocumentEndToken))
34 or token is None
35 )
36
37
38 def _check_newline_token(token):
39 return (
40 isinstance(token, ScalarToken)
41 and token.style is None
42 and "\n" in token.value
43 )
44
45
46 def legacy_parser(content):
47 """Legacy YAML parser."""
48 lines = iter(content.split("\n"))
49
50 # Read lines until an empty line is encountered.
51 meta = "\n".join(takewhile(operator.methodcaller("strip"), lines))
52 # The rest is the content. `lines` is an iterator so it continues
53 # where `itertools.takewhile` left it.
54 content = "\n".join(lines)
55 return meta, content
56
57
58 def libyaml_parser(content, path):
59 """YAML parser."""
60 yaml_loader = SafeLoader(NamedStringIO(content, path))
61 yaml_loader.get_token() # Get stream start token
62 token = yaml_loader.get_token()
63 if not isinstance(token, START_TOKENS):
64 meta = ""
65 content = content.lstrip("\n")
66 else:
67 lines = content.split("\n")
68 if isinstance(token, DocumentStartToken):
69 token = yaml_loader.get_token()
70 newline_token = None
71 while _check_continue_parsing_tokens(token):
72 try:
73 token = yaml_loader.get_token()
74 if _check_newline_token(token) and newline_token is None:
75 newline_token = token
76 except Exception:
77 break
78 if token is None and newline_token is None:
79 meta = content
80 content = ""
81 else:
82 if token is not None:
83 meta_end_line = token.end_mark.line + 1
84 else:
85 meta_end_line = newline_token.start_mark.line
86 meta_end_line += lines[meta_end_line:].index("")
87 meta = "\n".join(lines[:meta_end_line])
88 content = "\n".join(lines[meta_end_line:]).lstrip("\n")
89 return meta, content