-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompiler.py
More file actions
313 lines (269 loc) · 10.6 KB
/
Copy pathcompiler.py
File metadata and controls
313 lines (269 loc) · 10.6 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
# -*- coding: utf-8 -*-
import collections
import logging
import os
import re
def _(s):
return s
Fragment = collections.namedtuple(
'Fragment',
(
'pos', # fpos of fragment start
'line', # line number of fragment
'column', # column number of fragment
'command', # NOOP, STOR, LOAD, JUMP
'args',
),
)
NEW_LINE_RE = re.compile(r'\r?\n', re.MULTILINE)
SPECIAL_COMMENT_RE = re.compile(
r'(?P<wrapper><!--\s*(?:'
r'@(?:(?i)(?:import|include))\s+(?P<filenames>.*?)'
r'|'
r'[@$](?P<variable>[a-zA-Z][^\s:=]*?)\s*(?:[\s:=]\s*(?P<value>.*?))?'
r')-->)',
re.DOTALL | re.LOCALE | re.MULTILINE | re.UNICODE
)
default_logger = logging.getLogger(__name__)
def get_file_content(filepath, encoding_hints=None):
"""
@type filepath: str
@type encoding_hints: [str, ...]
@rtype: (str, str)
"""
with open(filepath, 'rb') as fp:
b = fp.read()
# TODO: not implemented encoding detection yet
return 'utf-8', unicode(b, encoding='utf-8', errors='replace')
class CompileError(Exception):
def to_message(self):
return _('Compile Error: unknown error')
class CyclicInclusionError(CompileError):
def __init__(self, filepath, stack):
self.filepath = filepath
self.stack = stack
super(CyclicInclusionError, self).__init__(filepath, stack)
def to_message(self):
msg = _('Compile Error: file "{}" is included already from {}')
msg = msg.format(
self.filepath,
_(' from ').join(['"{}"'.format(s) for s in reversed(self.stack)])
)
return msg
class FileNotFoundError(CompileError):
def __init__(self, filename):
self.filename = filename
super(FileNotFoundError, self).__init__(filename)
def to_message(self):
s = _('Compile Error: file "{}" does not found').format(self.filename)
return s
class UnknownEncodingError(CompileError):
pass
class VariableNotFoundError(CompileError):
def __init__(self, filepath, fragment):
self.filepath = filepath
self.fragment = fragment
super(VariableNotFoundError, self).__init__(filepath, fragment)
def to_message(self):
s = _('Compile Error: variable "{}" does not found on "{}:{}:{}"')
s = s.format(self.fragment.args, self.filepath, self.fragment.line,
self.fragment.column)
return s
class Compiler(object):
NEW_LINE_RE = NEW_LINE_RE
SPECIAL_COMMENT_RE = SPECIAL_COMMENT_RE
logger = default_logger
def __init__(self, framework_paths=None, logger=None,
missing_file_behavior=None, missing_variable_behavior=None):
"""
@param framework_paths: [str, ...]
@param logger: logging.Logger
@param missing_file_behavior: 'ignore', 'logonly' or 'exception'
(default: 'logonly')
@param missing_variable_behavior: 'ignroe', 'logonly' or 'exception'
(default: 'ignore')
"""
if framework_paths is None:
self.framework_paths = tuple()
elif isinstance(framework_paths, tuple):
self.framework_paths = framework_paths
elif isinstance(framework_paths, basestring):
self.framework_paths = (framework_paths,)
else:
self.framework_paths = tuple(framework_paths)
if logger is not None:
self.logger = logger
if missing_file_behavior is None:
missing_file_behavior = 'logonly'
self.missing_file_behavior = missing_file_behavior
if missing_variable_behavior is None:
missing_variable_behavior = 'ignore'
self.missing_variable_behavior = missing_variable_behavior
self.parsed_caches = dict()
def resolve_path(self, filename, base_path):
"""
@type filename: str
@type base_path: str
@rtype: str
"""
_, ext = os.path.splitext(filename)
if not ext:
filename += '.kit'
ext = '.kit'
if ext == '.kit':
prefixes = ('', '_')
paths = (base_path,) + self.framework_paths
else:
prefixes = ('',)
paths = (base_path,)
for prefix in prefixes:
for path in paths:
filepath = os.path.realpath(os.path.join(path, filename))
basename = os.path.basename(filename)
if prefix and not basename.startswith(prefix):
filepath = os.path.join(
os.path.dirname(filepath),
prefix + os.path.basename(filename)
)
if os.path.exists(filepath):
self.logger.debug('Using %s for %s', filepath, filename)
return filepath
return None
def normalize_path(self, filepath=None, filename=None, basepath=None):
if filepath:
filepath = os.path.realpath(filepath)
elif filename and basepath:
filepath = self.resolve_path(filename, basepath)
else:
pass # TODO: handle assert
return filepath
def get_new_signature(self, filepath):
"""
@param filepath: `realpath`ed full path of file
@type filepath: str
@return: tuple of inode number, mtime and size
@rtye: (int, int, int) or None
"""
cached_signature = None
if filepath in self.parsed_caches:
cache = self.parsed_caches[filepath]
cached_signature = cache['signature']
stat = os.stat(filepath)
signature = stat.st_ino, stat.st_mtime, stat.st_size
if cached_signature and signature == cached_signature:
signature = None
return signature
def parse_str(self, s):
"""
@type s: str
@rtype: [(int, int, int, str, str), ...]
"""
parsed = []
pos = 0
line = 1
column = 1
for m in self.SPECIAL_COMMENT_RE.finditer(s):
if m.start('wrapper') > pos:
subs = s[pos:m.start('wrapper')]
parsed.append(Fragment(pos, line, column, 'NOOP', subs))
pos = m.start('wrapper')
subs = self.NEW_LINE_RE.split(s[:pos])
line = len(subs)
column = len(subs[-1]) + 1
if m.group('filenames'):
for filename in m.group('filenames').split(','):
filename = filename.strip().strip('\'"')
parsed.append(Fragment(pos, line, column, 'JUMP',
filename))
elif m.group('value'):
value = m.group('value').strip()
parsed.append(Fragment(pos, line, column, 'STOR',
(m.group('variable'), value)))
else: # m.group('variable')
parsed.append(Fragment(pos, line, column, 'LOAD',
m.group('variable')))
pos = m.end('wrapper')
subs = self.NEW_LINE_RE.split(s[:pos])
line = len(subs)
column = len(subs[-1]) + 1
parsed.append(Fragment(pos, line, column, 'NOOP', s[pos:]))
return parsed
def parse_file(self, filepath=None, filename=None, basepath=None):
filepath = self.normalize_path(filepath, filename, basepath)
if filepath is None or not os.path.exists(filepath):
ex = FileNotFoundError(filepath)
if self.missing_file_behavior == 'exception':
raise ex
if self.missing_file_behavior == 'logonly':
self.logger.warn(ex.to_message())
return None
signature = self.get_new_signature(filepath)
if signature:
_, ext = os.path.splitext(filepath)
encoding, s = get_file_content(filepath)
if ext == '.kit':
data = self.parse_str(s)
else:
data = [Fragment(0, 1, 1, 'NOOP', s)]
self.parsed_caches[filepath] = dict(
signature=signature,
encoding=encoding,
data=data,
)
for i in range(len(data)):
fragment = data[i]
if fragment.command == 'JUMP':
subfilepath = self.parse_file(
filename=fragment.args,
basepath=os.path.dirname(filepath)
)
data[i] = Fragment(fragment.pos,
fragment.line,
fragment.column,
'JUMP',
subfilepath)
return filepath
def generate_to_list(self, filepath, context=None, stack=None):
filepath = os.path.realpath(filepath)
if context is None:
context = dict()
if stack is None:
stack = tuple()
if filepath in stack:
raise CyclicInclusionError(filepath, stack)
compiled = []
if filepath not in self.parsed_caches:
filepath = self.parse_file(filepath=filepath)
cache = self.parsed_caches.get(filepath, {})
for fragment in cache.get('data', []):
if fragment.command == 'NOOP':
compiled.append(fragment.args)
elif fragment.command == 'STOR':
context[fragment.args[0]] = fragment.args[1]
elif fragment.command == 'LOAD':
if fragment.args not in context:
ex = VariableNotFoundError(filepath, fragment)
if self.missing_variable_behavior == 'exception':
raise ex
elif self.missing_variable_behavior == 'logonly':
self.logger.warn(ex.to_message())
compiled.append(context.get(fragment.args, ''))
elif fragment.command == 'JUMP':
compiled.extend(
self.generate_to_list(fragment.args, context.copy(),
stack + (filepath,))
)
return compiled
def generate_to_str(self, filepath):
return ''.join(self.generate_to_list(filepath))
def generate_to_file(self, dest, src):
dest = os.path.realpath(dest)
d = os.path.dirname(dest)
if not os.path.exists(d):
os.makedirs(d)
s = self.generate_to_str(src)
# TODO: not implemented encoding detection yet
s = s.encode('utf-8')
with open(dest, 'wb') as fp:
fp.write(s)
return