2019-04-16 18:16:48 +02:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
2023-01-27 18:04:13 +01:00
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License version 2 as
|
|
|
|
# published by the Free Software Foundation.
|
|
|
|
|
|
|
|
import os
|
|
|
|
import io
|
2019-04-16 18:16:48 +02:00
|
|
|
import sys
|
|
|
|
|
|
|
|
ROOTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
sys.path.insert(0, os.path.realpath(ROOTDIR))
|
|
|
|
|
|
|
|
|
|
|
|
def path(*segments, join=os.path.join):
|
2019-11-07 23:23:48 +01:00
|
|
|
result = join(ROOTDIR, *segments)
|
|
|
|
os.makedirs(os.path.dirname(result), exist_ok=True)
|
|
|
|
return result
|
2023-01-27 18:04:13 +01:00
|
|
|
|
|
|
|
|
|
|
|
class lazy():
|
|
|
|
|
|
|
|
def __init__(self, path):
|
|
|
|
self.path = path
|
|
|
|
self.buffer = io.StringIO()
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self.buffer
|
|
|
|
|
2024-10-11 16:43:28 +02:00
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
2023-01-27 18:04:13 +01:00
|
|
|
# get content of old file
|
|
|
|
try:
|
|
|
|
with open(self.path, encoding="utf-8") as fp:
|
|
|
|
old = fp.read()
|
|
|
|
except Exception:
|
|
|
|
old = None
|
|
|
|
|
|
|
|
# get new content
|
|
|
|
new = self.buffer.getvalue()
|
|
|
|
|
|
|
|
if new != old:
|
|
|
|
# rewrite entire file
|
|
|
|
with open(self.path, "w", encoding="utf-8") as fp:
|
|
|
|
fp.write(new)
|
|
|
|
else:
|
|
|
|
# only update atime and mtime
|
|
|
|
os.utime(self.path)
|