1 | # Copyright Bruno da Silva de Oliveira 2003. Use, modification and |
---|
2 | # distribution is subject to the Boost Software License, Version 1.0. |
---|
3 | # (See accompanying file LICENSE_1_0.txt or copy at |
---|
4 | # http:#www.boost.org/LICENSE_1_0.txt) |
---|
5 | |
---|
6 | import os |
---|
7 | import md5 |
---|
8 | |
---|
9 | #============================================================================== |
---|
10 | # SmartFile |
---|
11 | #============================================================================== |
---|
12 | class SmartFile(object): |
---|
13 | ''' |
---|
14 | A file-like object used for writing files. The given file will only be |
---|
15 | actually written to disk if there's not a file with the same name, or if |
---|
16 | the existing file is *different* from the file to be written. |
---|
17 | ''' |
---|
18 | |
---|
19 | def __init__(self, filename, mode='w'): |
---|
20 | self.filename = filename |
---|
21 | self.mode = mode |
---|
22 | self._contents = [] |
---|
23 | self._closed = False |
---|
24 | |
---|
25 | |
---|
26 | def __del__(self): |
---|
27 | if not self._closed: |
---|
28 | self.close() |
---|
29 | |
---|
30 | |
---|
31 | def write(self, string): |
---|
32 | self._contents.append(string) |
---|
33 | |
---|
34 | |
---|
35 | def _dowrite(self, contents): |
---|
36 | f = file(self.filename, self.mode) |
---|
37 | f.write(contents) |
---|
38 | f.close() |
---|
39 | |
---|
40 | |
---|
41 | def _GetMD5(self, string): |
---|
42 | return md5.new(string).digest() |
---|
43 | |
---|
44 | |
---|
45 | def close(self): |
---|
46 | # if the filename doesn't exist, write the file right away |
---|
47 | this_contents = ''.join(self._contents) |
---|
48 | if not os.path.isfile(self.filename): |
---|
49 | self._dowrite(this_contents) |
---|
50 | else: |
---|
51 | # read the contents of the file already in disk |
---|
52 | f = file(self.filename) |
---|
53 | other_contents = f.read() |
---|
54 | f.close() |
---|
55 | # test the md5 for both files |
---|
56 | this_md5 = self._GetMD5(this_contents) |
---|
57 | other_md5 = self._GetMD5(other_contents) |
---|
58 | if this_md5 != other_md5: |
---|
59 | self._dowrite(this_contents) |
---|
60 | self._closed = True |
---|