1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17 #
18 # $Id: install_util.py,v 1.8 2002-09-10 00:18:20 richard Exp $
20 __doc__ = """
21 Support module to generate and check fingerprints of installed files.
22 """
24 import os, sha, shutil
26 # ".filter", ".index", ".item", ".newitem" are roundup-specific
27 sgml_file_types = [".xml", ".ent", ".html", ".filter", ".index", ".item", ".newitem"]
28 hash_file_types = [".py", ".sh", ".conf", ".cgi", '']
29 slast_file_types = [".css"]
31 digested_file_types = sgml_file_types + hash_file_types + slast_file_types
34 def checkDigest(filename):
35 """Read file, check for valid fingerprint, return TRUE if ok"""
36 # open and read file
37 inp = open(filename, "r")
38 lines = inp.readlines()
39 inp.close()
41 # get fingerprint from last line
42 if lines[-1][:6] == "#SHA: ":
43 # handle .py/.sh comment
44 fingerprint = lines[-1][6:].strip()
45 elif lines[-1][:10] == "<!-- SHA: ":
46 # handle xml/html files
47 fingerprint = lines[-1][10:]
48 fingerprint = fingerprint.replace('-->', '')
49 fingerprint = fingerprint.strip()
50 elif lines[-1][:8] == "/* SHA: ":
51 # handle css files
52 fingerprint = lines[-1][8:]
53 fingerprint = fingerprint.replace('*/', '')
54 fingerprint = fingerprint.strip()
55 else:
56 return 0
57 del lines[-1]
59 # calculate current digest
60 digest = sha.new()
61 for line in lines:
62 digest.update(line)
64 # compare current to stored digest
65 return fingerprint == digest.hexdigest()
68 class DigestFile:
69 """ A class that you can use like open() and that calculates
70 and writes a SHA digest to the target file.
71 """
73 def __init__(self, filename):
74 self.filename = filename
75 self.digest = sha.new()
76 self.file = open(self.filename, "w")
78 def write(self, data):
79 self.file.write(data)
80 self.digest.update(data)
82 def close(self):
83 file, ext = os.path.splitext(self.filename)
85 if ext in sgml_file_types:
86 self.file.write("<!-- SHA: %s -->\n" % (self.digest.hexdigest(),))
87 elif ext in hash_file_types:
88 self.file.write("#SHA: %s\n" % (self.digest.hexdigest(),))
89 elif ext in slast_file_types:
90 self.file.write("/* SHA: %s */\n" % (self.digest.hexdigest(),))
92 self.file.close()
95 def copyDigestedFile(src, dst, copystat=1):
96 """ Copy data from `src` to `dst`, adding a fingerprint to `dst`.
97 If `copystat` is true, the file status is copied, too
98 (like shutil.copy2).
99 """
100 if os.path.isdir(dst):
101 dst = os.path.join(dst, os.path.basename(src))
103 dummy, ext = os.path.splitext(src)
104 if ext not in digested_file_types:
105 if copystat:
106 return shutil.copy2(src, dst)
107 else:
108 return shutil.copyfile(src, dst)
110 fsrc = None
111 fdst = None
112 try:
113 fsrc = open(src, 'r')
114 fdst = DigestFile(dst)
115 shutil.copyfileobj(fsrc, fdst)
116 finally:
117 if fdst: fdst.close()
118 if fsrc: fsrc.close()
120 if copystat: shutil.copystat(src, dst)
123 def test():
124 import sys
126 testdata = open(sys.argv[0], 'r').read()
128 for ext in digested_file_types:
129 testfile = "__digest_test" + ext
131 out = DigestFile(testfile)
132 out.write(testdata)
133 out.close()
135 assert checkDigest(testfile), "digest ok w/o modification"
137 mod = open(testfile, 'r+')
138 mod.seek(0)
139 mod.write('# changed!')
140 mod.close()
142 assert not checkDigest(testfile), "digest fails after modification"
144 os.remove(testfile)
147 if __name__ == '__main__':
148 test()
150 # vim: set filetype=python ts=4 sw=4 et si