29 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
29 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
30 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
30 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
31 # |
31 # |
32 |
32 |
33 class OutputFile: |
33 class OutputFile: |
34 def __init__ (self, filename): |
34 def __init__(self, filename, *, verbose = False): |
35 self.filename = filename |
35 self.filename = filename |
|
36 self.verbose = verbose |
|
37 self.body = '' |
|
38 self.oldsum = '' |
|
39 def __enter__(self): |
36 try: |
40 try: |
37 with open (self.filename, "r") as file: |
41 with open(self.filename, "r") as file: |
38 self.oldsum = file.readline() |
42 self.oldsum = file.readline().strip().removeprefix('// ') |
39 self.oldsum = self.oldsum.replace ('// ', '').strip() |
|
40 except IOError: |
43 except IOError: |
41 self.oldsum = '' |
44 pass |
42 self.body = '' |
45 return self |
43 |
|
44 def write(self, text): |
46 def write(self, text): |
45 self.body += text |
47 self.body += text |
46 |
48 def __exit__(self, *args): |
47 def save(self, verbose = False): |
|
48 from hashlib import sha256 |
49 from hashlib import sha256 |
49 checksum = sha256(self.body.encode('utf-8')).hexdigest() |
50 checksum = sha256(self.body.encode('utf-8')).hexdigest() |
50 if checksum == self.oldsum: |
51 if checksum == self.oldsum: |
51 if verbose: |
52 if self.verbose: |
52 print ('%s is up to date' % self.filename) |
53 print(f'{self.filename} is up to date') |
53 pass |
54 pass |
54 else: |
55 else: |
55 with open (self.filename, "w") as file: |
56 with open(self.filename, "w") as file: |
56 file.write('// %s\n' % checksum) |
57 file.write('// %s\n' % checksum) |
57 file.write('// This file has been automatically generated. Do not edit by hand\n') |
58 file.write('// This file has been automatically generated. Do not edit by hand\n') |
58 file.write('\n') |
59 file.write('\n') |
59 file.write(self.body) |
60 file.write(self.body) |
60 if verbose: |
61 if self.verbose: |
61 print('%s written' % self.filename) |
62 print(f'{self.filename} written ({checksum})') |