2 from __future__ import absolute_import
3 import errno, os, tempfile
10 return pickle.load(f, encoding='bytes')
12 import cPickle as pickle
13 pickle_load = pickle.load
16 class Error(Exception):
20 def __init__(self, filename):
21 # Map a "dev:ino" node to a list of paths associated with that node.
23 # Map a path to a "dev:ino" node.
25 self._filename = filename
26 self._save_prepared = None
30 f = open(filename, 'rb')
32 if e.errno == errno.ENOENT:
38 self._node_paths = pickle_load(f)
42 # Set up the reverse hard link index.
43 for node, paths in compat.items(self._node_paths):
45 self._path_node[path] = node
47 def prepare_save(self):
48 """ Commit all of the relevant data to disk. Do as much work
49 as possible without actually making the changes visible."""
50 if self._save_prepared:
51 raise Error('save of %r already in progress' % self._filename)
53 (dir, name) = os.path.split(self._filename)
54 (ffd, self._tmpname) = tempfile.mkstemp(b'.tmp', name, dir)
57 f = os.fdopen(ffd, 'wb', 65536)
62 pickle.dump(self._node_paths, f, 2)
67 tmpname = self._tmpname
71 self._save_prepared = True
73 def commit_save(self):
74 if not self._save_prepared:
75 raise Error('cannot commit save of %r; no save prepared'
78 os.rename(self._tmpname, self._filename)
80 else: # No data -- delete _filename if it exists.
82 os.unlink(self._filename)
84 if e.errno == errno.ENOENT:
88 self._save_prepared = None
92 os.unlink(self._tmpname)
98 def add_path(self, path, dev, ino):
100 node = b'%d:%d' % (dev, ino)
101 self._path_node[path] = node
102 link_paths = self._node_paths.get(node)
103 if link_paths and path not in link_paths:
104 link_paths.append(path)
106 self._node_paths[node] = [path]
108 def _del_node_path(self, node, path):
109 link_paths = self._node_paths[node]
110 link_paths.remove(path)
112 del self._node_paths[node]
114 def change_path(self, path, new_dev, new_ino):
115 prev_node = self._path_node.get(path)
117 self._del_node_path(prev_node, path)
118 self.add_path(new_dev, new_ino, path)
120 def del_path(self, path):
121 # Path may not be in db (if updating a pre-hardlink support index).
122 node = self._path_node.get(path)
124 self._del_node_path(node, path)
125 del self._path_node[path]
127 def node_paths(self, dev, ino):
128 node = b'%d:%d' % (dev, ino)
129 return self._node_paths[node]