Somewhat large overhaul to move the kiosk towards using normal python
[kiosk.git] / file_writer.py
1 #!/usr/bin/env python3
2
3 import constants
4 import os
5 from uuid import uuid4
6
7
8 class file_writer:
9     """Helper context to write a pages file."""
10
11     def __init__(self, filename: str, *, transformations=[]):
12         temp = "temp-" + str(uuid4())
13         self.temp_filename = os.path.join(constants.pages_dir, temp)
14         self.full_filename = os.path.join(constants.pages_dir, filename)
15         self.xforms = [file_writer.remove_tricky_unicode]
16         self.xforms.extend(transformations)
17         self.f = None
18
19     @staticmethod
20     def remove_tricky_unicode(x: str) -> str:
21         try:
22             x = x.replace("\u2018", "'").replace("\u2019", "'")
23             x = x.replace("\u201c", '"').replace("\u201d", '"')
24             x = x.replace("\u2e3a", "-").replace("\u2014", "-")
25         except:
26             pass
27         return x
28
29     def write(self, data):
30         for xform in self.xforms:
31             data = xform(data)
32         self.f.write(data.encode("utf-8"))
33
34     def __enter__(self):
35         self.f = open(self.temp_filename, "wb")
36         return self
37
38     def __exit__(self, exc_type, exc_value, exc_traceback):
39         self.close()
40         cmd = f'/bin/mv -f {self.temp_filename} "{self.full_filename}"'
41         os.system(cmd)
42         print(cmd)
43
44     def done(self):
45         self.close()
46
47     def close(self):
48         self.f.close()
49
50
51 # Test
52 #def toupper(x):
53 #   return x.upper()
54
55 #with file_writer("test", transformations=[toupper]) as fw:
56 #   fw.write(u"Another test!!")