Coverage for pystratum_common/Util.py : 0%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import os
3from pystratum_backend.StratumStyle import StratumStyle
6class Util:
7 """
8 A helper class with miscellaneous functions that don;t belong somewhere else.
9 """
11 # ------------------------------------------------------------------------------------------------------------------
12 @staticmethod
13 def write_two_phases(filename: str, data: str, io: StratumStyle) -> 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 than 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 kep in tact 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 str filename: The name of the file were the data must be stored.
25 :param str data: The data that must be written.
26 :param StratumStyle 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# ----------------------------------------------------------------------------------------------------------------------