#!/usr/bin/python3
# SafeWriteFile -*- mode: python; coding: utf-8 -*-
#
# This file is a writable file object.  It writes to a specified newname,
# and when closed, renames the file to the realname.  If the object is
# deleted, without being closed, this rename isn't done.  If abort() is
# called, it also disables the rename.
#
# Copyright (c) 2001 Adam Heath <doogie@debian.org>
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

from shutil import copy2
from os import rename

class ObjectNotAllowed(Exception):
    pass

class InvalidMode(Exception):
    pass

class SafeWriteFile:
    def __init__(self, newname, realname, mode="w", bufsize=-1):

        if not isinstance(newname, str):
            raise ObjectNotAllowed(newname)
        if not isinstance(realname, str):
            raise ObjectNotAllowed(realname)

        if "r" in mode:
            raise InvalidMode(mode)
        if "a" in mode or "+" in mode:
            copy2(realname, newname)
        self.fobj=open(newname, mode, bufsize)
        self.newname=newname
        self.realname=realname
        self.__abort=False

    def close(self):
        self.fobj.close()
        if not (self.closed and self.__abort):
            rename(self.newname, self.realname)

    def abort(self):
        self.__abort=True

    def __del__(self):
        self.abort()
        del self.fobj

    def __getattr__(self, attr):
        try:
            return self.__dict__[attr]
        except:
            return eval("self.fobj." + attr)

if __name__ == "__main__":
    import time
    f=SafeWriteFile("sf.new", "sf.data")
    f.write("test\n")
    f.flush()
    time.sleep(1)
    f.close()

# vim:ts=4:sw=4:et:
