/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/_dirstate_helpers_py.py

  • Committer: Robert Collins
  • Date: 2010-05-06 23:41:35 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506234135-yivbzczw1sejxnxc
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
expected to return an object which can be used to unlock them. This reduces
duplicate code when using cleanups. The previous 'tokens's returned by
``Branch.lock_write`` and ``Repository.lock_write`` are now attributes
on the result of the lock_write. ``repository.RepositoryWriteLockResult``
and ``branch.BranchWriteLockResult`` document this. (Robert Collins)

``log._get_info_for_log_files`` now takes an add_cleanup callable.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Python implementations of Dirstate Helper functions."""
18
18
 
19
 
from __future__ import absolute_import
20
 
 
21
 
import binascii
22
19
import os
23
 
import struct
24
20
 
25
21
# We cannot import the dirstate module, because it loads this module
26
22
# All we really need is the IN_MEMORY_MODIFIED constant
27
 
from .dirstate import DirState, DirstateCorrupt
28
 
from ..sixish import (
29
 
    range,
30
 
    )
31
 
 
32
 
 
33
 
def pack_stat(st, _b64=binascii.b2a_base64, _pack=struct.Struct('>6L').pack):
34
 
    """Convert stat values into a packed representation
35
 
 
36
 
    Not all of the fields from the stat included are strictly needed, and by
37
 
    just encoding the mtime and mode a slight speed increase could be gained.
38
 
    However, using the pyrex version instead is a bigger win.
39
 
    """
40
 
    # base64 encoding always adds a final newline, so strip it off
41
 
    return _b64(_pack(st.st_size & 0xFFFFFFFF, int(st.st_mtime) & 0xFFFFFFFF,
42
 
                      int(st.st_ctime) & 0xFFFFFFFF, st.st_dev & 0xFFFFFFFF,
43
 
                      st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
44
 
 
45
 
 
46
 
def _unpack_stat(packed_stat):
47
 
    """Turn a packed_stat back into the stat fields.
48
 
 
49
 
    This is meant as a debugging tool, should not be used in real code.
50
 
    """
51
 
    (st_size, st_mtime, st_ctime, st_dev, st_ino,
52
 
     st_mode) = struct.unpack('>6L', binascii.a2b_base64(packed_stat))
53
 
    return dict(st_size=st_size, st_mtime=st_mtime, st_ctime=st_ctime,
54
 
                st_dev=st_dev, st_ino=st_ino, st_mode=st_mode)
 
23
from bzrlib import errors
 
24
from bzrlib.dirstate import DirState
55
25
 
56
26
 
57
27
def _bisect_path_left(paths, path):
93
63
        mid = (lo + hi) // 2
94
64
        # Grab the dirname for the current dirblock
95
65
        cur = paths[mid]
96
 
        if _lt_path_by_dirblock(cur, path):
 
66
        if _cmp_path_by_dirblock(cur, path) < 0:
97
67
            lo = mid + 1
98
68
        else:
99
69
            hi = mid
121
91
    hi = len(paths)
122
92
    lo = 0
123
93
    while lo < hi:
124
 
        mid = (lo + hi) // 2
 
94
        mid = (lo+hi)//2
125
95
        # Grab the dirname for the current dirblock
126
96
        cur = paths[mid]
127
 
        if _lt_path_by_dirblock(path, cur):
 
97
        if _cmp_path_by_dirblock(path, cur) < 0:
128
98
            hi = mid
129
99
        else:
130
100
            lo = mid + 1
146
116
    try:
147
117
        dirname_split = cache[dirname]
148
118
    except KeyError:
149
 
        dirname_split = dirname.split(b'/')
 
119
        dirname_split = dirname.split('/')
150
120
        cache[dirname] = dirname_split
151
121
    while lo < hi:
152
122
        mid = (lo + hi) // 2
155
125
        try:
156
126
            cur_split = cache[cur]
157
127
        except KeyError:
158
 
            cur_split = cur.split(b'/')
 
128
            cur_split = cur.split('/')
159
129
            cache[cur] = cur_split
160
 
        if cur_split < dirname_split:
161
 
            lo = mid + 1
162
 
        else:
163
 
            hi = mid
 
130
        if cur_split < dirname_split: lo = mid + 1
 
131
        else: hi = mid
164
132
    return lo
165
133
 
166
134
 
167
 
def lt_by_dirs(path1, path2):
 
135
def cmp_by_dirs(path1, path2):
168
136
    """Compare two paths directory by directory.
