Switch to using shlex for config file parsing

This commit is contained in:
Stefano Rivera 2010-12-20 23:36:17 +02:00
parent 432ddc28ff
commit 3d03dcdb3f
2 changed files with 18 additions and 12 deletions

View File

@ -19,7 +19,9 @@ import os
import os.path import os.path
import pwd import pwd
import re import re
import shlex
import socket import socket
import StringIO
import sys import sys
class UDTConfig(object): class UDTConfig(object):
@ -46,20 +48,20 @@ class UDTConfig(object):
dictionary dictionary
""" """
config = {} config = {}
var_re = re.compile(r'^\s*([A-Z_]+?)=(.+?)\s*$')
for fn in ('/etc/devscripts.conf', '~/.devscripts'): for fn in ('/etc/devscripts.conf', '~/.devscripts'):
f = open(os.path.expanduser(fn), 'r') try:
f = open(os.path.expanduser(fn), 'r')
except IOError:
continue
for line in f: for line in f:
m = var_re.match(line) parsed = shlex.split(line, comments=True)
if m: if len(parsed) > 1 and not isinstance(f, StringIO.StringIO):
value = m.group(2) print >> sys.stderr, (
# This isn't quite the same as bash's parsing, but "W: Cannot parse variable assignment in %s: %s"
# mostly-compatible for configuration files that aren't % (f.name, line))
# broken like this: KEY=foo bar if len(parsed) >= 1 and '=' in parsed[0]:
if (len(value) > 2 and value[0] == value[-1] key, value = parsed[0].split('=', 1)
and value[0] in ("'", '"')): config[key] = value
value = value[1:-1]
config[m.group(1)] = value
f.close() f.close()
return config return config

View File

@ -63,6 +63,8 @@ SPACE_SUFFIX=yes
SINGLE_QUOTE='yes no' SINGLE_QUOTE='yes no'
DOUBLE_QUOTE="yes no" DOUBLE_QUOTE="yes no"
QUOTED_QUOTE="it's" QUOTED_QUOTE="it's"
PAIR_QUOTES="yes "a' no'
COMMAND_EXECUTION=a b
INHERIT=user INHERIT=user
REPEAT=no REPEAT=no
REPEAT=yes REPEAT=yes
@ -75,6 +77,8 @@ REPEAT=yes
'SINGLE_QUOTE': 'yes no', 'SINGLE_QUOTE': 'yes no',
'DOUBLE_QUOTE': 'yes no', 'DOUBLE_QUOTE': 'yes no',
'QUOTED_QUOTE': "it's", 'QUOTED_QUOTE': "it's",
'PAIR_QUOTES': 'yes a no',
'COMMAND_EXECUTION': 'a',
'INHERIT': 'user', 'INHERIT': 'user',
'REPEAT': 'yes', 'REPEAT': 'yes',
}) })