1
# Copyright (C) 2007, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Python implementations of Dirstate Helper functions."""
23
# We cannot import the dirstate module, because it loads this module
24
# All we really need is the IN_MEMORY_MODIFIED constant
25
from bzrlib import errors
26
from bzrlib.dirstate import DirState
29
def pack_stat(st, _b64=binascii.b2a_base64, _pack=struct.Struct('>6L').pack):
30
"""Convert stat values into a packed representation
32
Not all of the fields from the stat included are strictly needed, and by
33
just encoding the mtime and mode a slight speed increase could be gained.
34
However, using the pyrex version instead is a bigger win.
36
# base64 encoding always adds a final newline, so strip it off
37
return _b64(_pack(st.st_size & 0xFFFFFFFF, int(st.st_mtime) & 0xFFFFFFFF,
38
int(st.st_ctime) & 0xFFFFFFFF, st.st_dev & 0xFFFFFFFF,
39
st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
42
def _unpack_stat(packed_stat):
43
"""Turn a packed_stat back into the stat fields.
45
This is meant as a debugging tool, should not be used in real code.
47
(st_size, st_mtime, st_ctime, st_dev, st_ino,
48
st_mode) = struct.unpack('>6L', binascii.a2b_base64(packed_stat))
49
return dict(st_size=st_size, st_mtime=st_mtime, st_ctime=st_ctime,
50
st_dev=st_dev, st_ino=st_ino, st_mode=st_mode)
53
def _bisect_path_left(paths, path):
54
"""Return the index where to insert path into paths.
56
This uses the dirblock sorting. So all children in a directory come before
57
the children of children. For example::
81
:param paths: A list of paths to search through
82
:param path: A single path to insert
83
:return: An offset where 'path' can be inserted.
84
:seealso: bisect.bisect_left
90
# Grab the dirname for the current dirblock
92
if _cmp_path_by_dirblock(cur, path) < 0:
99
def _bisect_path_right(paths, path):
100
"""Return the index where to insert path into paths.
102
This uses a path-wise comparison so we get::
112
:param paths: A list of paths to search through
113
:param path: A single path to insert
114
:return: An offset where 'path' can be inserted.
115
:seealso: bisect.bisect_right
121
# Grab the dirname for the current dirblock
123
if _cmp_path_by_dirblock(path, cur) < 0:
130
def bisect_dirblock(dirblocks, dirname, lo=0, hi=None, cache={}):
131
"""Return the index where to insert dirname into the dirblocks.
133
The return value idx is such that all directories blocks in dirblock[:idx]
134
have names < dirname, and all blocks in dirblock[idx:] have names >=
137
Optional args lo (default 0) and hi (default len(dirblocks)) bound the
138
slice of a to be searched.
143
dirname_split = cache[dirname]
145
dirname_split = dirname.split('/')
146
cache[dirname] = dirname_split
149
# Grab the dirname for the current dirblock
150
cur = dirblocks[mid][0]
152
cur_split = cache[cur]
154
cur_split = cur.split('/')
155
cache[cur] = cur_split
156
if cur_split < dirname_split: lo = mid + 1
161
def cmp_by_dirs(path1, path2):
162
"""Compare two paths directory by directory.
164
This is equivalent to doing::
166
cmp(path1.split('/'), path2.split('/'))
168
The idea is that you should compare path components separately. This
169
differs from plain ``cmp(path1, path2)`` for paths like ``'a-b'`` and
170
``a/b``. "a-b" comes after "a" but would come before "a/b" lexically.
172
:param path1: first path
173
:param path2: second path
174
:return: negative number if ``path1`` comes first,
175
0 if paths are equal,
176
and positive number if ``path2`` sorts first
178
if not isinstance(path1, str):
179
raise TypeError("'path1' must be a plain string, not %s: %r"
180
% (type(path1), path1))
181
if not isinstance(path2, str):
182
raise TypeError("'path2' must be a plain string, not %s: %r"
183
% (type(path2), path2))
184
return cmp(path1.split('/'), path2.split('/'))
187
def _cmp_path_by_dirblock(path1, path2):
188
"""Compare two paths based on what directory they are in.
190
This generates a sort order, such that all children of a directory are
191
sorted together, and grandchildren are in the same order as the
192
children appear. But all grandchildren come after all children.
194
:param path1: first path
195
:param path2: the second path
196
:return: negative number if ``path1`` comes first,
198
and a positive number if ``path2`` sorts first
200
if not isinstance(path1, str):
201
raise TypeError("'path1' must be a plain string, not %s: %r"
202
% (type(path1), path1))
203
if not isinstance(path2, str):
204
raise TypeError("'path2' must be a plain string, not %s: %r"
205
% (type(path2), path2))
206
dirname1, basename1 = os.path.split(path1)
207
key1 = (dirname1.split('/'), basename1)
208
dirname2, basename2 = os.path.split(path2)
209
key2 = (dirname2.split('/'), basename2)
210
return cmp(key1, key2)
213
def _read_dirblocks(state):
214
"""Read in the dirblocks for the given DirState object.
216
This is tightly bound to the DirState internal representation. It should be
217
thought of as a member function, which is only separated out so that we can
218
re-write it in pyrex.
220
:param state: A DirState object.
223
state._state_file.seek(state._end_of_header)
224
text = state._state_file.read()
225
# TODO: check the crc checksums. crc_measured = zlib.crc32(text)
227
fields = text.split('\0')
228
# Remove the last blank entry
229
trailing = fields.pop()
231
raise errors.DirstateCorrupt(state,
232
'trailing garbage: %r' % (trailing,))
233
# consider turning fields into a tuple.
235
# skip the first field which is the trailing null from the header.
237
# Each line now has an extra '\n' field which is not used
238
# so we just skip over it
240
# 3 fields for the key
241
# + number of fields per tree_data (5) * tree count
243
num_present_parents = state._num_present_parents()
244
tree_count = 1 + num_present_parents
245
entry_size = state._fields_per_entry()
246
expected_field_count = entry_size * state._num_entries
247
field_count = len(fields)
248
# this checks our adjustment, and also catches file too short.
249
if field_count - cur != expected_field_count:
250
raise errors.DirstateCorrupt(state,
251
'field count incorrect %s != %s, entry_size=%s, '\
252
'num_entries=%s fields=%r' % (
253
field_count - cur, expected_field_count, entry_size,
254
state._num_entries, fields))
256
if num_present_parents == 1:
257
# Bind external functions to local names
259
# We access all fields in order, so we can just iterate over
260
# them. Grab an straight iterator over the fields. (We use an
261
# iterator because we don't want to do a lot of additions, nor
262
# do we want to do a lot of slicing)
263
next = iter(fields).next
264
# Move the iterator to the current position
265
for x in xrange(cur):
267
# The two blocks here are deliberate: the root block and the
268
# contents-of-root block.
269
state._dirblocks = [('', []), ('', [])]
270
current_block = state._dirblocks[0][1]
272
append_entry = current_block.append
273
for count in xrange(state._num_entries):
277
if dirname != current_dirname:
278
# new block - different dirname
280
current_dirname = dirname
281
state._dirblocks.append((current_dirname, current_block))
282
append_entry = current_block.append
283
# we know current_dirname == dirname, so re-use it to avoid
284
# creating new strings
285
entry = ((current_dirname, name, file_id),
288
next(), # fingerprint
290
next() == 'y', # executable
291
next(), # packed_stat or revision_id
295
next(), # fingerprint
297
next() == 'y', # executable
298
next(), # packed_stat or revision_id
303
raise ValueError("trailing garbage in dirstate: %r" % trailing)
304
# append the entry to the current block
306
state._split_root_dirblock_into_contents()
308
fields_to_entry = state._get_fields_to_entry()
309
entries = [fields_to_entry(fields[pos:pos+entry_size])
310
for pos in xrange(cur, field_count, entry_size)]
311
state._entries_to_current_state(entries)
312
# To convert from format 2 => format 3
313
# state._dirblocks = sorted(state._dirblocks,
314
# key=lambda blk:blk[0].split('/'))
315
# To convert from format 3 => format 2
316
# state._dirblocks = sorted(state._dirblocks)
317
state._dirblock_state = DirState.IN_MEMORY_UNMODIFIED