]> arthur.barton.de Git - bup.git/blob - lib/bup/midx.py
split: separate opt handling and work; isolate packfile lifetime
[bup.git] / lib / bup / midx.py
1
2 from __future__ import absolute_import, print_function
3 import glob, os, struct
4
5 from bup import _helpers
6 from bup.compat import range
7 from bup.helpers import log, mmap_read
8 from bup.io import path_msg
9
10
11 MIDX_VERSION = 4
12
13 extract_bits = _helpers.extract_bits
14 _total_searches = 0
15 _total_steps = 0
16
17
18 class PackMidx:
19     """Wrapper which contains data from multiple index files.
20     Multiple index (.midx) files constitute a wrapper around index (.idx) files
21     and make it possible for bup to expand Git's indexing capabilities to vast
22     amounts of files.
23     """
24     def __init__(self, filename):
25         self.name = filename
26         self.force_keep = False
27         self.map = None
28         assert(filename.endswith(b'.midx'))
29         self.map = mmap_read(open(filename))
30         if self.map[0:4] != b'MIDX':
31             log('Warning: skipping: invalid MIDX header in %r\n'
32                 % path_msg(filename))
33             self.force_keep = True
34             self._init_failed()
35             return
36         ver = struct.unpack('!I', self.map[4:8])[0]
37         if ver < MIDX_VERSION:
38             log('Warning: ignoring old-style (v%d) midx %r\n'
39                 % (ver, path_msg(filename)))
40             self.force_keep = False  # old stuff is boring
41             self._init_failed()
42             return
43         if ver > MIDX_VERSION:
44             log('Warning: ignoring too-new (v%d) midx %r\n'
45                 % (ver, path_msg(filename)))
46             self.force_keep = True  # new stuff is exciting
47             self._init_failed()
48             return
49
50         self.bits = _helpers.firstword(self.map[8:12])
51         self.entries = 2**self.bits
52         self.fanout_ofs = 12
53         # fanout len is self.entries * 4
54         self.sha_ofs = self.fanout_ofs + self.entries * 4
55         self.nsha = self._fanget(self.entries - 1)
56         # sha table len is self.nsha * 20
57         self.which_ofs = self.sha_ofs + 20 * self.nsha
58         # which len is self.nsha * 4
59         self.idxnames = self.map[self.which_ofs + 4 * self.nsha:].split(b'\0')
60
61     def __del__(self):
62         self.close()
63
64     def __enter__(self):
65         return self
66
67     def __exit__(self, type, value, traceback):
68         self.close()
69
70     def _init_failed(self):
71         self.bits = 0
72         self.entries = 1
73         self.idxnames = []
74
75     def _fanget(self, i):
76         if i >= self.entries * 4 or i < 0:
77             raise IndexError('invalid midx index %d' % i)
78         ofs = self.fanout_ofs + i * 4
79         return _helpers.firstword(self.map[ofs : ofs + 4])
80
81     def _get(self, i):
82         if i >= self.nsha or i < 0:
83             raise IndexError('invalid midx index %d' % i)
84         ofs = self.sha_ofs + i * 20
85         return self.map[ofs : ofs + 20]
86
87     def _get_idx_i(self, i):
88         if i >= self.nsha or i < 0:
89             raise IndexError('invalid midx index %d' % i)
90         ofs = self.which_ofs + i * 4
91         return struct.unpack_from('!I', self.map, offset=ofs)[0]
92
93     def _get_idxname(self, i):
94         return self.idxnames[self._get_idx_i(i)]
95
96     def close(self):
97         if self.map is not None:
98             self.fanout = self.shatable = self.whichlist = self.idxnames = None
99             self.map.close()
100             self.map = None
101
102     def exists(self, hash, want_source=False):
103         """Return nonempty if the object exists in the index files."""
104         global _total_searches, _total_steps
105         _total_searches += 1
106         want = hash
107         el = extract_bits(want, self.bits)
108         if el:
109             start = self._fanget(el-1)
110             startv = el << (32-self.bits)
111         else:
112             start = 0
113             startv = 0
114         end = self._fanget(el)
115         endv = (el+1) << (32-self.bits)
116         _total_steps += 1   # lookup table is a step
117         hashv = _helpers.firstword(hash)
118         #print '(%08x) %08x %08x %08x' % (extract_bits(want, 32), startv, hashv, endv)
119         while start < end:
120             _total_steps += 1
121             #print '! %08x %08x %08x   %d - %d' % (startv, hashv, endv, start, end)
122             mid = start + (hashv - startv) * (end - start - 1) // (endv - startv)
123             #print '  %08x %08x %08x   %d %d %d' % (startv, hashv, endv, start, mid, end)
124             v = self._get(mid)
125             #print '    %08x' % self._num(v)
126             if v < want:
127                 start = mid+1
128                 startv = _helpers.firstword(v)
129             elif v > want:
130                 end = mid
131                 endv = _helpers.firstword(v)
132             else: # got it!
133                 return want_source and self._get_idxname(mid) or True
134         return None
135
136     def __iter__(self):
137         start = self.sha_ofs
138         for ofs in range(start, start + self.nsha * 20, 20):
139             yield self.map[ofs : ofs + 20]
140
141     def __len__(self):
142         return int(self.nsha)
143
144
145 def clear_midxes(dir=None):
146     for midx in glob.glob(os.path.join(dir, b'*.midx')):
147         os.unlink(midx)