tools/outputfile.py

changeset 272
9d52b119b3f5
parent 1
51d14b0c68c0
--- a/tools/outputfile.py	Mon Jun 27 02:01:52 2022 +0300
+++ b/tools/outputfile.py	Mon Jun 27 15:46:12 2022 +0300
@@ -31,31 +31,32 @@
 #
 
 class OutputFile:
-    def __init__ (self, filename):
+    def __init__(self, filename, *, verbose = False):
         self.filename = filename
+        self.verbose = verbose
+        self.body = ''
+        self.oldsum = ''
+    def __enter__(self):
         try:
-            with open (self.filename, "r") as file:
-                self.oldsum = file.readline()
-                self.oldsum = self.oldsum.replace ('// ', '').strip()
+            with open(self.filename, "r") as file:
+                self.oldsum = file.readline().strip().removeprefix('// ')
         except IOError:
-            self.oldsum = ''
-        self.body = ''
-
+            pass
+        return self
     def write(self, text):
         self.body += text
-
-    def save(self, verbose = False):
+    def __exit__(self, *args):
         from hashlib import sha256
         checksum = sha256(self.body.encode('utf-8')).hexdigest()
         if checksum == self.oldsum:
-            if verbose:
-                print ('%s is up to date' % self.filename)
+            if self.verbose:
+                print(f'{self.filename} is up to date')
             pass
         else:
-            with open (self.filename, "w") as file:
+            with open(self.filename, "w") as file:
                 file.write('// %s\n' % checksum)
                 file.write('// This file has been automatically generated. Do not edit by hand\n')
                 file.write('\n')
                 file.write(self.body)
-                if verbose:
-                    print('%s written' % self.filename)
+                if self.verbose:
+                    print(f'{self.filename} written ({checksum})')

mercurial