Coverage for pystratum_common/Util.py: 0%
18 statements
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-13 08:46 +0200
« prev ^ index » next coverage.py v7.5.1, created at 2024-05-13 08:46 +0200
1import os
3from pystratum_backend.StratumIO import StratumIO
6class Util:
7 """
8 A utility class with miscellaneous functions that don't belong somewhere else.
9 """
11 # ------------------------------------------------------------------------------------------------------------------
12 @staticmethod
13 def write_two_phases(filename: str, data: str, io: StratumIO) -> None:
14 """
15 Writes a file in two phase to the filesystem.
17 First write the data to a temporary file (in the same directory) and then renames the temporary file. If the
18 file already exists and its content is equal to the data that must be written no action is taken. This has the
19 following advantages:
20 * In case of some write error (e.g. disk full) the original file is keept intact and no file with partially data
21 is written.
22 * Renaming a file is atomic. So, running processes will never read a partially written data.
24 :param filename: The name of the file were the data must be stored.
25 :param data: The data that must be written.
26 :param io: The output decorator.
27 """
28 write_flag = True
29 if os.path.exists(filename):
30 with open(filename, 'r') as file:
31 old_data = file.read()
32 if data == old_data:
33 write_flag = False
35 if write_flag:
36 tmp_filename = filename + '.tmp'
37 with open(tmp_filename, 'w+') as file:
38 file.write(data)
39 os.replace(tmp_filename, filename)
40 io.text('Wrote: <fso>{0}</fso>'.format(filename))
41 else:
42 io.text('File <fso>{0}</fso> is up to date'.format(filename))
44# ----------------------------------------------------------------------------------------------------------------------