2017-11-01 13:26:10 +01:00
|
|
|
from StringTree import *
|
|
|
|
|
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:
|
|
|
|
|
if c == in_quote:
|
|
|
|
|
in_quote = None
|
|
|
|
|
else:
|
|
|
|
|
if c in [ '"', "'" ]:
|
|
|
|
|
in_quote = c
|
|
|
|
|
elif c == '#':
|
|
|
|
|
return r.strip()
|
|
|
|
|
r += c
|
|
|
|
|
return r
|
|
|
|
|
|
2017-11-01 13:26:10 +01:00
|
|
|
def parse(s): # export
|
|
|
|
|
slog(DEBUG, "parsing", s)
|
|
|
|
|
root = StringTree('', content='root')
|
|
|
|
|
sec = ''
|
|
|
|
|
for line in s.splitlines():
|
|
|
|
|
slog(DEBUG, "line=", line)
|
2017-11-02 11:47:04 +01:00
|
|
|
line = _cleanup_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
|
|
|
|
|
assignment = line.split('=')
|
|
|
|
|
if len(assignment) != 2:
|
|
|
|
|
raise Exception("failed to parse assignment", line)
|
|
|
|
|
slog(DEBUG, "sec=", sec, "assignment=", assignment)
|
|
|
|
|
root.add(sec + '.' + cleanup_string(assignment[0]), quote(assignment[1]))
|
|
|
|
|
return root
|
|
|
|
|
|
|
|
|
|
def read(path): # export
|
|
|
|
|
with open(path, 'r') as infile:
|
|
|
|
|
s = infile.read()
|
|
|
|
|
return parse(s)
|