a298961cdefabad439dbb91a4ceb32e003fbf1de
[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
10 class HashVersioningBase(VersioningBase):
11
12     def __init__(self, hash_method):
13         self.hash_method = hash_method
14
15     def needs_update(self, output_file, source_files, version):
16         output_file_name = get_output_filename(output_file, version)
17         ph = settings.COMPRESS_VERSION_PLACEHOLDER
18         of = output_file
19         try:
20             phi = of.index(ph)
21             old_version = output_file_name[phi:phi + len(ph) - len(of)]
22             return (version != old_version), version
23         except ValueError:
24             # no placeholder found, do not update, manual update if needed
25             return False, version
26
27     def get_version(self, source_files):
28         buf = concat(source_files)
29         s = cStringIO.StringIO(buf)
30         version = self.get_hash(s)
31         s.close()
32         return version
33
34     def get_hash(self, f, CHUNK=2 ** 16):
35         m = self.hash_method()
36         while 1:
37             chunk = f.read(CHUNK)
38             if not chunk:
39                 break
40             m.update(chunk)
41         return m.hexdigest()
42
43
44 class MD5Versioning(HashVersioningBase):
45
46     def __init__(self):
47         super(MD5Versioning, self).__init__(md5)
48
49
50 class SHA1Versioning(HashVersioningBase):
51
52     def __init__(self):
53         super(SHA1Versioning, self).__init__(sha1)