2 from __future__ import absolute_import
3 import errno, os, tempfile
6 from bup.compat import pending_raise
11 return pickle.load(f, encoding='bytes')
13 import cPickle as pickle
14 pickle_load = pickle.load
17 class Error(Exception):
21 def __init__(self, filename):
22 # Map a "dev:ino" node to a list of paths associated with that node.
24 # Map a path to a "dev:ino" node.
26 self._filename = filename
27 self._save_prepared = None
31 f = open(filename, 'rb')
33 if e.errno == errno.ENOENT:
39 self._node_paths = pickle_load(f)
43 # Set up the reverse hard link index.
44 for node, paths in compat.items(self._node_paths):
46 self._path_node[path] = node
48 def prepare_save(self):
49 """ Commit all of the relevant data to disk. Do as much work
50 as possible without actually making the changes visible."""
51 if self._save_prepared:
52 raise Error('save of %r already in progress' % self._filename)
54 (dir, name) = os.path.split(self._filename)
55 (ffd, self._tmpname) = tempfile.mkstemp(b'.tmp', name, dir)
58 f = os.fdopen(ffd, 'wb', 65536)
63 pickle.dump(self._node_paths, f, 2)
68 tmpname = self._tmpname
72 self._save_prepared = True
74 def commit_save(self):
75 if not self._save_prepared:
76 raise Error('cannot commit save of %r; no save prepared'
79 os.rename(self._tmpname, self._filename)
81 else: # No data -- delete _filename if it exists.
83 os.unlink(self._filename)
85 if e.errno == errno.ENOENT:
89 self._save_prepared = None
93 os.unlink(self._tmpname)
99 def __exit__(self, type, value, traceback):
100 with pending_raise(value, rethrow=True):
103 def add_path(self, path, dev, ino):
104 # Assume path is new.
105 node = b'%d:%d' % (dev, ino)
106 self._path_node[path] = node
107 link_paths = self._node_paths.get(node)
108 if link_paths and path not in link_paths:
109 link_paths.append(path)
111 self._node_paths[node] = [path]
113 def _del_node_path(self, node, path):
114 link_paths = self._node_paths[node]
115 link_paths.remove(path)
117 del self._node_paths[node]
119 def change_path(self, path, new_dev, new_ino):
120 prev_node = self._path_node.get(path)
122 self._del_node_path(prev_node, path)
123 self.add_path(new_dev, new_ino, path)
125 def del_path(self, path):
126 # Path may not be in db (if updating a pre-hardlink support index).
127 node = self._path_node.get(path)
129 self._del_node_path(node, path)
130 del self._path_node[path]
132 def node_paths(self, dev, ino):
133 node = b'%d:%d' % (dev, ino)
134 return self._node_paths[node]