From 980afad15c42d19b7af768edb8ae116e92fb7639 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pierre-Elliott=20B=C3=A9cue?= Date: Wed, 30 Apr 2014 21:30:58 +0200 Subject: [PATCH] =?UTF-8?q?[cranslib/conffile]=20Une=20librairie=20pour=20?= =?UTF-8?q?g=C3=A9rer=20les=20fichiers=20de=20configuration?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * S'utilise avec un context manager, le but est de faire un fichier temporaire de backup, et de s'assurer qu'on ferme bien le fichier dans lequel on écrit au fur et à mesure du temps --- cranslib/conffile.py | 81 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 cranslib/conffile.py diff --git a/cranslib/conffile.py b/cranslib/conffile.py new file mode 100644 index 00000000..6b8feb79 --- /dev/null +++ b/cranslib/conffile.py @@ -0,0 +1,81 @@ +#!/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)