""" Telltale files helpers """ import datetime import logging import os log = logging.getLogger(__name__) class TelltaleFile: """ Telltale file helper class """ 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" 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() ) ) 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 """ try: return datetime.datetime.fromtimestamp( os.stat(self.filepath).st_mtime ) except FileNotFoundError: log.info('Telltale file not found (%s)', self.filepath) return None def update(self): """ Update the telltale file """ log.info('Update telltale file (%s)', self.filepath) try: os.utime(self.filepath, None) except FileNotFoundError: # pylint: disable=consider-using-with open(self.filepath, 'a', encoding="utf-8").close() def remove(self): """ Remove the telltale file """ try: os.remove(self.filepath) return True except FileNotFoundError: return True