file.line with mode=replace on an empty file should return False

Fixes #31135

If a file exists but is empty, we are stack tracing on a call to
the body.split(os.linesep) function. This fix sets the body variable
to an empty string instead of stack tracing when the file is empty.

This allows the function to return ``False``, since no match can be
found in an empty file.

I also adjusted one of the ``line`` variables in the ``replace`` block
because it was shadowing the outer line function scope.
This commit is contained in:
rallytime 2016-11-03 14:58:50 -06:00
parent 94a00c66eb
commit 5f181cf00d

View file

@ -1512,9 +1512,13 @@ def line(path, content, match=None, mode=None, location=None,
body = os.linesep.join([line for line in body.split(os.linesep) if line.find(match) < 0])
elif mode == 'replace':
body = os.linesep.join([(_get_line_indent(line, content, indent)
if (line.find(match) > -1 and not line == content) else line)
for line in body.split(os.linesep)])
if os.stat(path).st_size == 0:
log.debug('Cannot find text to replace. File \'{0}\' is empty.'.format(path))
body = ''
else:
body = os.linesep.join([(_get_line_indent(file_line, content, indent)
if (file_line.find(match) > -1 and not file_line == content) else file_line)
for file_line in body.split(os.linesep)])
elif mode == 'insert':
if not location and not before and not after:
raise CommandExecutionError('On insert must be defined either "location" or "before/after" conditions.')