Use a regex in installutils.get_directive instead of line splitting

This will allow for whitespace around the separator and changes the
default space separator into white space (space + tabs) to be more
generic and work better on Ubuntu which uses tabs in its Apache
configuration.

https://pagure.io/freeipa/issue/7490

Signed-off-by: Rob Crittenden <rcritten@redhat.com>
Reviewed-By: Florence Blanc-Renaud <frenaud@redhat.com>
This commit is contained in:
Rob Crittenden 2018-04-17 11:05:30 -04:00 committed by Florence Blanc-Renaud
parent ae6c8d2c7a
commit e16e5cd0a6
2 changed files with 33 additions and 2 deletions

View File

@ -605,13 +605,20 @@ def get_directive(filename, directive, separator=' '):
:returns: The (unquoted) value if the directive was found, None otherwise :returns: The (unquoted) value if the directive was found, None otherwise
""" """
# Special case: consider space as "white space" so tabs are allowed
if separator == ' ':
separator = '[ \t]+'
fd = open(filename, "r") fd = open(filename, "r")
for line in fd: for line in fd:
if line.lstrip().startswith(directive): if line.lstrip().startswith(directive):
line = line.strip() line = line.strip()
(directive, sep, value) = line.partition(separator) match = re.match(r'{}\s*{}\s*(.*)'.format(directive, separator),
if not sep or not value: line)
if match:
value = match.group(1)
else:
raise ValueError("Malformed directive: {}".format(line)) raise ValueError("Malformed directive: {}".format(line))
result = unquote_directive_value(value.strip(), '"') result = unquote_directive_value(value.strip(), '"')

View File

@ -98,6 +98,30 @@ class test_set_directive(object):
os.remove(filename) os.remove(filename)
class test_get_directive(object):
def test_get_directive(self, tmpdir):
configfile = tmpdir.join('config')
configfile.write(''.join(EXAMPLE_CONFIG))
assert '1' == installutils.get_directive(str(configfile),
'foo',
separator='=')
assert '2' == installutils.get_directive(str(configfile),
'foobar',
separator='=')
class test_get_directive_whitespace(object):
def test_get_directive(self, tmpdir):
configfile = tmpdir.join('config')
configfile.write(''.join(WHITESPACE_CONFIG))
assert '1' == installutils.get_directive(str(configfile),
'foo')
assert '2' == installutils.get_directive(str(configfile),
'foobar')
def test_directivesetter(tempdir): def test_directivesetter(tempdir):
filename = os.path.join(tempdir, 'example.conf') filename = os.path.join(tempdir, 'example.conf')
with open(filename, 'w') as f: with open(filename, 'w') as f: