python-mylib/mylib/telltale.py

53 lines
1.7 KiB
Python
Raw Normal View History

2022-04-12 12:59:20 +02:00
""" Telltale files helpers """
import datetime
import logging
import os
log = logging.getLogger(__name__)
class TelltaleFile:
"""Telltale file helper class"""
2022-04-12 12:59:20 +02:00
def __init__(self, filepath=None, filename=None, dirpath=None):
assert filepath or filename, "filename or filepath is required"
if filepath:
assert (
not filename or os.path.basename(filepath) == filename
), "filepath and filename does not match"
assert (
not dirpath or os.path.dirname(filepath) == dirpath
), "filepath and dirpath does not match"
2022-04-12 12:59:20 +02:00
self.filename = filename if filename else os.path.basename(filepath)
self.dirpath = (
dirpath if dirpath else (os.path.dirname(filepath) if filepath else os.getcwd())
2022-04-12 12:59:20 +02:00
)
self.filepath = filepath if filepath else os.path.join(self.dirpath, self.filename)
@property
def last_update(self):
"""Retreive last update datetime of the telltall file"""
2022-04-12 12:59:20 +02:00
try:
return datetime.datetime.fromtimestamp(os.stat(self.filepath).st_mtime)
2022-04-12 12:59:20 +02:00
except FileNotFoundError:
log.info("Telltale file not found (%s)", self.filepath)
2022-04-12 12:59:20 +02:00
return None
def update(self):
"""Update the telltale file"""
log.info("Update telltale file (%s)", self.filepath)
2022-04-12 12:59:20 +02:00
try:
os.utime(self.filepath, None)
except FileNotFoundError:
2023-01-06 19:36:14 +01:00
# pylint: disable=consider-using-with
open(self.filepath, "a", encoding="utf-8").close()
2022-04-12 12:59:20 +02:00
def remove(self):
"""Remove the telltale file"""
2022-04-12 12:59:20 +02:00
try:
os.remove(self.filepath)
return True
except FileNotFoundError:
return True