Fixed empty file case in modules.file.append()

Lines are simply inserted at the beginning of the file for empty files.
This commit is contained in:
Luper Rouch 2013-10-07 16:31:42 +02:00
parent e5631f2671
commit db8eef8f32
2 changed files with 21 additions and 5 deletions

View File

@ -1188,12 +1188,21 @@ def append(path, *args):
with salt.utils.fopen(path, "r+") as ofile:
# Make sure we have a newline at the end of the file
ofile.seek(-1, os.SEEK_END)
if ofile.read(1) != '\n':
ofile.seek(0, os.SEEK_END)
ofile.write('\n')
try:
ofile.seek(-1, os.SEEK_END)
except IOError as exc:
if exc.errno == errno.EINVAL:
# Empty file, simply append lines at the beginning of the file
pass
else:
raise
else:
ofile.seek(0, os.SEEK_END)
if ofile.read(1) != '\n':
ofile.seek(0, os.SEEK_END)
ofile.write('\n')
else:
ofile.seek(0, os.SEEK_END)
# Append lines
for line in args:
ofile.write('{0}\n'.format(line))

View File

@ -126,18 +126,25 @@ class FileModuleTestCase(TestCase):
Check that file.append works consistently on files with and without
newlines at end of file.
'''
# File ending with a newline
with tempfile.NamedTemporaryFile() as tfile:
tfile.write('foo\n')
tfile.flush()
filemod.append(tfile.name, 'bar')
with open(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), 'foo\nbar\n')
# File not ending with a newline
with tempfile.NamedTemporaryFile() as tfile:
tfile.write('foo')
tfile.flush()
filemod.append(tfile.name, 'bar')
with open(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), 'foo\nbar\n')
# A newline should not be added in empty files
with tempfile.NamedTemporaryFile() as tfile:
filemod.append(tfile.name, 'bar')
with open(tfile.name) as tfile2:
self.assertEqual(tfile2.read(), 'bar\n')
if __name__ == '__main__':