2019-05-19 13:15:27 +00:00
|
|
|
from jwutils.stree.StringTree import *
|
2017-11-01 13:26:10 +01:00
|
|
|
from jwutils.log import *
|
|
|
|
|
|
2017-11-02 11:47:04 +01:00
|
|
|
def _cleanup_line(line):
|
|
|
|
|
line = line.strip()
|
|
|
|
|
r = ''
|
|
|
|
|
in_quote = None
|
|
|
|
|
for c in line:
|
2017-11-26 21:25:01 +01:00
|
|
|
# slog(DEBUG, "in_quote = >" + str(in_quote) + "<")
|
|
|
|
|
if in_quote is not None:
|
|
|
|
|
if c == in_quote:
|
|
|
|
|
in_quote = None
|
2017-11-02 11:47:04 +01:00
|
|
|
else:
|
|
|
|
|
if c in [ '"', "'" ]:
|
|
|
|
|
in_quote = c
|
2017-11-05 16:35:41 +01:00
|
|
|
elif in_quote is None and c == '#':
|
2017-11-02 11:47:04 +01:00
|
|
|
return r.strip()
|
|
|
|
|
r += c
|
2017-11-26 21:25:01 +01:00
|
|
|
if len(r) >= 2 and r[0] in [ '"', "'" ] and r[-1] == r[0]:
|
|
|
|
|
return r[1:-1]
|
2017-11-02 11:47:04 +01:00
|
|
|
return r
|
|
|
|
|
|
2020-04-04 11:14:33 +02:00
|
|
|
def parse(s, allow_full_lines=True, root_content='root'): # export
|
2017-11-01 13:26:10 +01:00
|
|
|
slog(DEBUG, "parsing", s)
|
2020-04-04 11:14:33 +02:00
|
|
|
root = StringTree('', content=root_content)
|
2017-11-01 13:26:10 +01:00
|
|
|
sec = ''
|
|
|
|
|
for line in s.splitlines():
|
|
|
|
|
slog(DEBUG, "line=", line)
|
2017-11-02 11:47:04 +01:00
|
|
|
line = _cleanup_line(line)
|
2017-11-26 21:25:01 +01:00
|
|
|
#slog(DEBUG, "cleaned line=", line)
|
2017-11-01 13:26:10 +01:00
|
|
|
if not len(line):
|
|
|
|
|
continue
|
|
|
|
|
if line[0] == '[':
|
|
|
|
|
if line[-1] == ']':
|
|
|
|
|
sec = line[1:-1]
|
|
|
|
|
elif line[-1] == '[':
|
|
|
|
|
if len(sec):
|
|
|
|
|
sec += '.'
|
|
|
|
|
sec += line[1:-1]
|
|
|
|
|
else:
|
|
|
|
|
raise Exception("failed to parse section line", line)
|
|
|
|
|
if root.get(sec) is None:
|
|
|
|
|
root.add(sec)
|
|
|
|
|
continue
|
|
|
|
|
elif line[0] == ']':
|
|
|
|
|
assert(len(sec) > 0)
|
|
|
|
|
sec = '.'.join(sec.split('.')[0:-1])
|
|
|
|
|
continue
|
2017-11-12 16:08:34 +01:00
|
|
|
lhs = ''
|
|
|
|
|
rhs = None
|
|
|
|
|
for c in line:
|
|
|
|
|
if rhs is None:
|
|
|
|
|
if c == '=':
|
|
|
|
|
rhs = ''
|
|
|
|
|
continue
|
|
|
|
|
lhs += c
|
|
|
|
|
continue
|
|
|
|
|
rhs += c
|
|
|
|
|
|
2019-05-19 13:15:27 +00:00
|
|
|
split = True
|
2017-11-12 16:08:34 +01:00
|
|
|
if rhs is None:
|
2019-05-19 13:15:27 +00:00
|
|
|
if not allow_full_lines:
|
|
|
|
|
raise Exception("failed to parse assignment", line)
|
|
|
|
|
rhs = 'empty'
|
|
|
|
|
split = False
|
|
|
|
|
root.add(sec + '.' + cleanup_string(lhs), cleanup_string(rhs), split=split)
|
2017-11-01 13:26:10 +01:00
|
|
|
return root
|
|
|
|
|
|
2020-04-04 11:14:33 +02:00
|
|
|
def read(path, root_content='root'): # export
|
2017-11-01 13:26:10 +01:00
|
|
|
with open(path, 'r') as infile:
|
|
|
|
|
s = infile.read()
|
2020-04-04 11:14:33 +02:00
|
|
|
return parse(s, root_content=root_content)
|