-
Notifications
You must be signed in to change notification settings - Fork 13
/
parsers.py
61 lines (43 loc) · 1.54 KB
/
parsers.py
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
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT License.
"""
import yaml
from html.parser import HTMLParser
from mistune import Renderer
from mechanical_markdown.step import Step
start_token = 'STEP'
end_token = 'END_STEP'
class MarkdownAnnotationError(Exception):
pass
class HTMLCommentParser(HTMLParser):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.comment_text = ""
def handle_comment(self, comment):
self.comment_text += comment
class RecipeParser(Renderer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.current_step = None
self.all_steps = []
def block_code(self, text, lang):
if lang is not None and lang.strip() in ('bash', 'sh') and self.current_step is not None:
self.current_step.add_command_block(text)
return ""
def block_html(self, text):
comment_parser = HTMLCommentParser()
comment_parser.feed(text)
comment_body = comment_parser.comment_text
if comment_body.find(end_token) >= 0:
if self.current_step is None:
raise MarkdownAnnotationError("Unexpected <!-- {} --> found".format(end_token))
self.all_steps.append(self.current_step)
self.current_step = None
return ""
start_pos = comment_body.find(start_token)
if start_pos < 0:
return ""
start_pos += len(start_token)
self.current_step = Step(yaml.safe_load(comment_body[start_pos:]))
return ""