#!/usr/bin/env python # -*- coding: utf-8 -*- # # Library designed to write in config files data # safely. # # Author : Pierre-Elliott Bécue # License : GPLv3 # Date : 30/05/2014 import tempfile import shutil import sys import time class ConfFile(object): """Class handling ConfigFiles """ def __init__(self, filename): self._name = filename self._backup = None self._fd = None def __enter__(self): """This file is used in context manager In case of syntax "with ConfFile("blop") as troll, troll will bind on self """ self.safe_open() return self def __exit__(self, etype, evalue, etraceback): """Closes file, and, if there is any traceback, restores the backup """ self._fd.close() if etype: # In case of exception, cleans the mess. self.restore() def safe_open(self): """Open a file in writemode but backups it before. """ self._backup = tempfile.NamedTemporaryFile() try: shutil.copyfile(self._name, self._backup.name) except IOError: self._backup = None self._fd = open(self._name, 'w') def write(self, data): """Writes data into file """ self._fd.write(data) def restore(self): """Restores the tempfile """ if self._backup is not None: shutil.copyfile(self._backup.name, self._name) def header(self, comment="#"): myHeader = """******************************************************************************************** This file was generated automatically using the software %s. You should not modify it directly if you don't know what you are doing. Date : %s ********************************************************************************************""" % (sys.argv[0].split("/")[-1], time.strftime("%d/%m/%Y - %H:%M:%S", time.localtime())) myHeader = comment + myHeader.replace("\n", "\n%s" % (comment,)) myHeader += "\n\n" self.write(myHeader)