mirror of
https://github.com/valitydev/salt.git
synced 2024-11-07 17:09:03 +00:00
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:
parent
e5631f2671
commit
db8eef8f32
@ -1188,12 +1188,21 @@ def append(path, *args):
|
|||||||
|
|
||||||
with salt.utils.fopen(path, "r+") as ofile:
|
with salt.utils.fopen(path, "r+") as ofile:
|
||||||
# Make sure we have a newline at the end of the file
|
# Make sure we have a newline at the end of the file
|
||||||
ofile.seek(-1, os.SEEK_END)
|
try:
|
||||||
if ofile.read(1) != '\n':
|
ofile.seek(-1, os.SEEK_END)
|
||||||
ofile.seek(0, os.SEEK_END)
|
except IOError as exc:
|
||||||
ofile.write('\n')
|
if exc.errno == errno.EINVAL:
|
||||||
|
# Empty file, simply append lines at the beginning of the file
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
raise
|
||||||
else:
|
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:
|
for line in args:
|
||||||
ofile.write('{0}\n'.format(line))
|
ofile.write('{0}\n'.format(line))
|
||||||
|
|
||||||
|
@ -126,18 +126,25 @@ class FileModuleTestCase(TestCase):
|
|||||||
Check that file.append works consistently on files with and without
|
Check that file.append works consistently on files with and without
|
||||||
newlines at end of file.
|
newlines at end of file.
|
||||||
'''
|
'''
|
||||||
|
# File ending with a newline
|
||||||
with tempfile.NamedTemporaryFile() as tfile:
|
with tempfile.NamedTemporaryFile() as tfile:
|
||||||
tfile.write('foo\n')
|
tfile.write('foo\n')
|
||||||
tfile.flush()
|
tfile.flush()
|
||||||
filemod.append(tfile.name, 'bar')
|
filemod.append(tfile.name, 'bar')
|
||||||
with open(tfile.name) as tfile2:
|
with open(tfile.name) as tfile2:
|
||||||
self.assertEqual(tfile2.read(), 'foo\nbar\n')
|
self.assertEqual(tfile2.read(), 'foo\nbar\n')
|
||||||
|
# File not ending with a newline
|
||||||
with tempfile.NamedTemporaryFile() as tfile:
|
with tempfile.NamedTemporaryFile() as tfile:
|
||||||
tfile.write('foo')
|
tfile.write('foo')
|
||||||
tfile.flush()
|
tfile.flush()
|
||||||
filemod.append(tfile.name, 'bar')
|
filemod.append(tfile.name, 'bar')
|
||||||
with open(tfile.name) as tfile2:
|
with open(tfile.name) as tfile2:
|
||||||
self.assertEqual(tfile2.read(), 'foo\nbar\n')
|
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__':
|
if __name__ == '__main__':
|
||||||
|
Loading…
Reference in New Issue
Block a user