jwutils.misc: Add commit_tmpfile()

commit_tmpfile() is a better os.rename which doesn't do anything if
source and target files are equal, and logs if does something.

Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
Jan Lindemann 2020-04-08 08:50:54 +02:00
commit 47f4de938f

View file

@ -62,4 +62,13 @@ def get_derived_classes(mod, base): # export
r.append(c)
return r
def commit_tmpfile(tmp, path): # export
caller = log.get_caller_pos()
if os.path.isfile(path) and filecmp.cmp(tmp, path):
log.slog(log.INFO, "{} is up to date".format(path), caller=caller)
os.unlink(tmp)
else:
log.slog(log.NOTICE, "saving {}".format(path), caller=caller)
os.rename(path + '.tmp', path)
atexit.register(_cleanup)