74721fe0d0458f01ce1401db6807304492674e43
[redakcja.git] / apps / compress / versioning / hash / __init__.py
1 import cStringIO
2 from hashlib import md5, sha1
3 import os
4
5 from compress.conf import settings
6 from compress.utils import concat, get_output_filename
7 from compress.versioning.base import VersioningBase
8
9 class HashVersioningBase(VersioningBase):
10     def __init__(self, hash_method):
11         self.hash_method = hash_method
12     
13     def needs_update(self, output_file, source_files, version):
14         output_file_name = get_output_filename(output_file, version)
15         ph = settings.COMPRESS_VERSION_PLACEHOLDER
16         of = output_file
17         try:
18             phi = of.index(ph)
19             old_version = output_file_name[phi:phi+len(ph)-len(of)]
20             return (version != old_version), version
21         except ValueError:
22             # no placeholder found, do not update, manual update if needed
23             return False, version
24             
25     def get_version(self, source_files):
26         buf = concat(source_files)
27         s = cStringIO.StringIO(buf)
28         version = self.get_hash(s)
29         s.close()
30         return version            
31             
32     def get_hash(self, f, CHUNK=2**16):
33         m = self.hash_method()
34         while 1:
35             chunk = f.read(CHUNK)
36             if not chunk:
37                 break
38             m.update(chunk)
39         return m.hexdigest()
40
41 class MD5Versioning(HashVersioningBase):
42     def __init__(self):
43         super(MD5Versioning, self).__init__(md5)
44
45 class SHA1Versioning(HashVersioningBase):
46     def __init__(self):
47         super(SHA1Versioning, self).__init__(sha1)