cache cache status
[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.cached is None:
17                 c.cached = __contains(c)
18
19         return c.cached
20
21 def __contains(c):
22         for repo in (c.repo, c.meta):
23                 if repo.dirty_files():
24                         if config.force:
25                                 return False
26                         else:
27                                 raise Error('Dirty files in ' + repo)
28
29         path = get_path(c)
30         if not os.path.exists(path):
31                 return False
32
33         file = open(path)
34         try:
35                 line = file.readline()
36         finally:
37                 file.close()
38
39         match = regex.match(line)
40         if not match:
41                 return False
42
43         hash, flagstring = match.groups()
44
45         if hash != get_hash(c):
46                 if config.debug:
47                         print 'New changes in', c.repo.path
48                 return False
49
50         if flagstring:
51                 flags = flagstring.split(',')
52         else:
53                 flags = []
54
55         if set(flags) != set(c.flags):
56                 if config.debug:
57                         print 'Obsolete flags for', c.repo.path
58                 return False
59
60         return True
61
62 def update(c):
63         path = get_path(c)
64
65         dir = os.path.dirname(path)
66         if not os.path.exists(dir):
67                 os.makedirs(dir)
68
69         file = open(path, 'w')
70         done = False
71         try:
72                 print >>file, get_hash(c), ','.join(c.flags)
73                 done = True
74         finally:
75                 file.close()
76                 if not done:
77                         os.remove(path)
78
79 def remove(c):
80         path = get_path(c)
81         if os.path.exists(path):
82                 os.remove(path)
83
84 def get_path(c):
85         return os.path.join(config.cache_dir, c.name)
86
87 def get_hash(c):
88         return '%s+%s' % (c.repo.get_hash(), c.meta.get_hash())