169
137
 
170
138
    This is equivalent to doing::
171
139
 
172
 
       operator.lt(path1.split('/'), path2.split('/'))
 
140
       cmp(path1.split('/'), path2.split('/'))
173
141
 
174
142
    The idea is that you should compare path components separately. This
175
 
    differs from plain ``path1 < path2`` for paths like ``'a-b'`` and ``a/b``.
176
 
    "a-b" comes after "a" but would come before "a/b" lexically.
 
143
    differs from plain ``cmp(path1, path2)`` for paths like ``'a-b'`` and
 
144
    ``a/b``. "a-b" comes after "a" but would come before "a/b" lexically.
177
145
 
178
146
    :param path1: first path
179
147
    :param path2: second path
180
 
    :return: True if path1 comes first, otherwise False
 
148
    :return: negative number if ``path1`` comes first,
 
149
        0 if paths are equal,
 
150
        and positive number if ``path2`` sorts first
181
151
    """
182
 
    if not isinstance(path1, bytes):
183
 
        raise TypeError("'path1' must be a byte string, not %s: %r"
 
152
    if not isinstance(path1, str):
 
153
        raise TypeError("'path1' must be a plain string, not %s: %r"
184
154
                        % (type(path1), path1))
185
 
    if not isinstance(path2, bytes):
186
 
        raise TypeError("'path2' must be a byte string, not %s: %r"
 
155
    if not isinstance(path2, str):
 
156
        raise TypeError("'path2' must be a plain string, not %s: %r"
187
157
                        % (type(path2), path2))
188
 
    return path1.split(b'/') < path2.split(b'/')
189
 
 
190
 
 
191
 
def _lt_path_by_dirblock(path1, path2):
 
158
    return cmp(path1.split('/'), path2.split('/'))
 
159
 
 
160
 
 
161
def _cmp_path_by_dirblock(path1, path2):
192
162
    """Compare two paths based on what directory they are in.
193
163
 
194
164
    This generates a sort order, such that all children of a directory are
197
167
 
198
168
    :param path1: first path
199
169
    :param path2: the second path
200
 
    :return: True if path1 comes first, otherwise False
 
170
    :return: negative number if ``path1`` comes first,
 
171
        0 if paths are equal
 
172
        and a positive number if ``path2`` sorts first
