Replace the output file atomically

When writing the new .data file, first write the new content, then replace
the target. This way, there isn't a temporary state in which the file is
partially written. This temporary state can be misleading if the build is
interrupted. It's annoying if you're watching changes to the output and the
changes appear as emptying the file following by the new version appearing.
Now interrupted builds don't leave a file that appears to be up to date but
isn't, and when watching the output, there's a single transition to the new
version.

Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
This commit is contained in:
Gilles Peskine 2022-09-21 22:00:06 +02:00
parent 22514eb99b
commit c217f48251

View File

@ -92,9 +92,11 @@ def write_data_file(filename: str,
"""
if caller is None:
caller = os.path.basename(sys.argv[0])
with open(filename, 'w') as out:
tempfile = filename + '.new'
with open(tempfile, 'w') as out:
out.write('# Automatically generated by {}. Do not edit!\n'
.format(caller))
for tc in test_cases:
tc.write(out)
out.write('\n# End of automatically generated file.\n')
os.replace(tempfile, filename)