blob: 6d8afff9687c0d09bace9a9282d633d9b49a8933 [file] [log] [blame]
mblighb62f7242009-07-29 14:34:30 +00001# Copyright 2009 Google Inc. Released under the GPL v2
2
3# This file contains the classes used for the known kernel versions persistent
4# storage
5
6import cPickle
7
8class item(object):
9 """Wrap a file item stored in a database."""
10 def __init__(self, name, size, timestamp):
11 assert type(size) == int
12 assert type(timestamp) == int
13
14 self.name = name
15 self.size = size
16 self.timestamp = timestamp
17
18
19 def __repr__(self):
20 return ("database.item('%s', %d, %d)" %
21 (self.name, self.size, self.timestamp))
22
23
24 def __eq__(self, other):
25 if not isinstance(other, item):
26 return NotImplemented
27
28 return (self.name == other.name and self.size == other.size and
29 self.timestamp == other.timestamp)
30
31
32 def __ne__(self, other):
33 return not self.__eq__(other)
34
35
36class database(object):
37 """
38 This is an Abstract Base Class for the file items database, not strictly
39 needed in Python because of the dynamic nature of the language but useful
40 to document the expected common API of the implementations.
41 """
42
43 def get_dictionary(self):
44 """
45 Should be implemented to open and read the persistent contents of
46 the database and return it as a key->value dictionary.
47 """
48 raise NotImplemented('get_dictionary not implemented')
49
50
51 def merge_dictionary(self, values):
52 """
53 Should be implemented to merge the "values" dictionary into the
54 database persistent contents (ie to update existent entries and to add
55 those that do not exist).
56 """
57 raise NotImplemented('merge_dictionary not implemented')
58
59
60class dict_database(database):
61 """
62 A simple key->value database that uses standard python pickle dump of
63 a dictionary object for persistent storage.
64 """
65 def __init__(self, path):
66 self.path = path
67
68
69 def get_dictionary(self, _open_func=open):
70 """
71 Return the key/value pairs as a standard dictionary.
72 """
73 try:
74 fd = _open_func(self.path, 'rb')
75 except IOError:
76 # no db file, considering as if empty dictionary
77 res = {}
78 else:
79 res = cPickle.load(fd)
80
81 return res
82
83
84 def merge_dictionary(self, values, _open_func=open):
85 """
86 Merge the contents of "values" with the current contents of the
87 database.
88 """
89 if not values:
90 return
91
92 contents = self.get_dictionary()
93 contents.update(values)
94 # FIXME implement some kind of protection against full disk problem
95 cPickle.dump(contents, _open_func(self.path, 'wb'),
96 protocol=cPickle.HIGHEST_PROTOCOL)