cache module
[matrix.git] / matrix / cache.py
1 # Copyright (C) 2006-2008 Movial Oy
2 # Authors: Timo Savola <tsavola@movial.fi>
3
4 import os
5 import re
6 from sets import Set as set
7
8 import config
9 import git
10
11 Error = RuntimeError
12
13 regex = re.compile(r'([^\s]+)[\s]?([^\s]*)')
14
15 def contains(c):
16         if c.from_platform:
17                 return True
18
19         for repo in (c.repo, c.meta):
20                 if git.ls_files(repo.path, ['-m', '-d']):
21                         if config.force:
22                                 return False
23                         else:
24                                 raise Error('Dirty files in ' + repo.path)
25
26         path = get_path(c)
27         if not os.path.exists(path):
28                 return False
29
30         file = open(path)
31         try:
32                 line = file.readline()
33         finally:
34                 file.close()
35
36         match = regex.match(line)
37         if not match:
38                 return False
39
40         hash, flagstring = match.groups()
41
42         if hash != get_component_hash(c):
43                 if config.debug:
44                         print 'New changes in', c.repo.path
45                 return False
46
47         if flagstring:
48                 flags = flagstring.split(',')
49         else:
50                 flags = []
51
52         if set(flags) != set(c.flags):
53                 if config.debug:
54                         print 'Obsolete flags for', c.repo.path
55                 return False
56
57         return True
58
59 def update(c):
60         path = get_path(c)
61
62         dir = os.path.dirname(path)
63         if not os.path.exists(dir):
64                 os.makedirs(dir)
65
66         file = open(path, 'w')
67         done = False
68         try:
69                 print >>file, get_component_hash(c), ','.join(c.flags)
70                 done = True
71         finally:
72                 file.close()
73                 if not done:
74                         os.remove(path)
75
76 def remove(c):
77         path = get_path(c)
78         if os.path.exists(path):
79                 os.remove(path)
80
81 def get_path(c):
82         return os.path.join(config.cache_dir, c.name)
83
84 def get_component_hash(c):
85         return '%s+%s' % (get_repository_hash(c.repo),
86                           get_repository_hash(c.meta))
87
88 def get_repository_hash(repo):
89         if repo.active_hash is None:
90                 repo.active_hash = git.rev_parse(repo.path, 'HEAD')
91         return repo.active_hash