|
1 # Copyright (C) 2005, Giovanni Bajo |
|
2 # Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc. |
|
3 # |
|
4 # This program is free software; you can redistribute it and/or |
|
5 # modify it under the terms of the GNU General Public License |
|
6 # as published by the Free Software Foundation; either version 2 |
|
7 # of the License, or (at your option) any later version. |
|
8 # |
|
9 # This program is distributed in the hope that it will be useful, |
|
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
12 # GNU General Public License for more details. |
|
13 # |
|
14 # You should have received a copy of the GNU General Public License |
|
15 # along with this program; if not, write to the Free Software |
|
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA |
|
17 |
|
18 _orig_open = open |
|
19 |
|
20 class _BkFile: |
|
21 def __init__(self, file, mode, bufsize): |
|
22 import os |
|
23 self.__filename = file |
|
24 self.__backup = file + '~' |
|
25 try: |
|
26 os.unlink(self.__backup) |
|
27 except os.error: |
|
28 pass |
|
29 try: |
|
30 os.rename(file, self.__backup) |
|
31 except os.error: |
|
32 self.__backup = None |
|
33 self.__file = _orig_open(file, mode, bufsize) |
|
34 self.closed = self.__file.closed |
|
35 self.fileno = self.__file.fileno |
|
36 self.flush = self.__file.flush |
|
37 self.isatty = self.__file.isatty |
|
38 self.mode = self.__file.mode |
|
39 self.name = self.__file.name |
|
40 self.read = self.__file.read |
|
41 self.readinto = self.__file.readinto |
|
42 self.readline = self.__file.readline |
|
43 self.readlines = self.__file.readlines |
|
44 self.seek = self.__file.seek |
|
45 self.softspace = self.__file.softspace |
|
46 self.tell = self.__file.tell |
|
47 self.truncate = self.__file.truncate |
|
48 self.write = self.__file.write |
|
49 self.writelines = self.__file.writelines |
|
50 |
|
51 def close(self): |
|
52 self.__file.close() |
|
53 if self.__backup is None: |
|
54 return |
|
55 try: |
|
56 from cmp import do_cmp |
|
57 except: |
|
58 from filecmp import cmp |
|
59 do_cmp = cmp |
|
60 # don't use cmp.cmp because of NFS bugs :-( and |
|
61 # anyway, the stat mtime values differ so do_cmp will |
|
62 # most likely be called anyway |
|
63 if do_cmp(self.__backup, self.__filename): |
|
64 import os |
|
65 os.unlink(self.__filename) |
|
66 os.rename(self.__backup, self.__filename) |
|
67 |
|
68 def open(file, mode = 'r', bufsize = -1): |
|
69 if 'w' not in mode: |
|
70 return _orig_open(file, mode, bufsize) |
|
71 return _BkFile(file, mode, bufsize) |