-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathread_annotations.py
More file actions
executable file
·186 lines (156 loc) · 4.98 KB
/
read_annotations.py
File metadata and controls
executable file
·186 lines (156 loc) · 4.98 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
#!/usr/bin/env python3
"""read_annotations
Usage:
read_annotations.py [options] <file>
Options:
--single-line-comment=<start> Single line comment
--multi-line-comment="<start> <end>" Multi line comment
-h --help Show this screen.
--version Show version.
"""
from docopt import docopt
import string
class ParserReader:
def __init__(self, text):
self.text = text
self.pos = 0 # position
def peek(self):
return self.text[self.pos]
def read_while(self, fn):
j = self.pos
while j<len(self.text) and fn(self.text[j], j):
j+=1
if j > self.pos:
r = self.text[self.pos:j]
self.pos = j
return r
else: return None
def space(self):
return self.read_while(lambda c, i: c == " ")
def name(self):
return self.read_while(lambda c, i: c in string.ascii_letters)
def constant(self):
self.consume(['"'])
constant = self.read_while(lambda c, i: c != '"')
self.expect(['"'])
return constant
def consume(self, lst):
"""try to read one string in s from text, return it if found"""
if type(lst) == str: lst = list(lst)
for s in lst:
if self.text[self.pos:self.pos+len(s)] == s:
self.pos += len(s)
return s
return None
def expect(self, lst):
found = self.consume(lst)
if found:
return found
raise Exception("parsing error, expected one of " + str(lst) + ", got '" + self.text[self.pos:self.pos+50] + "', in '" + self.text + "'")
def parse(s):
result = {}
pr = ParserReader(s)
pr.space()
name = pr.name()
if name:
pr.space()
op = pr.consume(["="])
if op:
pr.space()
result["type"] = "field"
result["name"] = name
result["op"] = op
if pr.peek() == '"':
result["value"] = pr.constant()
elif pr.peek() == '{':
result["type"] = "field-start"
else:
result["value"] = pr.read_while(lambda c,i: c !=" " and c!="\n")
return result
elif pr.peek() == '}':
result["type"] = "field-end"
return result
def read_annotations(it, slc=None, mlc=None, read_everything=False):
"""
it: line iterator
slc: single line comment
mlc: multi line comment
"""
# multi line comment start and end
mlcs = []
if mlc:
if not type(mlc) == list:
mlc = [mlc]
for i in mlc:
mlcs.append(i.split(' '))
# helper function
def parse_comment(line):
p = None
if slc and slc in line:
comment = line[line.find(slc)+len(slc):]
return parse(comment)
for mlc1, mlc2 in mlcs:
if mlc1 and mlc1 in line:
start = line.find(mlc1) + len(mlc1)
end = line.find(mlc2)
if end < 0:
raise RuntimeError('multiline comments spanning multiple lines currently not supported')
comment = line[start:end]
return parse(comment)
return p
result = []
fields = {}
other = []
for line in it:
line = line.replace('\n','')
p = parse_comment(line)
if not p:
if read_everything:
other.append(line)
continue
if len(other) > 0:
result += [{
"type": "other",
"value": "\n".join(other),
}]
other = []
if p["type"] == "field":
fields[p["name"]] = p
result += [p]
elif p["type"] == "field-start":
content = ""
try:
while True:
line = it.__next__()
tmp = parse_comment(line)
if tmp and tmp["type"] == "field-end":
break
content += line
except StopIteration:
raise ValueError("could not find closing of field " + p["name"])
op = p["op"]
if p["name"] in fields:
p = fields[p["name"]]
p["value"] += "...\n" + content
else:
p["type"] = "field"
p["value"] = content
fields[p["name"]] = p
result += [p]
if len(other) > 0:
result += [{
"type": "other",
"value": "\n".join(other),
}]
return result, fields
if __name__ == '__main__':
arguments = docopt(__doc__, version='read_annotations')
with open(arguments["<file>"]) as f:
it = iter(f)
annotations = read_annotations(
it,
arguments["--single-line-comment"],
arguments["--multi-line-comment"]
)
for i in annotations:
print(i)