201
173
    """
202
 
    if not isinstance(path1, bytes):
 
174
    if not isinstance(path1, str):
203
175
        raise TypeError("'path1' must be a plain string, not %s: %r"
204
176
                        % (type(path1), path1))
205
 
    if not isinstance(path2, bytes):
 
177
    if not isinstance(path2, str):
206
178
        raise TypeError("'path2' must be a plain string, not %s: %r"
207
179
                        % (type(path2), path2))
208
180
    dirname1, basename1 = os.path.split(path1)
209
 
    key1 = (dirname1.split(b'/'), basename1)
 
181
    key1 = (dirname1.split('/'), basename1)
210
182
    dirname2, basename2 = os.path.split(path2)
211
 
    key2 = (dirname2.split(b'/'), basename2)
212
 
    return key1 < key2
 
183
    key2 = (dirname2.split('/'), basename2)
 
184
    return cmp(key1, key2)
213
185
 
214
186
 
215
187
def _read_dirblocks(state):
226
198
    text = state._state_file.read()
227
199
    # TODO: check the crc checksums. crc_measured = zlib.crc32(text)
228
200
 
229
 
    fields = text.split(b'\0')
 
201
    fields = text.split('\0')
230
202
    # Remove the last blank entry
231
203
    trailing = fields.pop()
232
 
    if trailing != b'':
233
 
        raise DirstateCorrupt(state,
234
 
                              'trailing garbage: %r' % (trailing,))
 
204
    if trailing != '':
 
205
        raise errors.DirstateCorrupt(state,
 
206
            'trailing garbage: %r' % (trailing,))
235
207
    # consider turning fields into a tuple.
236
208
 
237
209
    # skip the first field which is the trailing null from the header.
249
221
    field_count = len(fields)
250
222
    # this checks our adjustment, and also catches file too short.
251
223
    if field_count - cur != expected_field_count:
252
 
        raise DirstateCorrupt(state,
253
 
                              'field count incorrect %s != %s, entry_size=%s, '
254
 
                              'num_entries=%s fields=%r' % (
255
 
                                  field_count - cur, expected_field_count, entry_size,
256
 
                                  state._num_entries, fields))
 
224
        raise errors.DirstateCorrupt(state,
 
225
            'field count incorrect %s != %s, entry_size=%s, '\
 
226
            'num_entries=%s fields=%r' % (
 
227
            field_count - cur, expected_field_count, entry_size,
 
228
            state._num_entries, fields))
257
229
 
258
230
    if num_present_parents == 1:
259
231
        # Bind external functions to local names
262
234
        # them. Grab an straight iterator over the fields. (We use an
263
235
        # iterator because we don't want to do a lot of additions, nor
264
236
        # do we want to do a lot of slicing)
265
 
        _iter = iter(fields)
266
 
        # Get a local reference to the compatible next method
267
 
        next = getattr(_iter, '__next__', None)
268
 
        if next is None:
269
 
            next = _iter.next
 
237
        next = iter(fields).next
270
238
        # Move the iterator to the current position
271
 
        for x in range(cur):
 
239
        for x in xrange(cur):
272
240
            next()
273
241
        # The two blocks here are deliberate: the root block and the
274
242
        # contents-of-root block.
275
 
        state._dirblocks = [(b'', []), (b'', [])]
 
243
        state._dirblocks = [('', []), ('', [])]
276
244
        current_block = state._dirblocks[0][1]
277
 
        current_dirname = b''
 
245
        current_dirname = ''
278
246
        append_entry = current_block.append
279
 
        for count in range(state._num_entries):
 
247
        for count in xrange(state._num_entries):
280
248
            dirname = next()
281
249
            name = next()
282
250
            file_id = next()
289
257
            # we know current_dirname == dirname, so re-use it to avoid
290
258
            # creating new strings
291
259
            entry = ((current_dirname, name, file_id),
292
 
                     [(  # Current Tree
293
 
                         next(),                # minikind
294
 
                         next(),                # fingerprint
295
 
                         _int(next()),          # size
296
 
                         next() == b'y',        # executable
297
 
                         next(),                # packed_stat or revision_id
298
 
                     ),
299
 
                (  # Parent 1
300
 
                         next(),                # minikind
301
 
                         next(),                # fingerprint
302
 
                         _int(next()),          # size
303
 
                         next() == b'y',        # executable
304
 
                         next(),                # packed_stat or revision_id
305
 
                     ),
306
 
                ])
 
260
                     [(# Current Tree
 
261
                         next(),                # minikind
 
262
                         next(),                # fingerprint
 
263
                         _int(next()),          # size
 
264
                         next() == 'y',         # executable
 
265
                         next(),                # packed_stat or revision_id
 
266
                     ),
 
267
                     ( # Parent 1
 
268
                         next(),                # minikind
 
269
                         next(),                # fingerprint
 
270
                         _int(next()),          # size
 
271
                         next() == 'y',         # executable
 
272
                         next(),                # packed_stat or revision_id
 
273
                     ),
 
274
                     ])
307
275
            trailing = next()
308
 
            if trailing != b'\n':
 
276
            if trailing != '\n':
309
277
                raise ValueError("trailing garbage in dirstate: %r" % trailing)
310
278
            # append the entry to the current block
311
279
            append_entry(entry)
312
280
        state._split_root_dirblock_into_contents()
313
281
    else:
314
282
        fields_to_entry = state._get_fields_to_entry()
315
 
        entries = [fields_to_entry(fields[pos:pos + entry_size])
316
 
                   for pos in range(cur, field_count, entry_size)]
 
283
        entries = [fields_to_entry(fields[pos:pos+entry_size])
 
284
                   for pos in xrange(cur, field_count, entry_size)]
317
285
        state._entries_to_current_state(entries)
318
286
    # To convert from format 2  => format 3
319
287
    # state._dirblocks = sorted(state._dirblocks,