~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: Daniel Watkins
  • Date: 2007-07-31 10:33:33 UTC
  • mto: (2687.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 2689.
  • Revision ID: d.m.watkins@warwick.ac.uk-20070731103333-sdelcaazn0fxgaf3
Added tests for ExtendedTestResult.wasStrictlySuccessful.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""DirState objects record the state of a directory and its bzr metadata.
18
18
 
29
29
 
30
30
dirstate format = header line, full checksum, row count, parent details,
31
31
 ghost_details, entries;
32
 
header line = "#bazaar dirstate flat format 3", NL;
 
32
header line = "#bazaar dirstate flat format 2", NL;
33
33
full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
34
 
row count = "num_entries: ", WHOLE_NUMBER, NL;
 
34
row count = "num_entries: ", digit, NL;
35
35
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
36
36
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
37
37
entries = {entry};
82
82
'a' is an absent entry: In that tree the id is not present at this path.
83
83
'd' is a directory entry: This path in this tree is a directory with the
84
84
    current file id. There is no fingerprint for directories.
85
 
'f' is a file entry: As for directory, but it's a file. The fingerprint is the
86
 
    sha1 value of the file's canonical form, i.e. after any read filters have
87
 
    been applied to the convenience form stored in the working tree.
 
85
'f' is a file entry: As for directory, but its a file. The fingerprint is a
 
86
    sha1 value.
88
87
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
89
88
    link target.
90
89
't' is a reference to a nested subtree; the fingerprint is the referenced
100
99
 
101
100
--- Format 1 had the following different definition: ---
102
101
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
103
 
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
102
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target, 
104
103
    {PARENT ROW}
105
104
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
106
105
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
119
118
where we need id->path mapping; we also usually read the whole file, so
120
119
I'm going to skip that for the moment, as we have the ability to locate
121
120
via bisect any path in any tree, and if we lookup things by path, we can
122
 
accumulate an id->path mapping as we go, which will tend to match what we
 
121
accumulate a id->path mapping as we go, which will tend to match what we
123
122
looked for.
124
123
 
125
124
I plan to implement this asap, so please speak up now to alter/tweak the
131
130
operations for the less common but still occurs a lot status/diff/commit
132
131
on specific files). Operations on specific files involve a scan for all
133
132
the children of a path, *in every involved tree*, which the current
134
 
format did not accommodate.
 
133
format did not accommodate. 
135
134
----
136
135
 
137
136
Design priorities:
144
143
Locking:
145
144
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
146
145
 been modified, but will require that we flush/ignore cached stat-hit data
147
 
 because we won't want to restat all files on disk just because a lock was
 
146
 because we wont want to restat all files on disk just because a lock was
148
147
 acquired, yet we cannot trust the data after the previous lock was released.
149
148
 
150
149
Memory representation:
151
150
 vector of all directories, and vector of the childen ?
152
 
   i.e.
153
 
     root_entrie = (direntry for root, [parent_direntries_for_root]),
 
151
   i.e. 
 
152
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
154
153
     dirblocks = [
155
154
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
156
155
     ('dir', ['achild', 'cchild', 'echild'])
159
158
    - in-order for serialisation - this is 'dirblock' grouping.
160
159
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
161
160
      insert 10K elements from scratch does not generates O(N^2) memoves of a
162
 
      single vector, rather each individual, which tends to be limited to a
163
 
      manageable number. Will scale badly on trees with 10K entries in a
 
161
      single vector, rather each individual, which tends to be limited to a 
 
162
      manageable number. Will scale badly on trees with 10K entries in a 
164
163
      single directory. compare with Inventory.InventoryDirectory which has
165
164
      a dictionary for the children. No bisect capability, can only probe for
166
 
      exact matches, or grab all elements and sort.
167
 
    - What's the risk of error here? Once we have the base format being processed
168
 
      we should have a net win regardless of optimality. So we are going to
169
 
      go with what seems reasonable.
 
165
      exact matches, or grab all elements and sorta.
 
166
    - Whats the risk of error here? Once we have the base format being processed
 
167
      we should have a net win regardless of optimality. So we are going to 
 
168
      go with what seems reasonably.
170
169
open questions:
171
170
 
172
 
Maybe we should do a test profile of the core structure - 10K simulated
173
 
searches/lookups/etc?
 
171
maybe we should do a test profile of these core structure - 10K simulated searches/lookups/etc?
174
172
 
175
173
Objects for each row?
176
174
The lifetime of Dirstate objects is current per lock, but see above for
187
185
the file on disk, and then immediately discard, the overhead of object creation
188
186
becomes a significant cost.
189
187
 
190
 
Figures: Creating a tuple from 3 elements was profiled at 0.0625
 
188
Figures: Creating a tuple from from 3 elements was profiled at 0.0625
191
189
microseconds, whereas creating a object which is subclassed from tuple was
192
190
0.500 microseconds, and creating an object with 3 elements and slots was 3
193
191
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
213
211
import zlib
214
212
 
215
213
from bzrlib import (
216
 
    cache_utf8,
217
 
    debug,
218
214
    errors,
219
215
    inventory,
220
216
    lock,
223
219
    )
224
220
 
225
221
 
226
 
# This is the Windows equivalent of ENOTDIR
227
 
# It is defined in pywin32.winerror, but we don't want a strong dependency for
228
 
# just an error code.
229
 
ERROR_PATH_NOT_FOUND = 3
230
 
ERROR_DIRECTORY = 267
231
 
 
232
 
 
233
 
if not getattr(struct, '_compile', None):
234
 
    # Cannot pre-compile the dirstate pack_stat
235
 
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
236
 
        """Convert stat values into a packed representation."""
237
 
        return _encode(_pack('>LLLLLL', st.st_size, int(st.st_mtime),
238
 
            int(st.st_ctime), st.st_dev, st.st_ino & 0xFFFFFFFF,
239
 
            st.st_mode))[:-1]
240
 
else:
241
 
    # compile the struct compiler we need, so as to only do it once
242
 
    from _struct import Struct
243
 
    _compiled_pack = Struct('>LLLLLL').pack
244
 
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=_compiled_pack):
245
 
        """Convert stat values into a packed representation."""
246
 
        # jam 20060614 it isn't really worth removing more entries if we
247
 
        # are going to leave it in packed form.
248
 
        # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
249
 
        # With all entries, filesize is 5.9M and read time is maybe 280ms
250
 
        # well within the noise margin
251
 
 
252
 
        # base64 encoding always adds a final newline, so strip it off
253
 
        # The current version
254
 
        return _encode(_pack(st.st_size, int(st.st_mtime), int(st.st_ctime),
255
 
            st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
256
 
        # This is 0.060s / 1.520s faster by not encoding as much information
257
 
        # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
258
 
        # This is not strictly faster than _encode(_pack())[:-1]
259
 
        # return '%X.%X.%X.%X.%X.%X' % (
260
 
        #      st.st_size, int(st.st_mtime), int(st.st_ctime),
261
 
        #      st.st_dev, st.st_ino, st.st_mode)
262
 
        # Similar to the _encode(_pack('>LL'))
263
 
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
264
 
 
265
 
 
266
 
class SHA1Provider(object):
267
 
    """An interface for getting sha1s of a file."""
268
 
 
269
 
    def sha1(self, abspath):
270
 
        """Return the sha1 of a file given its absolute path."""
271
 
        raise NotImplementedError(self.sha1)
272
 
 
273
 
    def stat_and_sha1(self, abspath):
274
 
        """Return the stat and sha1 of a file given its absolute path.
275
 
        
276
 
        Note: the stat should be the stat of the physical file
277
 
        while the sha may be the sha of its canonical content.
278
 
        """
279
 
        raise NotImplementedError(self.stat_and_sha1)
280
 
 
281
 
 
282
 
class DefaultSHA1Provider(SHA1Provider):
283
 
    """A SHA1Provider that reads directly from the filesystem."""
284
 
 
285
 
    def sha1(self, abspath):
286
 
        """Return the sha1 of a file given its absolute path."""
287
 
        return osutils.sha_file_by_name(abspath)
288
 
 
289
 
    def stat_and_sha1(self, abspath):
290
 
        """Return the stat and sha1 of a file given its absolute path."""
291
 
        file_obj = file(abspath, 'rb')
292
 
        try:
293
 
            statvalue = os.fstat(file_obj.fileno())
294
 
            sha1 = osutils.sha_file(file_obj)
295
 
        finally:
296
 
            file_obj.close()
297
 
        return statvalue, sha1
 
222
def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
 
223
    """Convert stat values into a packed representation."""
 
224
    # jam 20060614 it isn't really worth removing more entries if we
 
225
    # are going to leave it in packed form.
 
226
    # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
 
227
    # With all entries filesize is 5.9M and read time is mabye 280ms
 
228
    # well within the noise margin
 
229
 
 
230
    # base64 encoding always adds a final newline, so strip it off
 
231
    # The current version
 
232
    return _encode(_pack('>LLLLLL'
 
233
        , st.st_size, int(st.st_mtime), int(st.st_ctime)
 
234
        , st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
 
235
    # This is 0.060s / 1.520s faster by not encoding as much information
 
236
    # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
 
237
    # This is not strictly faster than _encode(_pack())[:-1]
 
238
    # return '%X.%X.%X.%X.%X.%X' % (
 
239
    #      st.st_size, int(st.st_mtime), int(st.st_ctime),
 
240
    #      st.st_dev, st.st_ino, st.st_mode)
 
241
    # Similar to the _encode(_pack('>LL'))
 
242
    # return '%X.%X' % (int(st.st_mtime), st.st_mode)
298
243
 
299
244
 
300
245
class DirState(object):
302
247
 
303
248
    A dirstate is a specialised data structure for managing local working
304
249
    tree state information. Its not yet well defined whether it is platform
305
 
    specific, and if it is how we detect/parameterize that.
 
250
    specific, and if it is how we detect/parameterise that.
306
251
 
307
252
    Dirstates use the usual lock_write, lock_read and unlock mechanisms.
308
253
    Unlike most bzr disk formats, DirStates must be locked for reading, using
355
300
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
356
301
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
357
302
 
358
 
    def __init__(self, path, sha1_provider):
 
303
    def __init__(self, path):
359
304
        """Create a  DirState object.
360
305
 
 
306
        Attributes of note:
 
307
 
 
308
        :attr _root_entrie: The root row of the directory/file information,
 
309
            - contains the path to / - '', ''
 
310
            - kind of 'directory',
 
311
            - the file id of the root in utf8
 
312
            - size of 0
 
313
            - a packed state
 
314
            - and no sha information.
361
315
        :param path: The path at which the dirstate file on disk should live.
362
 
        :param sha1_provider: an object meeting the SHA1Provider interface.
363
316
        """
364
317
        # _header_state and _dirblock_state represent the current state
365
318
        # of the dirstate metadata and the per-row data respectiely.
367
320
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
368
321
        #   is the same as is on disk
369
322
        # IN_MEMORY_MODIFIED indicates that we have a modified version
370
 
        #   of what is on disk.
 
323
        #   of what is on disk. 
371
324
        # In future we will add more granularity, for instance _dirblock_state
372
325
        # will probably support partially-in-memory as a separate variable,
373
326
        # allowing for partially-in-memory unmodified and partially-in-memory
374
327
        # modified states.
375
328
        self._header_state = DirState.NOT_IN_MEMORY
376
329
        self._dirblock_state = DirState.NOT_IN_MEMORY
377
 
        # If true, an error has been detected while updating the dirstate, and
378
 
        # for safety we're not going to commit to disk.
379
 
        self._changes_aborted = False
380
330
        self._dirblocks = []
381
331
        self._ghosts = []
382
332
        self._parents = []
385
335
        self._lock_token = None
386
336
        self._lock_state = None
387
337
        self._id_index = None
388
 
        # a map from packed_stat to sha's.
389
 
        self._packed_stat_index = None
390
338
        self._end_of_header = None
391
339
        self._cutoff_time = None
392
340
        self._split_path_cache = {}
393
341
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
394
 
        self._sha1_provider = sha1_provider
395
 
        if 'hashcache' in debug.debug_flags:
396
 
            self._sha1_file = self._sha1_file_and_mutter
397
 
        else:
398
 
            self._sha1_file = self._sha1_provider.sha1
399
 
        # These two attributes provide a simple cache for lookups into the
400
 
        # dirstate in-memory vectors. By probing respectively for the last
401
 
        # block, and for the next entry, we save nearly 2 bisections per path
402
 
        # during commit.
403
 
        self._last_block_index = None
404
 
        self._last_entry_index = None
405
342
 
406
343
    def __repr__(self):
407
344
        return "%s(%r)" % \
411
348
        """Add a path to be tracked.
412
349
 
413
350
        :param path: The path within the dirstate - '' is the root, 'foo' is the
414
 
            path foo within the root, 'foo/bar' is the path bar within foo
 
351
            path foo within the root, 'foo/bar' is the path bar within foo 
415
352
            within the root.
416
353
        :param file_id: The file id of the path being added.
417
 
        :param kind: The kind of the path, as a string like 'file',
 
354
        :param kind: The kind of the path, as a string like 'file', 
418
355
            'directory', etc.
419
356
        :param stat: The output of os.lstat for the path.
420
 
        :param fingerprint: The sha value of the file's canonical form (i.e.
421
 
            after any read filters have been applied),
 
357
        :param fingerprint: The sha value of the file,
422
358
            or the target of a symlink,
423
359
            or the referenced revision id for tree-references,
424
360
            or '' for directories.
425
361
        """
426
362
        # adding a file:
427
 
        # find the block its in.
 
363
        # find the block its in. 
428
364
        # find the location in the block.
429
365
        # check its not there
430
366
        # add it.
431
 
        #------- copied from inventory.ensure_normalized_name - keep synced.
 
367
        #------- copied from inventory.make_entry
432
368
        # --- normalized_filename wants a unicode basename only, so get one.
433
369
        dirname, basename = osutils.split(path)
434
370
        # we dont import normalized_filename directly because we want to be
443
379
        # in the parent, or according to the special treatment for the root
444
380
        if basename == '.' or basename == '..':
445
381
            raise errors.InvalidEntryName(path)
446
 
        # now that we've normalised, we need the correct utf8 path and
 
382
        # now that we've normalised, we need the correct utf8 path and 
447
383
        # dirname and basename elements. This single encode and split should be
448
384
        # faster than three separate encodes.
449
385
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
450
386
        dirname, basename = osutils.split(utf8path)
451
 
        # uses __class__ for speed; the check is needed for safety
452
 
        if file_id.__class__ is not str:
453
 
            raise AssertionError(
454
 
                "must be a utf8 file_id not %s" % (type(file_id), ))
 
387
        assert file_id.__class__ == str, \
 
388
            "must be a utf8 file_id not %s" % (type(file_id))
455
389
        # Make sure the file_id does not exist in this tree
456
 
        rename_from = None
457
 
        file_id_entry = self._get_entry(0, fileid_utf8=file_id, include_deleted=True)
 
390
        file_id_entry = self._get_entry(0, fileid_utf8=file_id)
458
391
        if file_id_entry != (None, None):
459
 
            if file_id_entry[1][0][0] == 'a':
460
 
                if file_id_entry[0] != (dirname, basename, file_id):
461
 
                    # set the old name's current operation to rename
462
 
                    self.update_minimal(file_id_entry[0],
463
 
                        'r',
464
 
                        path_utf8='',
465
 
                        packed_stat='',
466
 
                        fingerprint=utf8path
467
 
                    )
468
 
                    rename_from = file_id_entry[0][0:2]
469
 
            else:
470
 
                path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
471
 
                kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
472
 
                info = '%s:%s' % (kind, path)
473
 
                raise errors.DuplicateFileId(file_id, info)
 
392
            path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
 
393
            kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
 
394
            info = '%s:%s' % (kind, path)
 
395
            raise errors.DuplicateFileId(file_id, info)
474
396
        first_key = (dirname, basename, '')
475
397
        block_index, present = self._find_block_index_from_key(first_key)
476
398
        if present:
477
399
            # check the path is not in the tree
478
400
            block = self._dirblocks[block_index][1]
479
401
            entry_index, _ = self._find_entry_index(first_key, block)
480
 
            while (entry_index < len(block) and
 
402
            while (entry_index < len(block) and 
481
403
                block[entry_index][0][0:2] == first_key[0:2]):
482
404
                if block[entry_index][1][0][0] not in 'ar':
483
405
                    # this path is in the dirstate in the current tree.
503
425
            packed_stat = pack_stat(stat)
504
426
        parent_info = self._empty_parent_info()
505
427
        minikind = DirState._kind_to_minikind[kind]
506
 
        if rename_from is not None:
507
 
            if rename_from[0]:
508
 
                old_path_utf8 = '%s/%s' % rename_from
509
 
            else:
510
 
                old_path_utf8 = rename_from[1]
511
 
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
512
428
        if kind == 'file':
513
429
            entry_data = entry_key, [
514
430
                (minikind, fingerprint, size, False, packed_stat),
531
447
        if not present:
532
448
            block.insert(entry_index, entry_data)
533
449
        else:
534
 
            if block[entry_index][1][0][0] != 'a':
535
 
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
 
450
            assert block[entry_index][1][0][0] == 'a', " %r(%r) already added" % (basename, file_id)
536
451
            block[entry_index][1][0] = entry_data[1][0]
537
452
 
538
453
        if kind == 'directory':
557
472
        # If _dirblock_state was in memory, we should just return info from
558
473
        # there, this function is only meant to handle when we want to read
559
474
        # part of the disk.
560
 
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
561
 
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
 
475
        assert self._dirblock_state == DirState.NOT_IN_MEMORY
562
476
 
563
477
        # The disk representation is generally info + '\0\n\0' at the end. But
564
478
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
737
651
        _bisect_dirblocks is meant to find the contents of directories, which
738
652
        differs from _bisect, which only finds individual entries.
739
653
 
740
 
        :param dir_list: A sorted list of directory names ['', 'dir', 'foo'].
 
654
        :param dir_list: An sorted list of directory names ['', 'dir', 'foo'].
741
655
        :return: A map from dir => entries_for_dir
742
656
        """
743
657
        # TODO: jam 20070223 A lot of the bisecting logic could be shared
750
664
        # If _dirblock_state was in memory, we should just return info from
751
665
        # there, this function is only meant to handle when we want to read
752
666
        # part of the disk.
753
 
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
754
 
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
 
667
        assert self._dirblock_state == DirState.NOT_IN_MEMORY
 
668
 
755
669
        # The disk representation is generally info + '\0\n\0' at the end. But
756
670
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
757
671
        # Because it means we can sync on the '\n'
971
885
            processed_dirs.update(pending_dirs)
972
886
        return found
973
887
 
974
 
    def _discard_merge_parents(self):
975
 
        """Discard any parents trees beyond the first.
976
 
 
977
 
        Note that if this fails the dirstate is corrupted.
978
 
 
979
 
        After this function returns the dirstate contains 2 trees, neither of
980
 
        which are ghosted.
981
 
        """
982
 
        self._read_header_if_needed()
983
 
        parents = self.get_parent_ids()
984
 
        if len(parents) < 1:
985
 
            return
986
 
        # only require all dirblocks if we are doing a full-pass removal.
987
 
        self._read_dirblocks_if_needed()
988
 
        dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
989
 
        def iter_entries_removable():
990
 
            for block in self._dirblocks:
991
 
                deleted_positions = []
992
 
                for pos, entry in enumerate(block[1]):
993
 
                    yield entry
994
 
                    if (entry[1][0][0], entry[1][1][0]) in dead_patterns:
995
 
                        deleted_positions.append(pos)
996
 
                if deleted_positions:
997
 
                    if len(deleted_positions) == len(block[1]):
998
 
                        del block[1][:]
999
 
                    else:
1000
 
                        for pos in reversed(deleted_positions):
1001
 
                            del block[1][pos]
1002
 
        # if the first parent is a ghost:
1003
 
        if parents[0] in self.get_ghosts():
1004
 
            empty_parent = [DirState.NULL_PARENT_DETAILS]
1005
 
            for entry in iter_entries_removable():
1006
 
                entry[1][1:] = empty_parent
1007
 
        else:
1008
 
            for entry in iter_entries_removable():
1009
 
                del entry[1][2:]
1010
 
 
1011
 
        self._ghosts = []
1012
 
        self._parents = [parents[0]]
1013
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1014
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
1015
 
 
1016
888
    def _empty_parent_info(self):
1017
889
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1018
890
                                                    len(self._ghosts))
1044
916
        # the basename of the directory must be the end of its full name.
1045
917
        if not (parent_block_index == -1 and
1046
918
            parent_block_index == -1 and dirname == ''):
1047
 
            if not dirname.endswith(
1048
 
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
1049
 
                raise AssertionError("bad dirname %r" % dirname)
 
919
            assert dirname.endswith(
 
920
                self._dirblocks[parent_block_index][1][parent_row_index][0][1])
1050
921
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
1051
922
        if not present:
1052
 
            ## In future, when doing partial parsing, this should load and
 
923
            ## In future, when doing partial parsing, this should load and 
1053
924
            # populate the entire block.
1054
925
            self._dirblocks.insert(block_index, (dirname, []))
1055
926
        return block_index
1064
935
            to prevent unneeded overhead when callers have a sorted list already.
1065
936
        :return: Nothing.
1066
937
        """
1067
 
        if new_entries[0][0][0:2] != ('', ''):
1068
 
            raise AssertionError(
1069
 
                "Missing root row %r" % (new_entries[0][0],))
1070
 
        # The two blocks here are deliberate: the root block and the
 
938
        assert new_entries[0][0][0:2] == ('', ''), \
 
939
            "Missing root row %r" % (new_entries[0][0],)
 
940
        # The two blocks here are deliberate: the root block and the 
1071
941
        # contents-of-root block.
1072
942
        self._dirblocks = [('', []), ('', [])]
1073
943
        current_block = self._dirblocks[0][1]
1094
964
        # The above loop leaves the "root block" entries mixed with the
1095
965
        # "contents-of-root block". But we don't want an if check on
1096
966
        # all entries, so instead we just fix it up here.
1097
 
        if self._dirblocks[1] != ('', []):
1098
 
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
 
967
        assert self._dirblocks[1] == ('', [])
1099
968
        root_block = []
1100
969
        contents_of_root_block = []
1101
970
        for entry in self._dirblocks[0][1]:
1106
975
        self._dirblocks[0] = ('', root_block)
1107
976
        self._dirblocks[1] = ('', contents_of_root_block)
1108
977
 
1109
 
    def _entries_for_path(self, path):
1110
 
        """Return a list with all the entries that match path for all ids."""
1111
 
        dirname, basename = os.path.split(path)
1112
 
        key = (dirname, basename, '')
1113
 
        block_index, present = self._find_block_index_from_key(key)
1114
 
        if not present:
1115
 
            # the block which should contain path is absent.
1116
 
            return []
1117
 
        result = []
1118
 
        block = self._dirblocks[block_index][1]
1119
 
        entry_index, _ = self._find_entry_index(key, block)
1120
 
        # we may need to look at multiple entries at this path: walk while the specific_files match.
1121
 
        while (entry_index < len(block) and
1122
 
            block[entry_index][0][0:2] == key[0:2]):
1123
 
            result.append(block[entry_index])
1124
 
            entry_index += 1
1125
 
        return result
1126
 
 
1127
978
    def _entry_to_line(self, entry):
1128
979
        """Serialize entry to a NULL delimited line ready for _get_output_lines.
1129
980
 
1185
1036
        """
1186
1037
        if key[0:2] == ('', ''):
1187
1038
            return 0, True
1188
 
        try:
1189
 
            if (self._last_block_index is not None and
1190
 
                self._dirblocks[self._last_block_index][0] == key[0]):
1191
 
                return self._last_block_index, True
1192
 
        except IndexError:
1193
 
            pass
1194
1039
        block_index = bisect_dirblock(self._dirblocks, key[0], 1,
1195
1040
                                      cache=self._split_path_cache)
1196
1041
        # _right returns one-past-where-key is so we have to subtract
1197
1042
        # one to use it. we use _right here because there are two
1198
1043
        # '' blocks - the root, and the contents of root
1199
1044
        # we always have a minimum of 2 in self._dirblocks: root and
1200
 
        # root-contents, and for '', we get 2 back, so this is
 
1045
        # root-contents, and for '', we get 2 back, so this is 
1201
1046
        # simple and correct:
1202
1047
        present = (block_index < len(self._dirblocks) and
1203
1048
            self._dirblocks[block_index][0] == key[0])
1204
 
        self._last_block_index = block_index
1205
 
        # Reset the entry index cache to the beginning of the block.
1206
 
        self._last_entry_index = -1
1207
1049
        return block_index, present
1208
1050
 
1209
1051
    def _find_entry_index(self, key, block):
1211
1053
 
1212
1054
        :return: The entry index, True if the entry for the key is present.
1213
1055
        """
1214
 
        len_block = len(block)
1215
 
        try:
1216
 
            if self._last_entry_index is not None:
1217
 
                # mini-bisect here.
1218
 
                entry_index = self._last_entry_index + 1
1219
 
                # A hit is when the key is after the last slot, and before or
1220
 
                # equal to the next slot.
1221
 
                if ((entry_index > 0 and block[entry_index - 1][0] < key) and
1222
 
                    key <= block[entry_index][0]):
1223
 
                    self._last_entry_index = entry_index
1224
 
                    present = (block[entry_index][0] == key)
1225
 
                    return entry_index, present
1226
 
        except IndexError:
1227
 
            pass
1228
1056
        entry_index = bisect.bisect_left(block, (key, []))
1229
 
        present = (entry_index < len_block and
 
1057
        present = (entry_index < len(block) and
1230
1058
            block[entry_index][0] == key)
1231
 
        self._last_entry_index = entry_index
1232
1059
        return entry_index, present
1233
1060
 
1234
1061
    @staticmethod
1235
 
    def from_tree(tree, dir_state_filename, sha1_provider=None):
 
1062
    def from_tree(tree, dir_state_filename):
1236
1063
        """Create a dirstate from a bzr Tree.
1237
1064
 
1238
1065
        :param tree: The tree which should provide parent information and
1239
1066
            inventory ids.
1240
 
        :param sha1_provider: an object meeting the SHA1Provider interface.
1241
 
            If None, a DefaultSHA1Provider is used.
1242
1067
        :return: a DirState object which is currently locked for writing.
1243
1068
            (it was locked by DirState.initialize)
1244
1069
        """
1245
 
        result = DirState.initialize(dir_state_filename,
1246
 
            sha1_provider=sha1_provider)
 
1070
        result = DirState.initialize(dir_state_filename)
1247
1071
        try:
1248
1072
            tree.lock_read()
1249
1073
            try:
1267
1091
            raise
1268
1092
        return result
1269
1093
 
1270
 
    def update_by_delta(self, delta):
1271
 
        """Apply an inventory delta to the dirstate for tree 0
1272
 
 
1273
 
        :param delta: An inventory delta.  See Inventory.apply_delta for
1274
 
            details.
1275
 
        """
1276
 
        self._read_dirblocks_if_needed()
1277
 
        insertions = {}
1278
 
        removals = {}
1279
 
        for old_path, new_path, file_id, inv_entry in sorted(delta, reverse=True):
1280
 
            if (file_id in insertions) or (file_id in removals):
1281
 
                raise AssertionError("repeated file id in delta %r" % (file_id,))
1282
 
            if old_path is not None:
1283
 
                old_path = old_path.encode('utf-8')
1284
 
                removals[file_id] = old_path
1285
 
            if new_path is not None:
1286
 
                new_path = new_path.encode('utf-8')
1287
 
                dirname, basename = osutils.split(new_path)
1288
 
                key = (dirname, basename, file_id)
1289
 
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1290
 
                if minikind == 't':
1291
 
                    fingerprint = inv_entry.reference_revision
1292
 
                else:
1293
 
                    fingerprint = ''
1294
 
                insertions[file_id] = (key, minikind, inv_entry.executable,
1295
 
                                       fingerprint, new_path)
1296
 
            # Transform moves into delete+add pairs
1297
 
            if None not in (old_path, new_path):
1298
 
                for child in self._iter_child_entries(0, old_path):
1299
 
                    if child[0][2] in insertions or child[0][2] in removals:
1300
 
                        continue
1301
 
                    child_dirname = child[0][0]
1302
 
                    child_basename = child[0][1]
1303
 
                    minikind = child[1][0][0]
1304
 
                    fingerprint = child[1][0][4]
1305
 
                    executable = child[1][0][3]
1306
 
                    old_child_path = osutils.pathjoin(child[0][0],
1307
 
                                                      child[0][1])
1308
 
                    removals[child[0][2]] = old_child_path
1309
 
                    child_suffix = child_dirname[len(old_path):]
1310
 
                    new_child_dirname = (new_path + child_suffix)
1311
 
                    key = (new_child_dirname, child_basename, child[0][2])
1312
 
                    new_child_path = os.path.join(new_child_dirname,
1313
 
                                                  child_basename)
1314
 
                    insertions[child[0][2]] = (key, minikind, executable,
1315
 
                                               fingerprint, new_child_path)
1316
 
        self._apply_removals(removals.values())
1317
 
        self._apply_insertions(insertions.values())
1318
 
 
1319
 
    def _apply_removals(self, removals):
1320
 
        for path in sorted(removals, reverse=True):
1321
 
            dirname, basename = osutils.split(path)
1322
 
            block_i, entry_i, d_present, f_present = \
1323
 
                self._get_block_entry_index(dirname, basename, 0)
1324
 
            entry = self._dirblocks[block_i][1][entry_i]
1325
 
            self._make_absent(entry)
1326
 
            # See if we have a malformed delta: deleting a directory must not
1327
 
            # leave crud behind. This increases the number of bisects needed
1328
 
            # substantially, but deletion or renames of large numbers of paths
1329
 
            # is rare enough it shouldn't be an issue (famous last words?) RBC
1330
 
            # 20080730.
1331
 
            block_i, entry_i, d_present, f_present = \
1332
 
                self._get_block_entry_index(path, '', 0)
1333
 
            if d_present:
1334
 
                # The dir block is still present in the dirstate; this could
1335
 
                # be due to it being in a parent tree, or a corrupt delta.
1336
 
                for child_entry in self._dirblocks[block_i][1]:
1337
 
                    if child_entry[1][0][0] not in ('r', 'a'):
1338
 
                        raise errors.InconsistentDelta(path, entry[0][2],
1339
 
                            "The file id was deleted but its children were "
1340
 
                            "not deleted.")
1341
 
 
1342
 
    def _apply_insertions(self, adds):
1343
 
        for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
1344
 
            self.update_minimal(key, minikind, executable, fingerprint,
1345
 
                                path_utf8=path_utf8)
1346
 
 
1347
 
    def update_basis_by_delta(self, delta, new_revid):
1348
 
        """Update the parents of this tree after a commit.
1349
 
 
1350
 
        This gives the tree one parent, with revision id new_revid. The
1351
 
        inventory delta is applied to the current basis tree to generate the
1352
 
        inventory for the parent new_revid, and all other parent trees are
1353
 
        discarded.
1354
 
 
1355
 
        Note that an exception during the operation of this method will leave
1356
 
        the dirstate in a corrupt state where it should not be saved.
1357
 
 
1358
 
        Finally, we expect all changes to be synchronising the basis tree with
1359
 
        the working tree.
1360
 
 
1361
 
        :param new_revid: The new revision id for the trees parent.
1362
 
        :param delta: An inventory delta (see apply_inventory_delta) describing
1363
 
            the changes from the current left most parent revision to new_revid.
1364
 
        """
1365
 
        self._read_dirblocks_if_needed()
1366
 
        self._discard_merge_parents()
1367
 
        if self._ghosts != []:
1368
 
            raise NotImplementedError(self.update_basis_by_delta)
1369
 
        if len(self._parents) == 0:
1370
 
            # setup a blank tree, the most simple way.
1371
 
            empty_parent = DirState.NULL_PARENT_DETAILS
1372
 
            for entry in self._iter_entries():
1373
 
                entry[1].append(empty_parent)
1374
 
            self._parents.append(new_revid)
1375
 
 
1376
 
        self._parents[0] = new_revid
1377
 
 
1378
 
        delta = sorted(delta, reverse=True)
1379
 
        adds = []
1380
 
        changes = []
1381
 
        deletes = []
1382
 
        # The paths this function accepts are unicode and must be encoded as we
1383
 
        # go.
1384
 
        encode = cache_utf8.encode
1385
 
        inv_to_entry = self._inv_entry_to_details
1386
 
        # delta is now (deletes, changes), (adds) in reverse lexographical
1387
 
        # order.
1388
 
        # deletes in reverse lexographic order are safe to process in situ.
1389
 
        # renames are not, as a rename from any path could go to a path
1390
 
        # lexographically lower, so we transform renames into delete, add pairs,
1391
 
        # expanding them recursively as needed.
1392
 
        # At the same time, to reduce interface friction we convert the input
1393
 
        # inventory entries to dirstate.
1394
 
        root_only = ('', '')
1395
 
        for old_path, new_path, file_id, inv_entry in delta:
1396
 
            if old_path is None:
1397
 
                adds.append((None, encode(new_path), file_id,
1398
 
                    inv_to_entry(inv_entry), True))
1399
 
            elif new_path is None:
1400
 
                deletes.append((encode(old_path), None, file_id, None, True))
1401
 
            elif (old_path, new_path) != root_only:
1402
 
                # Renames:
1403
 
                # Because renames must preserve their children we must have
1404
 
                # processed all relocations and removes before hand. The sort
1405
 
                # order ensures we've examined the child paths, but we also
1406
 
                # have to execute the removals, or the split to an add/delete
1407
 
                # pair will result in the deleted item being reinserted, or
1408
 
                # renamed items being reinserted twice - and possibly at the
1409
 
                # wrong place. Splitting into a delete/add pair also simplifies
1410
 
                # the handling of entries with ('f', ...), ('r' ...) because
1411
 
                # the target of the 'r' is old_path here, and we add that to
1412
 
                # deletes, meaning that the add handler does not need to check
1413
 
                # for 'r' items on every pass.
1414
 
                self._update_basis_apply_deletes(deletes)
1415
 
                deletes = []
1416
 
                new_path_utf8 = encode(new_path)
1417
 
                # Split into an add/delete pair recursively.
1418
 
                adds.append((None, new_path_utf8, file_id,
1419
 
                    inv_to_entry(inv_entry), False))
1420
 
                # Expunge deletes that we've seen so that deleted/renamed
1421
 
                # children of a rename directory are handled correctly.
1422
 
                new_deletes = reversed(list(self._iter_child_entries(1,
1423
 
                    encode(old_path))))
1424
 
                # Remove the current contents of the tree at orig_path, and
1425
 
                # reinsert at the correct new path.
1426
 
                for entry in new_deletes:
1427
 
                    if entry[0][0]:
1428
 
                        source_path = entry[0][0] + '/' + entry[0][1]
1429
 
                    else:
1430
 
                        source_path = entry[0][1]
1431
 
                    if new_path_utf8:
1432
 
                        target_path = new_path_utf8 + source_path[len(old_path):]
1433
 
                    else:
1434
 
                        if old_path == '':
1435
 
                            raise AssertionError("cannot rename directory to"
1436
 
                                " itself")
1437
 
                        target_path = source_path[len(old_path) + 1:]
1438
 
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1439
 
                    deletes.append(
1440
 
                        (source_path, target_path, entry[0][2], None, False))
1441
 
                deletes.append(
1442
 
                    (encode(old_path), new_path, file_id, None, False))
1443
 
            else:
1444
 
                # changes to just the root should not require remove/insertion
1445
 
                # of everything.
1446
 
                changes.append((encode(old_path), encode(new_path), file_id,
1447
 
                    inv_to_entry(inv_entry)))
1448
 
 
1449
 
        # Finish expunging deletes/first half of renames.
1450
 
        self._update_basis_apply_deletes(deletes)
1451
 
        # Reinstate second half of renames and new paths.
1452
 
        self._update_basis_apply_adds(adds)
1453
 
        # Apply in-situ changes.
1454
 
        self._update_basis_apply_changes(changes)
1455
 
 
1456
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1457
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
1458
 
        self._id_index = None
1459
 
        return
1460
 
 
1461
 
    def _update_basis_apply_adds(self, adds):
1462
 
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1463
 
 
1464
 
        They may be adds, or renames that have been split into add/delete
1465
 
        pairs.
1466
 
 
1467
 
        :param adds: A sequence of adds. Each add is a tuple:
1468
 
            (None, new_path_utf8, file_id, (entry_details), real_add). real_add
1469
 
            is False when the add is the second half of a remove-and-reinsert
1470
 
            pair created to handle renames and deletes.
1471
 
        """
1472
 
        # Adds are accumulated partly from renames, so can be in any input
1473
 
        # order - sort it.
1474
 
        adds.sort()
1475
 
        # adds is now in lexographic order, which places all parents before
1476
 
        # their children, so we can process it linearly.
1477
 
        absent = 'ar'
1478
 
        for old_path, new_path, file_id, new_details, real_add in adds:
1479
 
            # the entry for this file_id must be in tree 0.
1480
 
            entry = self._get_entry(0, file_id, new_path)
1481
 
            if entry[0] is None or entry[0][2] != file_id:
1482
 
                self._changes_aborted = True
1483
 
                raise errors.InconsistentDelta(new_path, file_id,
1484
 
                    'working tree does not contain new entry')
1485
 
            if real_add and entry[1][1][0] not in absent:
1486
 
                self._changes_aborted = True
1487
 
                raise errors.InconsistentDelta(new_path, file_id,
1488
 
                    'The entry was considered to be a genuinely new record,'
1489
 
                    ' but there was already an old record for it.')
1490
 
            # We don't need to update the target of an 'r' because the handling
1491
 
            # of renames turns all 'r' situations into a delete at the original
1492
 
            # location.
1493
 
            entry[1][1] = new_details
1494
 
 
1495
 
    def _update_basis_apply_changes(self, changes):
1496
 
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1497
 
 
1498
 
        :param adds: A sequence of changes. Each change is a tuple:
1499
 
            (path_utf8, path_utf8, file_id, (entry_details))
1500
 
        """
1501
 
        absent = 'ar'
1502
 
        for old_path, new_path, file_id, new_details in changes:
1503
 
            # the entry for this file_id must be in tree 0.
1504
 
            entry = self._get_entry(0, file_id, new_path)
1505
 
            if entry[0] is None or entry[0][2] != file_id:
1506
 
                self._changes_aborted = True
1507
 
                raise errors.InconsistentDelta(new_path, file_id,
1508
 
                    'working tree does not contain new entry')
1509
 
            if (entry[1][0][0] in absent or
1510
 
                entry[1][1][0] in absent):
1511
 
                self._changes_aborted = True
1512
 
                raise errors.InconsistentDelta(new_path, file_id,
1513
 
                    'changed considered absent')
1514
 
            entry[1][1] = new_details
1515
 
 
1516
 
    def _update_basis_apply_deletes(self, deletes):
1517
 
        """Apply a sequence of deletes to tree 1 during update_basis_by_delta.
1518
 
 
1519
 
        They may be deletes, or renames that have been split into add/delete
1520
 
        pairs.
1521
 
 
1522
 
        :param deletes: A sequence of deletes. Each delete is a tuple:
1523
 
            (old_path_utf8, new_path_utf8, file_id, None, real_delete).
1524
 
            real_delete is True when the desired outcome is an actual deletion
1525
 
            rather than the rename handling logic temporarily deleting a path
1526
 
            during the replacement of a parent.
1527
 
        """
1528
 
        null = DirState.NULL_PARENT_DETAILS
1529
 
        for old_path, new_path, file_id, _, real_delete in deletes:
1530
 
            if real_delete != (new_path is None):
1531
 
                raise AssertionError("bad delete delta")
1532
 
            # the entry for this file_id must be in tree 1.
1533
 
            dirname, basename = osutils.split(old_path)
1534
 
            block_index, entry_index, dir_present, file_present = \
1535
 
                self._get_block_entry_index(dirname, basename, 1)
1536
 
            if not file_present:
1537
 
                self._changes_aborted = True
1538
 
                raise errors.InconsistentDelta(old_path, file_id,
1539
 
                    'basis tree does not contain removed entry')
1540
 
            entry = self._dirblocks[block_index][1][entry_index]
1541
 
            if entry[0][2] != file_id:
1542
 
                self._changes_aborted = True
1543
 
                raise errors.InconsistentDelta(old_path, file_id,
1544
 
                    'mismatched file_id in tree 1')
1545
 
            if real_delete:
1546
 
                if entry[1][0][0] != 'a':
1547
 
                    self._changes_aborted = True
1548
 
                    raise errors.InconsistentDelta(old_path, file_id,
1549
 
                            'This was marked as a real delete, but the WT state'
1550
 
                            ' claims that it still exists and is versioned.')
1551
 
                del self._dirblocks[block_index][1][entry_index]
1552
 
            else:
1553
 
                if entry[1][0][0] == 'a':
1554
 
                    self._changes_aborted = True
1555
 
                    raise errors.InconsistentDelta(old_path, file_id,
1556
 
                        'The entry was considered a rename, but the source path'
1557
 
                        ' is marked as absent.')
1558
 
                    # For whatever reason, we were asked to rename an entry
1559
 
                    # that was originally marked as deleted. This could be
1560
 
                    # because we are renaming the parent directory, and the WT
1561
 
                    # current state has the file marked as deleted.
1562
 
                elif entry[1][0][0] == 'r':
1563
 
                    # implement the rename
1564
 
                    del self._dirblocks[block_index][1][entry_index]
1565
 
                else:
1566
 
                    # it is being resurrected here, so blank it out temporarily.
1567
 
                    self._dirblocks[block_index][1][entry_index][1][1] = null
1568
 
 
1569
 
    def _observed_sha1(self, entry, sha1, stat_value,
1570
 
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1571
 
        """Note the sha1 of a file.
1572
 
 
1573
 
        :param entry: The entry the sha1 is for.
1574
 
        :param sha1: The observed sha1.
1575
 
        :param stat_value: The os.lstat for the file.
 
1094
    def update_entry(self, entry, abspath, stat_value,
 
1095
                     _stat_to_minikind=_stat_to_minikind,
 
1096
                     _pack_stat=pack_stat):
 
1097
        """Update the entry based on what is actually on disk.
 
1098
 
 
1099
        :param entry: This is the dirblock entry for the file in question.
 
1100
        :param abspath: The path on disk for this file.
 
1101
        :param stat_value: (optional) if we already have done a stat on the
 
1102
            file, re-use it.
 
1103
        :return: The sha1 hexdigest of the file (40 bytes) or link target of a
 
1104
                symlink.
1576
1105
        """
1577
1106
        try:
1578
1107
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
1580
1109
            # Unhandled kind
1581
1110
            return None
1582
1111
        packed_stat = _pack_stat(stat_value)
 
1112
        (saved_minikind, saved_link_or_sha1, saved_file_size,
 
1113
         saved_executable, saved_packed_stat) = entry[1][0]
 
1114
 
 
1115
        if (minikind == saved_minikind
 
1116
            and packed_stat == saved_packed_stat):
 
1117
            # The stat hasn't changed since we saved, so we can re-use the
 
1118
            # saved sha hash.
 
1119
            if minikind == 'd':
 
1120
                return None
 
1121
 
 
1122
            # size should also be in packed_stat
 
1123
            if saved_file_size == stat_value.st_size:
 
1124
                return saved_link_or_sha1
 
1125
 
 
1126
        # If we have gotten this far, that means that we need to actually
 
1127
        # process this entry.
 
1128
        link_or_sha1 = None
1583
1129
        if minikind == 'f':
1584
 
            if self._cutoff_time is None:
1585
 
                self._sha_cutoff_time()
1586
 
            if (stat_value.st_mtime < self._cutoff_time
1587
 
                and stat_value.st_ctime < self._cutoff_time):
1588
 
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
1589
 
                    packed_stat)
1590
 
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1130
            link_or_sha1 = self._sha1_file(abspath, entry)
 
1131
            executable = self._is_executable(stat_value.st_mode,
 
1132
                                             saved_executable)
 
1133
            if self._cutoff_time is None:
 
1134
                self._sha_cutoff_time()
 
1135
            if (stat_value.st_mtime < self._cutoff_time
 
1136
                and stat_value.st_ctime < self._cutoff_time):
 
1137
                entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
1138
                               executable, packed_stat)
 
1139
            else:
 
1140
                entry[1][0] = ('f', '', stat_value.st_size,
 
1141
                               executable, DirState.NULLSTAT)
 
1142
        elif minikind == 'd':
 
1143
            link_or_sha1 = None
 
1144
            entry[1][0] = ('d', '', 0, False, packed_stat)
 
1145
            if saved_minikind != 'd':
 
1146
                # This changed from something into a directory. Make sure we
 
1147
                # have a directory block for it. This doesn't happen very
 
1148
                # often, so this doesn't have to be super fast.
 
1149
                block_index, entry_index, dir_present, file_present = \
 
1150
                    self._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
1151
                self._ensure_block(block_index, entry_index,
 
1152
                                   osutils.pathjoin(entry[0][0], entry[0][1]))
 
1153
        elif minikind == 'l':
 
1154
            link_or_sha1 = self._read_link(abspath, saved_link_or_sha1)
 
1155
            if self._cutoff_time is None:
 
1156
                self._sha_cutoff_time()
 
1157
            if (stat_value.st_mtime < self._cutoff_time
 
1158
                and stat_value.st_ctime < self._cutoff_time):
 
1159
                entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
1160
                               False, packed_stat)
 
1161
            else:
 
1162
                entry[1][0] = ('l', '', stat_value.st_size,
 
1163
                               False, DirState.NULLSTAT)
 
1164
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1165
        return link_or_sha1
1591
1166
 
1592
1167
    def _sha_cutoff_time(self):
1593
1168
        """Return cutoff time.
1606
1181
        """Return the os.lstat value for this path."""
1607
1182
        return os.lstat(abspath)
1608
1183
 
1609
 
    def _sha1_file_and_mutter(self, abspath):
1610
 
        # when -Dhashcache is turned on, this is monkey-patched in to log
1611
 
        # file reads
1612
 
        trace.mutter("dirstate sha1 " + abspath)
1613
 
        return self._sha1_provider.sha1(abspath)
 
1184
    def _sha1_file(self, abspath, entry):
 
1185
        """Calculate the SHA1 of a file by reading the full text"""
 
1186
        f = file(abspath, 'rb', buffering=65000)
 
1187
        try:
 
1188
            return osutils.sha_file(f)
 
1189
        finally:
 
1190
            f.close()
1614
1191
 
1615
1192
    def _is_executable(self, mode, old_executable):
1616
1193
        """Is this file executable?"""
1629
1206
        #       already in memory. However, this really needs to be done at a
1630
1207
        #       higher level, because there either won't be anything on disk,
1631
1208
        #       or the thing on disk will be a file.
1632
 
        fs_encoding = osutils._fs_enc
1633
 
        if isinstance(abspath, unicode):
1634
 
            # abspath is defined as the path to pass to lstat. readlink is
1635
 
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
1636
 
            # encoding), so we need to encode ourselves knowing that unicode
1637
 
            # paths are produced by UnicodeDirReader on purpose.
1638
 
            abspath = abspath.encode(fs_encoding)
1639
 
        target = os.readlink(abspath)
1640
 
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
1641
 
            # Change encoding if needed
1642
 
            target = target.decode(fs_encoding).encode('UTF-8')
1643
 
        return target
 
1209
        return os.readlink(abspath)
1644
1210
 
1645
1211
    def get_ghosts(self):
1646
1212
        """Return a list of the parent tree revision ids that are ghosts."""
1764
1330
            be attempted.
1765
1331
        :return: A tuple describing where the path is located, or should be
1766
1332
            inserted. The tuple contains four fields: the block index, the row
1767
 
            index, the directory is present (boolean), the entire path is
1768
 
            present (boolean).  There is no guarantee that either
 
1333
            index, anda two booleans are True when the directory is present, and
 
1334
            when the entire path is present.  There is no guarantee that either
1769
1335
            coordinate is currently reachable unless the found field for it is
1770
1336
            True. For instance, a directory not present in the searched tree
1771
1337
            may be returned with a value one greater than the current highest
1783
1349
            return block_index, 0, False, False
1784
1350
        block = self._dirblocks[block_index][1] # access the entries only
1785
1351
        entry_index, present = self._find_entry_index(key, block)
1786
 
        # linear search through entries at this path to find the one
 
1352
        # linear search through present entries at this path to find the one
1787
1353
        # requested.
1788
1354
        while entry_index < len(block) and block[entry_index][0][1] == basename:
1789
 
            if block[entry_index][1][tree_index][0] not in 'ar':
1790
 
                # neither absent or relocated
 
1355
            if block[entry_index][1][tree_index][0] not in \
 
1356
                       ('a', 'r'): # absent, relocated
1791
1357
                return block_index, entry_index, True, True
1792
1358
            entry_index += 1
1793
1359
        return block_index, entry_index, True, False
1794
1360
 
1795
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
1796
 
        """Get the dirstate entry for path in tree tree_index.
 
1361
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
 
1362
        """Get the dirstate entry for path in tree tree_index
1797
1363
 
1798
1364
        If either file_id or path is supplied, it is used as the key to lookup.
1799
1365
        If both are supplied, the fastest lookup is used, and an error is
1806
1372
            trees.
1807
1373
        :param fileid_utf8: A utf8 file_id to look up.
1808
1374
        :param path_utf8: An utf8 path to be looked up.
1809
 
        :param include_deleted: If True, and performing a lookup via
1810
 
            fileid_utf8 rather than path_utf8, return an entry for deleted
1811
 
            (absent) paths.
1812
1375
        :return: The dirstate entry tuple for path, or (None, None)
1813
1376
        """
1814
1377
        self._read_dirblocks_if_needed()
1815
1378
        if path_utf8 is not None:
1816
 
            if type(path_utf8) is not str:
1817
 
                raise AssertionError('path_utf8 is not a str: %s %s'
1818
 
                    % (type(path_utf8), path_utf8))
 
1379
            assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
1819
1380
            # path lookups are faster
1820
1381
            dirname, basename = osutils.split(path_utf8)
1821
1382
            block_index, entry_index, dir_present, file_present = \
1823
1384
            if not file_present:
1824
1385
                return None, None
1825
1386
            entry = self._dirblocks[block_index][1][entry_index]
1826
 
            if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
1827
 
                raise AssertionError('unversioned entry?')
 
1387
            assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
1828
1388
            if fileid_utf8:
1829
1389
                if entry[0][2] != fileid_utf8:
1830
 
                    self._changes_aborted = True
1831
1390
                    raise errors.BzrError('integrity error ? : mismatching'
1832
1391
                                          ' tree_index, file_id and path')
1833
1392
            return entry
1834
1393
        else:
 
1394
            assert fileid_utf8 is not None
1835
1395
            possible_keys = self._get_id_index().get(fileid_utf8, None)
1836
1396
            if not possible_keys:
1837
1397
                return None, None
1844
1404
                    continue
1845
1405
                # WARNING: DO not change this code to use _get_block_entry_index
1846
1406
                # as that function is not suitable: it does not use the key
1847
 
                # to lookup, and thus the wrong coordinates are returned.
 
1407
                # to lookup, and thus the wront coordinates are returned.
1848
1408
                block = self._dirblocks[block_index][1]
1849
1409
                entry_index, present = self._find_entry_index(key, block)
1850
1410
                if present:
1851
1411
                    entry = self._dirblocks[block_index][1][entry_index]
1852
1412
                    if entry[1][tree_index][0] in 'fdlt':
1853
 
                        # this is the result we are looking for: the
 
1413
                        # this is the result we are looking for: the  
1854
1414
                        # real home of this file_id in this tree.
1855
1415
                        return entry
1856
1416
                    if entry[1][tree_index][0] == 'a':
1857
1417
                        # there is no home for this entry in this tree
1858
 
                        if include_deleted:
1859
 
                            return entry
1860
1418
                        return None, None
1861
 
                    if entry[1][tree_index][0] != 'r':
1862
 
                        raise AssertionError(
1863
 
                            "entry %r has invalid minikind %r for tree %r" \
1864
 
                            % (entry,
1865
 
                               entry[1][tree_index][0],
1866
 
                               tree_index))
 
1419
                    assert entry[1][tree_index][0] == 'r', \
 
1420
                        "entry %r has invalid minikind %r for tree %r" \
 
1421
                        % (entry,
 
1422
                           entry[1][tree_index][0],
 
1423
                           tree_index)
1867
1424
                    real_path = entry[1][tree_index][1]
1868
1425
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
1869
1426
                        path_utf8=real_path)
1870
1427
            return None, None
1871
1428
 
1872
1429
    @classmethod
1873
 
    def initialize(cls, path, sha1_provider=None):
 
1430
    def initialize(cls, path):
1874
1431
        """Create a new dirstate on path.
1875
1432
 
1876
1433
        The new dirstate will be an empty tree - that is it has no parents,
1877
1434
        and only a root node - which has id ROOT_ID.
1878
1435
 
1879
1436
        :param path: The name of the file for the dirstate.
1880
 
        :param sha1_provider: an object meeting the SHA1Provider interface.
1881
 
            If None, a DefaultSHA1Provider is used.
1882
1437
        :return: A write-locked DirState object.
1883
1438
        """
1884
1439
        # This constructs a new DirState object on a path, sets the _state_file
1886
1441
        # stock empty dirstate information - a root with ROOT_ID, no children,
1887
1442
        # and no parents. Finally it calls save() to ensure that this data will
1888
1443
        # persist.
1889
 
        if sha1_provider is None:
1890
 
            sha1_provider = DefaultSHA1Provider()
1891
 
        result = cls(path, sha1_provider)
 
1444
        result = cls(path)
1892
1445
        # root dir and root dir contents with no children.
1893
1446
        empty_tree_dirblocks = [('', []), ('', [])]
1894
1447
        # a new root directory, with a NULLSTAT.
1905
1458
            raise
1906
1459
        return result
1907
1460
 
1908
 
    @staticmethod
1909
 
    def _inv_entry_to_details(inv_entry):
 
1461
    def _inv_entry_to_details(self, inv_entry):
1910
1462
        """Convert an inventory entry (from a revision tree) to state details.
1911
1463
 
1912
1464
        :param inv_entry: An inventory entry whose sha1 and link targets can be
1917
1469
        kind = inv_entry.kind
1918
1470
        minikind = DirState._kind_to_minikind[kind]
1919
1471
        tree_data = inv_entry.revision
 
1472
        assert len(tree_data) > 0, 'empty revision for the inv_entry.'
1920
1473
        if kind == 'directory':
1921
1474
            fingerprint = ''
1922
1475
            size = 0
1923
1476
            executable = False
1924
1477
        elif kind == 'symlink':
1925
 
            if inv_entry.symlink_target is None:
1926
 
                fingerprint = ''
1927
 
            else:
1928
 
                fingerprint = inv_entry.symlink_target.encode('utf8')
 
1478
            fingerprint = inv_entry.symlink_target or ''
1929
1479
            size = 0
1930
1480
            executable = False
1931
1481
        elif kind == 'file':
1940
1490
            raise Exception("can't pack %s" % inv_entry)
1941
1491
        return (minikind, fingerprint, size, executable, tree_data)
1942
1492
 
1943
 
    def _iter_child_entries(self, tree_index, path_utf8):
1944
 
        """Iterate over all the entries that are children of path_utf.
1945
 
 
1946
 
        This only returns entries that are present (not in 'a', 'r') in
1947
 
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
1948
 
        results may differ from that obtained if paths were statted to
1949
 
        determine what ones were directories.
1950
 
 
1951
 
        Asking for the children of a non-directory will return an empty
1952
 
        iterator.
1953
 
        """
1954
 
        pending_dirs = []
1955
 
        next_pending_dirs = [path_utf8]
1956
 
        absent = 'ar'
1957
 
        while next_pending_dirs:
1958
 
            pending_dirs = next_pending_dirs
1959
 
            next_pending_dirs = []
1960
 
            for path in pending_dirs:
1961
 
                block_index, present = self._find_block_index_from_key(
1962
 
                    (path, '', ''))
1963
 
                if block_index == 0:
1964
 
                    block_index = 1
1965
 
                    if len(self._dirblocks) == 1:
1966
 
                        # asked for the children of the root with no other
1967
 
                        # contents.
1968
 
                        return
1969
 
                if not present:
1970
 
                    # children of a non-directory asked for.
1971
 
                    continue
1972
 
                block = self._dirblocks[block_index]
1973
 
                for entry in block[1]:
1974
 
                    kind = entry[1][tree_index][0]
1975
 
                    if kind not in absent:
1976
 
                        yield entry
1977
 
                    if kind == 'd':
1978
 
                        if entry[0][0]:
1979
 
                            path = entry[0][0] + '/' + entry[0][1]
1980
 
                        else:
1981
 
                            path = entry[0][1]
1982
 
                        next_pending_dirs.append(path)
1983
 
 
1984
1493
    def _iter_entries(self):
1985
1494
        """Iterate over all the entries in the dirstate.
1986
1495
 
2002
1511
        return self._id_index
2003
1512
 
2004
1513
    def _get_output_lines(self, lines):
2005
 
        """Format lines for final output.
 
1514
        """format lines for final output.
2006
1515
 
2007
 
        :param lines: A sequence of lines containing the parents list and the
 
1516
        :param lines: A sequece of lines containing the parents list and the
2008
1517
            path lines.
2009
1518
        """
2010
1519
        output_lines = [DirState.HEADER_FORMAT_3]
2018
1527
        return output_lines
2019
1528
 
2020
1529
    def _make_deleted_row(self, fileid_utf8, parents):
2021
 
        """Return a deleted row for fileid_utf8."""
 
1530
        """Return a deleted for for fileid_utf8."""
2022
1531
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
2023
1532
            ''), parents
2024
1533
 
2027
1536
        return len(self._parents) - len(self._ghosts)
2028
1537
 
2029
1538
    @staticmethod
2030
 
    def on_file(path, sha1_provider=None):
2031
 
        """Construct a DirState on the file at path "path".
 
1539
    def on_file(path):
 
1540
        """Construct a DirState on the file at path path.
2032
1541
 
2033
 
        :param path: The path at which the dirstate file on disk should live.
2034
 
        :param sha1_provider: an object meeting the SHA1Provider interface.
2035
 
            If None, a DefaultSHA1Provider is used.
2036
1542
        :return: An unlocked DirState object, associated with the given path.
2037
1543
        """
2038
 
        if sha1_provider is None:
2039
 
            sha1_provider = DefaultSHA1Provider()
2040
 
        result = DirState(path, sha1_provider)
 
1544
        result = DirState(path)
2041
1545
        return result
2042
1546
 
2043
1547
    def _read_dirblocks_if_needed(self):
2044
1548
        """Read in all the dirblocks from the file if they are not in memory.
2045
 
 
 
1549
        
2046
1550
        This populates self._dirblocks, and sets self._dirblock_state to
2047
1551
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
2048
1552
        loading.
2063
1567
        parent_line = self._state_file.readline()
2064
1568
        info = parent_line.split('\0')
2065
1569
        num_parents = int(info[0])
 
1570
        assert num_parents == len(info)-2, 'incorrect parent info line'
2066
1571
        self._parents = info[1:-1]
 
1572
 
2067
1573
        ghost_line = self._state_file.readline()
2068
1574
        info = ghost_line.split('\0')
2069
1575
        num_ghosts = int(info[1])
 
1576
        assert num_ghosts == len(info)-3, 'incorrect ghost info line'
2070
1577
        self._ghosts = info[2:-1]
2071
1578
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
2072
1579
        self._end_of_header = self._state_file.tell()
2080
1587
            self._read_header()
2081
1588
 
2082
1589
    def _read_prelude(self):
2083
 
        """Read in the prelude header of the dirstate file.
 
1590
        """Read in the prelude header of the dirstate file
2084
1591
 
2085
1592
        This only reads in the stuff that is not connected to the crc
2086
1593
        checksum. The position will be correct to read in the rest of
2089
1596
        and their ids. Followed by a newline.
2090
1597
        """
2091
1598
        header = self._state_file.readline()
2092
 
        if header != DirState.HEADER_FORMAT_3:
2093
 
            raise errors.BzrError(
2094
 
                'invalid header line: %r' % (header,))
 
1599
        assert header == DirState.HEADER_FORMAT_3, \
 
1600
            'invalid header line: %r' % (header,)
2095
1601
        crc_line = self._state_file.readline()
2096
 
        if not crc_line.startswith('crc32: '):
2097
 
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
 
1602
        assert crc_line.startswith('crc32: '), 'missing crc32 checksum'
2098
1603
        self.crc_expected = int(crc_line[len('crc32: '):-1])
2099
1604
        num_entries_line = self._state_file.readline()
2100
 
        if not num_entries_line.startswith('num_entries: '):
2101
 
            raise errors.BzrError('missing num_entries line')
 
1605
        assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
2102
1606
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
2103
1607
 
2104
 
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
2105
 
        """Find a sha1 given a stat lookup."""
2106
 
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
2107
 
 
2108
 
    def _get_packed_stat_index(self):
2109
 
        """Get a packed_stat index of self._dirblocks."""
2110
 
        if self._packed_stat_index is None:
2111
 
            index = {}
2112
 
            for key, tree_details in self._iter_entries():
2113
 
                if tree_details[0][0] == 'f':
2114
 
                    index[tree_details[0][4]] = tree_details[0][1]
2115
 
            self._packed_stat_index = index
2116
 
        return self._packed_stat_index
2117
 
 
2118
1608
    def save(self):
2119
1609
        """Save any pending changes created during this session.
2120
1610
 
2121
1611
        We reuse the existing file, because that prevents race conditions with
2122
1612
        file creation, and use oslocks on it to prevent concurrent modification
2123
 
        and reads - because dirstate's incremental data aggregation is not
 
1613
        and reads - because dirstates incremental data aggretation is not
2124
1614
        compatible with reading a modified file, and replacing a file in use by
2125
 
        another process is impossible on Windows.
 
1615
        another process is impossible on windows.
2126
1616
 
2127
1617
        A dirstate in read only mode should be smart enough though to validate
2128
1618
        that the file has not changed, and otherwise discard its cache and
2129
1619
        start over, to allow for fine grained read lock duration, so 'status'
2130
1620
        wont block 'commit' - for example.
2131
1621
        """
2132
 
        if self._changes_aborted:
2133
 
            # Should this be a warning? For now, I'm expecting that places that
2134
 
            # mark it inconsistent will warn, making a warning here redundant.
2135
 
            trace.mutter('Not saving DirState because '
2136
 
                    '_changes_aborted is set.')
2137
 
            return
2138
1622
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
2139
1623
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2140
1624
 
2173
1657
 
2174
1658
        :param parent_ids: A list of parent tree revision ids.
2175
1659
        :param dirblocks: A list containing one tuple for each directory in the
2176
 
            tree. Each tuple contains the directory path and a list of entries
 
1660
            tree. Each tuple contains the directory path and a list of entries 
2177
1661
            found in that directory.
2178
1662
        """
2179
1663
        # our memory copy is now authoritative.
2182
1666
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2183
1667
        self._parents = list(parent_ids)
2184
1668
        self._id_index = None
2185
 
        self._packed_stat_index = None
2186
1669
 
2187
1670
    def set_path_id(self, path, new_id):
2188
1671
        """Change the id of path to new_id in the current working tree.
2192
1675
        :param new_id: The new id to assign to the path. This must be a utf8
2193
1676
            file id (not unicode, and not None).
2194
1677
        """
 
1678
        assert new_id.__class__ == str, \
 
1679
            "path_id %r is not a plain string" % (new_id,)
2195
1680
        self._read_dirblocks_if_needed()
2196
1681
        if len(path):
2197
 
            # TODO: logic not written
 
1682
            # logic not written
2198
1683
            raise NotImplementedError(self.set_path_id)
2199
1684
        # TODO: check new id is unique
2200
1685
        entry = self._get_entry(0, path_utf8=path)
2213
1698
        """Set the parent trees for the dirstate.
2214
1699
 
2215
1700
        :param trees: A list of revision_id, tree tuples. tree must be provided
2216
 
            even if the revision_id refers to a ghost: supply an empty tree in
 
1701
            even if the revision_id refers to a ghost: supply an empty tree in 
2217
1702
            this case.
2218
1703
        :param ghosts: A list of the revision_ids that are ghosts at the time
2219
1704
            of setting.
2220
 
        """
2221
 
        # TODO: generate a list of parent indexes to preserve to save
 
1705
        """ 
 
1706
        # TODO: generate a list of parent indexes to preserve to save 
2222
1707
        # processing specific parent trees. In the common case one tree will
2223
1708
        # be preserved - the left most parent.
2224
1709
        # TODO: if the parent tree is a dirstate, we might want to walk them
2229
1714
        # map and then walk the new parent trees only, mapping them into the
2230
1715
        # dirstate. Walk the dirstate at the same time to remove unreferenced
2231
1716
        # entries.
2232
 
        # for now:
2233
 
        # sketch: loop over all entries in the dirstate, cherry picking
 
1717
        # for now: 
 
1718
        # sketch: loop over all entries in the dirstate, cherry picking 
2234
1719
        # entries from the parent trees, if they are not ghost trees.
2235
1720
        # after we finish walking the dirstate, all entries not in the dirstate
2236
1721
        # are deletes, so we want to append them to the end as per the design
2241
1726
        #   links. We dont't trivially use the inventory from other trees
2242
1727
        #   because this leads to either double touching, or to accessing
2243
1728
        #   missing keys,
2244
 
        # - find other keys containing a path
2245
 
        # We accumulate each entry via this dictionary, including the root
 
1729
        # - find other keys containing a path 
 
1730
        # We accumulate each entry via this dictionary, including the root 
2246
1731
        by_path = {}
2247
1732
        id_index = {}
2248
1733
        # we could do parallel iterators, but because file id data may be
2252
1737
        # parent, but for now the common cases are adding a new parent (merge),
2253
1738
        # and replacing completely (commit), and commit is more common: so
2254
1739
        # optimise merge later.
2255
 
 
 
1740
        
2256
1741
        # ---- start generation of full tree mapping data
2257
1742
        # what trees should we use?
2258
1743
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2259
 
        # how many trees do we end up with
 
1744
        # how many trees do we end up with 
2260
1745
        parent_count = len(parent_trees)
2261
1746
 
2262
1747
        # one: the current tree
2263
1748
        for entry in self._iter_entries():
2264
1749
            # skip entries not in the current tree
2265
 
            if entry[1][0][0] in 'ar': # absent, relocated
 
1750
            if entry[1][0][0] in ('a', 'r'): # absent, relocated
2266
1751
                continue
2267
1752
            by_path[entry[0]] = [entry[1][0]] + \
2268
1753
                [DirState.NULL_PARENT_DETAILS] * parent_count
2269
1754
            id_index[entry[0][2]] = set([entry[0]])
2270
 
 
 
1755
        
2271
1756
        # now the parent trees:
2272
1757
        for tree_index, tree in enumerate(parent_trees):
2273
1758
            # the index is off by one, adjust it.
2287
1772
                # avoid checking all known paths for the id when generating a
2288
1773
                # new entry at this path: by adding the id->path mapping last,
2289
1774
                # all the mappings are valid and have correct relocation
2290
 
                # records where needed.
 
1775
                # records where needed. 
2291
1776
                file_id = entry.file_id
2292
1777
                path_utf8 = path.encode('utf8')
2293
1778
                dirname, basename = osutils.split(path_utf8)
2302
1787
                        # this file id is at a different path in one of the
2303
1788
                        # other trees, so put absent pointers there
2304
1789
                        # This is the vertical axis in the matrix, all pointing
2305
 
                        # to the real path.
 
1790
                        # tot he real path.
2306
1791
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
2307
 
                # by path consistency: Insert into an existing path record (trivial), or
 
1792
                # by path consistency: Insert into an existing path record (trivial), or 
2308
1793
                # add a new one with relocation pointers for the other tree indexes.
2309
1794
                if new_entry_key in id_index[file_id]:
2310
1795
                    # there is already an entry where this data belongs, just insert it.
2323
1808
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2324
1809
                        else:
2325
1810
                            # grab any one entry, use it to find the right path.
2326
 
                            # TODO: optimise this to reduce memory use in highly
 
1811
                            # TODO: optimise this to reduce memory use in highly 
2327
1812
                            # fragmented situations by reusing the relocation
2328
1813
                            # records.
2329
1814
                            a_key = iter(id_index[file_id]).next()
2356
1841
        try to keep everything in sorted blocks all the time, but sometimes
2357
1842
        it's easier to sort after the fact.
2358
1843
        """
 
1844
        # TODO: Might be faster to do a schwartzian transform?
2359
1845
        def _key(entry):
2360
1846
            # sort by: directory parts, file name, file id
2361
1847
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
2362
1848
        return sorted(entry_list, key=_key)
2363
1849
 
2364
1850
    def set_state_from_inventory(self, new_inv):
2365
 
        """Set new_inv as the current state.
 
1851
        """Set new_inv as the current state. 
2366
1852
 
2367
1853
        This API is called by tree transform, and will usually occur with
2368
1854
        existing parent trees.
2369
1855
 
2370
1856
        :param new_inv: The inventory object to set current state from.
2371
1857
        """
2372
 
        if 'evil' in debug.debug_flags:
2373
 
            trace.mutter_callsite(1,
2374
 
                "set_state_from_inventory called; please mutate the tree instead")
2375
1858
        self._read_dirblocks_if_needed()
2376
1859
        # sketch:
2377
 
        # Two iterators: current data and new data, both in dirblock order.
2378
 
        # We zip them together, which tells about entries that are new in the
2379
 
        # inventory, or removed in the inventory, or present in both and
2380
 
        # possibly changed.
2381
 
        #
2382
 
        # You might think we could just synthesize a new dirstate directly
2383
 
        # since we're processing it in the right order.  However, we need to
2384
 
        # also consider there may be any number of parent trees and relocation
2385
 
        # pointers, and we don't want to duplicate that here.
 
1860
        # incremental algorithm:
 
1861
        # two iterators: current data and new data, both in dirblock order. 
2386
1862
        new_iterator = new_inv.iter_entries_by_dir()
2387
1863
        # we will be modifying the dirstate, so we need a stable iterator. In
2388
1864
        # future we might write one, for now we just clone the state into a
2389
 
        # list - which is a shallow copy.
 
1865
        # list - which is a shallow copy, so each 
2390
1866
        old_iterator = iter(list(self._iter_entries()))
2391
1867
        # both must have roots so this is safe:
2392
1868
        current_new = new_iterator.next()
2398
1874
                return None
2399
1875
        while current_new or current_old:
2400
1876
            # skip entries in old that are not really there
2401
 
            if current_old and current_old[1][0][0] in 'ar':
 
1877
            if current_old and current_old[1][0][0] in ('r', 'a'):
2402
1878
                # relocated or absent
2403
1879
                current_old = advance(old_iterator)
2404
1880
                continue
2411
1887
                current_new_minikind = \
2412
1888
                    DirState._kind_to_minikind[current_new[1].kind]
2413
1889
                if current_new_minikind == 't':
2414
 
                    fingerprint = current_new[1].reference_revision or ''
 
1890
                    fingerprint = current_new[1].reference_revision
2415
1891
                else:
2416
 
                    # We normally only insert or remove records, or update
2417
 
                    # them when it has significantly changed.  Then we want to
2418
 
                    # erase its fingerprint.  Unaffected records should
2419
 
                    # normally not be updated at all.
2420
1892
                    fingerprint = ''
2421
1893
            else:
2422
1894
                # for safety disable variables
2423
 
                new_path_utf8 = new_dirname = new_basename = new_id = \
2424
 
                    new_entry_key = None
 
1895
                new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
2425
1896
            # 5 cases, we dont have a value that is strictly greater than everything, so
2426
1897
            # we make both end conditions explicit
2427
1898
            if not current_old:
2436
1907
                current_old = advance(old_iterator)
2437
1908
            elif new_entry_key == current_old[0]:
2438
1909
                # same -  common case
2439
 
                # We're looking at the same path and id in both the dirstate
2440
 
                # and inventory, so just need to update the fields in the
2441
 
                # dirstate from the one in the inventory.
2442
1910
                # TODO: update the record if anything significant has changed.
2443
1911
                # the minimal required trigger is if the execute bit or cached
2444
1912
                # kind has changed.
2450
1918
                # both sides are dealt with, move on
2451
1919
                current_old = advance(old_iterator)
2452
1920
                current_new = advance(new_iterator)
2453
 
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
2454
 
                  or (new_dirname == current_old[0][0]
2455
 
                      and new_entry_key[1:] < current_old[0][1:])):
 
1921
            elif (new_entry_key[0].split('/') < current_old[0][0].split('/')
 
1922
                  and new_entry_key[1:] < current_old[0][1:]):
2456
1923
                # new comes before:
2457
1924
                # add a entry for this and advance new
2458
1925
                self.update_minimal(new_entry_key, current_new_minikind,
2460
1927
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
2461
1928
                current_new = advance(new_iterator)
2462
1929
            else:
2463
 
                # we've advanced past the place where the old key would be,
2464
 
                # without seeing it in the new list.  so it must be gone.
 
1930
                # old comes before:
2465
1931
                self._make_absent(current_old)
2466
1932
                current_old = advance(old_iterator)
2467
1933
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2468
1934
        self._id_index = None
2469
 
        self._packed_stat_index = None
2470
1935
 
2471
1936
    def _make_absent(self, current_old):
2472
1937
        """Mark current_old - an entry - as absent for tree 0.
2473
1938
 
2474
 
        :return: True if this was the last details entry for the entry key:
 
1939
        :return: True if this was the last details entry for they entry key:
2475
1940
            that is, if the underlying block has had the entry removed, thus
2476
1941
            shrinking in length.
2477
1942
        """
2478
1943
        # build up paths that this id will be left at after the change is made,
2479
1944
        # so we can update their cross references in tree 0
2480
1945
        all_remaining_keys = set()
2481
 
        # Dont check the working tree, because it's going.
 
1946
        # Dont check the working tree, because its going.
2482
1947
        for details in current_old[1][1:]:
2483
 
            if details[0] not in 'ar': # absent, relocated
 
1948
            if details[0] not in ('a', 'r'): # absent, relocated
2484
1949
                all_remaining_keys.add(current_old[0])
2485
1950
            elif details[0] == 'r': # relocated
2486
1951
                # record the key for the real path.
2493
1958
            # Remove it, its meaningless.
2494
1959
            block = self._find_block(current_old[0])
2495
1960
            entry_index, present = self._find_entry_index(current_old[0], block[1])
2496
 
            if not present:
2497
 
                raise AssertionError('could not find entry for %s' % (current_old,))
 
1961
            assert present, 'could not find entry for %s' % (current_old,)
2498
1962
            block[1].pop(entry_index)
2499
1963
            # if we have an id_index in use, remove this key from it for this id.
2500
1964
            if self._id_index is not None:
2501
1965
                self._id_index[current_old[0][2]].remove(current_old[0])
2502
1966
        # update all remaining keys for this id to record it as absent. The
2503
 
        # existing details may either be the record we are marking as deleted
 
1967
        # existing details may either be the record we are making as deleted
2504
1968
        # (if there were other trees with the id present at this path), or may
2505
1969
        # be relocations.
2506
1970
        for update_key in all_remaining_keys:
2507
1971
            update_block_index, present = \
2508
1972
                self._find_block_index_from_key(update_key)
2509
 
            if not present:
2510
 
                raise AssertionError('could not find block for %s' % (update_key,))
 
1973
            assert present, 'could not find block for %s' % (update_key,)
2511
1974
            update_entry_index, present = \
2512
1975
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
2513
 
            if not present:
2514
 
                raise AssertionError('could not find entry for %s' % (update_key,))
 
1976
            assert present, 'could not find entry for %s' % (update_key,)
2515
1977
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
2516
1978
            # it must not be absent at the moment
2517
 
            if update_tree_details[0][0] == 'a': # absent
2518
 
                raise AssertionError('bad row %r' % (update_tree_details,))
 
1979
            assert update_tree_details[0][0] != 'a' # absent
2519
1980
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2520
1981
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2521
1982
        return last_reference
2532
1993
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
2533
1994
                'directory'), etc.
2534
1995
        :param executable: Should the executable bit be set?
2535
 
        :param fingerprint: Simple fingerprint for new entry: canonical-form
2536
 
            sha1 for files, referenced revision id for subtrees, etc.
2537
 
        :param packed_stat: Packed stat value for new entry.
 
1996
        :param fingerprint: Simple fingerprint for new entry.
 
1997
        :param packed_stat: packed stat value for new entry.
2538
1998
        :param size: Size information for new entry
2539
1999
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
2540
2000
                extra computation.
2541
 
 
2542
 
        If packed_stat and fingerprint are not given, they're invalidated in
2543
 
        the entry.
2544
2001
        """
2545
2002
        block = self._find_block(key)[1]
2546
2003
        if packed_stat is None:
2547
2004
            packed_stat = DirState.NULLSTAT
2548
 
        # XXX: Some callers pass '' as the packed_stat, and it seems to be
2549
 
        # sometimes present in the dirstate - this seems oddly inconsistent.
2550
 
        # mbp 20071008
2551
2005
        entry_index, present = self._find_entry_index(key, block)
2552
2006
        new_details = (minikind, fingerprint, size, executable, packed_stat)
2553
2007
        id_index = self._get_id_index()
2569
2023
                    # the test for existing kinds is different: this can be
2570
2024
                    # factored out to a helper though.
2571
2025
                    other_block_index, present = self._find_block_index_from_key(other_key)
2572
 
                    if not present:
2573
 
                        raise AssertionError('could not find block for %s' % (other_key,))
 
2026
                    assert present, 'could not find block for %s' % (other_key,)
2574
2027
                    other_entry_index, present = self._find_entry_index(other_key,
2575
2028
                                            self._dirblocks[other_block_index][1])
2576
 
                    if not present:
2577
 
                        raise AssertionError('could not find entry for %s' % (other_key,))
2578
 
                    if path_utf8 is None:
2579
 
                        raise AssertionError('no path')
 
2029
                    assert present, 'could not find entry for %s' % (other_key,)
 
2030
                    assert path_utf8 is not None
2580
2031
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
2581
2032
                        ('r', path_utf8, 0, False, '')
2582
2033
 
2583
2034
                num_present_parents = self._num_present_parents()
2584
2035
                for lookup_index in xrange(1, num_present_parents + 1):
2585
2036
                    # grab any one entry, use it to find the right path.
2586
 
                    # TODO: optimise this to reduce memory use in highly
 
2037
                    # TODO: optimise this to reduce memory use in highly 
2587
2038
                    # fragmented situations by reusing the relocation
2588
2039
                    # records.
2589
2040
                    update_block_index, present = \
2590
2041
                        self._find_block_index_from_key(other_key)
2591
 
                    if not present:
2592
 
                        raise AssertionError('could not find block for %s' % (other_key,))
 
2042
                    assert present, 'could not find block for %s' % (other_key,)
2593
2043
                    update_entry_index, present = \
2594
2044
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
2595
 
                    if not present:
2596
 
                        raise AssertionError('could not find entry for %s' % (other_key,))
 
2045
                    assert present, 'could not find entry for %s' % (other_key,)
2597
2046
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
2598
 
                    if update_details[0] in 'ar': # relocated, absent
 
2047
                    if update_details[0] in ('r', 'a'): # relocated, absent
2599
2048
                        # its a pointer or absent in lookup_index's tree, use
2600
2049
                        # it as is.
2601
2050
                        new_entry[1].append(update_details)
2606
2055
            block.insert(entry_index, new_entry)
2607
2056
            existing_keys.add(key)
2608
2057
        else:
2609
 
            # Does the new state matter?
 
2058
            # Does the new state matter? 
2610
2059
            block[entry_index][1][0] = new_details
2611
2060
            # parents cannot be affected by what we do.
2612
 
            # other occurences of this id can be found
 
2061
            # other occurences of this id can be found 
2613
2062
            # from the id index.
2614
2063
            # ---
2615
2064
            # tree index consistency: All other paths for this id in this tree
2617
2066
            # we may have passed entries in the state with this file id already
2618
2067
            # that were absent - where parent entries are - and they need to be
2619
2068
            # converted to relocated.
2620
 
            if path_utf8 is None:
2621
 
                raise AssertionError('no path')
 
2069
            assert path_utf8 is not None
2622
2070
            for entry_key in id_index.setdefault(key[2], set()):
2623
2071
                # TODO:PROFILING: It might be faster to just update
2624
2072
                # rather than checking if we need to, and then overwrite
2629
2077
                    # This is the vertical axis in the matrix, all pointing
2630
2078
                    # to the real path.
2631
2079
                    block_index, present = self._find_block_index_from_key(entry_key)
2632
 
                    if not present:
2633
 
                        raise AssertionError('not present: %r', entry_key)
 
2080
                    assert present
2634
2081
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
2635
 
                    if not present:
2636
 
                        raise AssertionError('not present: %r', entry_key)
 
2082
                    assert present
2637
2083
                    self._dirblocks[block_index][1][entry_index][1][0] = \
2638
2084
                        ('r', path_utf8, 0, False, '')
2639
2085
        # add a containing dirblock if needed.
2648
2094
    def _validate(self):
2649
2095
        """Check that invariants on the dirblock are correct.
2650
2096
 
2651
 
        This can be useful in debugging; it shouldn't be necessary in
 
2097
        This can be useful in debugging; it shouldn't be necessary in 
2652
2098
        normal code.
2653
2099
 
2654
2100
        This must be called with a lock held.
2670
2116
            if not self._dirblocks[0][0] == '':
2671
2117
                raise AssertionError(
2672
2118
                    "dirblocks don't start with root block:\n" + \
2673
 
                    pformat(self._dirblocks))
 
2119
                    pformat(dirblocks))
2674
2120
        if len(self._dirblocks) > 1:
2675
2121
            if not self._dirblocks[1][0] == '':
2676
2122
                raise AssertionError(
2677
2123
                    "dirblocks missing root directory:\n" + \
2678
 
                    pformat(self._dirblocks))
 
2124
                    pformat(dirblocks))
2679
2125
        # the dirblocks are sorted by their path components, name, and dir id
2680
2126
        dir_names = [d[0].split('/')
2681
2127
                for d in self._dirblocks[1:]]
2699
2145
                    "dirblock for %r is not sorted:\n%s" % \
2700
2146
                    (dirblock[0], pformat(dirblock)))
2701
2147
 
 
2148
 
2702
2149
        def check_valid_parent():
2703
2150
            """Check that the current entry has a valid parent.
2704
2151
 
2723
2170
        # For each file id, for each tree: either
2724
2171
        # the file id is not present at all; all rows with that id in the
2725
2172
        # key have it marked as 'absent'
2726
 
        # OR the file id is present under exactly one name; any other entries
 
2173
        # OR the file id is present under exactly one name; any other entries 
2727
2174
        # that mention that id point to the correct name.
2728
2175
        #
2729
2176
        # We check this with a dict per tree pointing either to the present
2739
2186
                "wrong number of entry details for row\n%s" \
2740
2187
                ",\nexpected %d" % \
2741
2188
                (pformat(entry), tree_count))
2742
 
            absent_positions = 0
2743
2189
            for tree_index, tree_state in enumerate(entry[1]):
2744
2190
                this_tree_map = id_path_maps[tree_index]
2745
2191
                minikind = tree_state[0]
2746
 
                if minikind in 'ar':
2747
 
                    absent_positions += 1
2748
2192
                # have we seen this id before in this column?
2749
2193
                if file_id in this_tree_map:
2750
 
                    previous_path, previous_loc = this_tree_map[file_id]
 
2194
                    previous_path = this_tree_map[file_id]
2751
2195
                    # any later mention of this file must be consistent with
2752
2196
                    # what was said before
2753
2197
                    if minikind == 'a':
2767
2211
                        # pointed to by a relocation, which must point here
2768
2212
                        if previous_path != this_path:
2769
2213
                            raise AssertionError(
2770
 
                                "entry %r inconsistent with previous path %r "
2771
 
                                "seen at %r" %
2772
 
                                (entry, previous_path, previous_loc))
 
2214
                            "entry %r inconsistent with previous path %r" % \
 
2215
                            (entry, previous_path))
2773
2216
                        check_valid_parent()
2774
2217
                else:
2775
2218
                    if minikind == 'a':
2776
2219
                        # absent; should not occur anywhere else
2777
 
                        this_tree_map[file_id] = None, this_path
 
2220
                        this_tree_map[file_id] = None
2778
2221
                    elif minikind == 'r':
2779
 
                        # relocation, must occur at expected location
2780
 
                        this_tree_map[file_id] = tree_state[1], this_path
 
2222
                        # relocation, must occur at expected location 
 
2223
                        this_tree_map[file_id] = tree_state[1]
2781
2224
                    else:
2782
 
                        this_tree_map[file_id] = this_path, this_path
 
2225
                        this_tree_map[file_id] = this_path
2783
2226
                        check_valid_parent()
2784
 
            if absent_positions == tree_count:
2785
 
                raise AssertionError(
2786
 
                    "entry %r has no data for any tree." % (entry,))
2787
2227
 
2788
2228
    def _wipe_state(self):
2789
2229
        """Forget all state information about the dirstate."""
2790
2230
        self._header_state = DirState.NOT_IN_MEMORY
2791
2231
        self._dirblock_state = DirState.NOT_IN_MEMORY
2792
 
        self._changes_aborted = False
2793
2232
        self._parents = []
2794
2233
        self._ghosts = []
2795
2234
        self._dirblocks = []
2796
2235
        self._id_index = None
2797
 
        self._packed_stat_index = None
2798
2236
        self._end_of_header = None
2799
2237
        self._cutoff_time = None
2800
2238
        self._split_path_cache = {}
2801
2239
 
2802
2240
    def lock_read(self):
2803
 
        """Acquire a read lock on the dirstate."""
 
2241
        """Acquire a read lock on the dirstate"""
2804
2242
        if self._lock_token is not None:
2805
2243
            raise errors.LockContention(self._lock_token)
2806
2244
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
2813
2251
        self._wipe_state()
2814
2252
 
2815
2253
    def lock_write(self):
2816
 
        """Acquire a write lock on the dirstate."""
 
2254
        """Acquire a write lock on the dirstate"""
2817
2255
        if self._lock_token is not None:
2818
2256
            raise errors.LockContention(self._lock_token)
2819
2257
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
2826
2264
        self._wipe_state()
2827
2265
 
2828
2266
    def unlock(self):
2829
 
        """Drop any locks held on the dirstate."""
 
2267
        """Drop any locks held on the dirstate"""
2830
2268
        if self._lock_token is None:
2831
2269
            raise errors.LockNotHeld(self)
2832
2270
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
2840
2278
        self._split_path_cache = {}
2841
2279
 
2842
2280
    def _requires_lock(self):
2843
 
        """Check that a lock is currently held by someone on the dirstate."""
 
2281
        """Checks that a lock is currently held by someone on the dirstate"""
2844
2282
        if not self._lock_token:
2845
2283
            raise errors.ObjectNotLocked(self)
2846
2284
 
2847
2285
 
2848
 
def py_update_entry(state, entry, abspath, stat_value,
2849
 
                 _stat_to_minikind=DirState._stat_to_minikind,
2850
 
                 _pack_stat=pack_stat):
2851
 
    """Update the entry based on what is actually on disk.
2852
 
 
2853
 
    This function only calculates the sha if it needs to - if the entry is
2854
 
    uncachable, or clearly different to the first parent's entry, no sha
2855
 
    is calculated, and None is returned.
2856
 
 
2857
 
    :param state: The dirstate this entry is in.
2858
 
    :param entry: This is the dirblock entry for the file in question.
2859
 
    :param abspath: The path on disk for this file.
2860
 
    :param stat_value: The stat value done on the path.
2861
 
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
2862
 
        target of a symlink.
2863
 
    """
2864
 
    try:
2865
 
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
2866
 
    except KeyError:
2867
 
        # Unhandled kind
2868
 
        return None
2869
 
    packed_stat = _pack_stat(stat_value)
2870
 
    (saved_minikind, saved_link_or_sha1, saved_file_size,
2871
 
     saved_executable, saved_packed_stat) = entry[1][0]
2872
 
 
2873
 
    if minikind == 'd' and saved_minikind == 't':
2874
 
        minikind = 't'
2875
 
    if (minikind == saved_minikind
2876
 
        and packed_stat == saved_packed_stat):
2877
 
        # The stat hasn't changed since we saved, so we can re-use the
2878
 
        # saved sha hash.
2879
 
        if minikind == 'd':
2880
 
            return None
2881
 
 
2882
 
        # size should also be in packed_stat
2883
 
        if saved_file_size == stat_value.st_size:
2884
 
            return saved_link_or_sha1
2885
 
 
2886
 
    # If we have gotten this far, that means that we need to actually
2887
 
    # process this entry.
2888
 
    link_or_sha1 = None
2889
 
    if minikind == 'f':
2890
 
        executable = state._is_executable(stat_value.st_mode,
2891
 
                                         saved_executable)
2892
 
        if state._cutoff_time is None:
2893
 
            state._sha_cutoff_time()
2894
 
        if (stat_value.st_mtime < state._cutoff_time
2895
 
            and stat_value.st_ctime < state._cutoff_time
2896
 
            and len(entry[1]) > 1
2897
 
            and entry[1][1][0] != 'a'):
2898
 
            # Could check for size changes for further optimised
2899
 
            # avoidance of sha1's. However the most prominent case of
2900
 
            # over-shaing is during initial add, which this catches.
2901
 
            # Besides, if content filtering happens, size and sha
2902
 
            # are calculated at the same time, so checking just the size
2903
 
            # gains nothing w.r.t. performance.
2904
 
            link_or_sha1 = state._sha1_file(abspath)
2905
 
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
2906
 
                           executable, packed_stat)
2907
 
        else:
2908
 
            entry[1][0] = ('f', '', stat_value.st_size,
2909
 
                           executable, DirState.NULLSTAT)
2910
 
    elif minikind == 'd':
2911
 
        link_or_sha1 = None
2912
 
        entry[1][0] = ('d', '', 0, False, packed_stat)
2913
 
        if saved_minikind != 'd':
2914
 
            # This changed from something into a directory. Make sure we
2915
 
            # have a directory block for it. This doesn't happen very
2916
 
            # often, so this doesn't have to be super fast.
2917
 
            block_index, entry_index, dir_present, file_present = \
2918
 
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
2919
 
            state._ensure_block(block_index, entry_index,
2920
 
                               osutils.pathjoin(entry[0][0], entry[0][1]))
2921
 
    elif minikind == 'l':
2922
 
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
2923
 
        if state._cutoff_time is None:
2924
 
            state._sha_cutoff_time()
2925
 
        if (stat_value.st_mtime < state._cutoff_time
2926
 
            and stat_value.st_ctime < state._cutoff_time):
2927
 
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
2928
 
                           False, packed_stat)
2929
 
        else:
2930
 
            entry[1][0] = ('l', '', stat_value.st_size,
2931
 
                           False, DirState.NULLSTAT)
2932
 
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
2933
 
    return link_or_sha1
2934
 
update_entry = py_update_entry
2935
 
 
2936
 
 
2937
 
class ProcessEntryPython(object):
2938
 
 
2939
 
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id", "uninteresting",
2940
 
        "last_source_parent", "last_target_parent", "include_unchanged",
2941
 
        "use_filesystem_for_exec", "utf8_decode", "searched_specific_files",
2942
 
        "search_specific_files", "state", "source_index", "target_index",
2943
 
        "want_unversioned", "tree"]
2944
 
 
2945
 
    def __init__(self, include_unchanged, use_filesystem_for_exec,
2946
 
        search_specific_files, state, source_index, target_index,
2947
 
        want_unversioned, tree):
2948
 
        self.old_dirname_to_file_id = {}
2949
 
        self.new_dirname_to_file_id = {}
2950
 
        # Just a sentry, so that _process_entry can say that this
2951
 
        # record is handled, but isn't interesting to process (unchanged)
2952
 
        self.uninteresting = object()
2953
 
        # Using a list so that we can access the values and change them in
2954
 
        # nested scope. Each one is [path, file_id, entry]
2955
 
        self.last_source_parent = [None, None]
2956
 
        self.last_target_parent = [None, None]
2957
 
        self.include_unchanged = include_unchanged
2958
 
        self.use_filesystem_for_exec = use_filesystem_for_exec
2959
 
        self.utf8_decode = cache_utf8._utf8_decode
2960
 
        # for all search_indexs in each path at or under each element of
2961
 
        # search_specific_files, if the detail is relocated: add the id, and add the
2962
 
        # relocated path as one to search if its not searched already. If the
2963
 
        # detail is not relocated, add the id.
2964
 
        self.searched_specific_files = set()
2965
 
        self.search_specific_files = search_specific_files
2966
 
        self.state = state
2967
 
        self.source_index = source_index
2968
 
        self.target_index = target_index
2969
 
        self.want_unversioned = want_unversioned
2970
 
        self.tree = tree
2971
 
 
2972
 
    def _process_entry(self, entry, path_info, pathjoin=osutils.pathjoin):
2973
 
        """Compare an entry and real disk to generate delta information.
2974
 
 
2975
 
        :param path_info: top_relpath, basename, kind, lstat, abspath for
2976
 
            the path of entry. If None, then the path is considered absent.
2977
 
            (Perhaps we should pass in a concrete entry for this ?)
2978
 
            Basename is returned as a utf8 string because we expect this
2979
 
            tuple will be ignored, and don't want to take the time to
2980
 
            decode.
2981
 
        :return: None if these don't match
2982
 
                 A tuple of information about the change, or
2983
 
                 the object 'uninteresting' if these match, but are
2984
 
                 basically identical.
2985
 
        """
2986
 
        if self.source_index is None:
2987
 
            source_details = DirState.NULL_PARENT_DETAILS
2988
 
        else:
2989
 
            source_details = entry[1][self.source_index]
2990
 
        target_details = entry[1][self.target_index]
2991
 
        target_minikind = target_details[0]
2992
 
        if path_info is not None and target_minikind in 'fdlt':
2993
 
            if not (self.target_index == 0):
2994
 
                raise AssertionError()
2995
 
            link_or_sha1 = update_entry(self.state, entry,
2996
 
                abspath=path_info[4], stat_value=path_info[3])
2997
 
            # The entry may have been modified by update_entry
2998
 
            target_details = entry[1][self.target_index]
2999
 
            target_minikind = target_details[0]
3000
 
        else:
3001
 
            link_or_sha1 = None
3002
 
        file_id = entry[0][2]
3003
 
        source_minikind = source_details[0]
3004
 
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
3005
 
            # claimed content in both: diff
3006
 
            #   r    | fdlt   |      | add source to search, add id path move and perform
3007
 
            #        |        |      | diff check on source-target
3008
 
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
3009
 
            #        |        |      | ???
3010
 
            if source_minikind in 'r':
3011
 
                # add the source to the search path to find any children it
3012
 
                # has.  TODO ? : only add if it is a container ?
3013
 
                if not osutils.is_inside_any(self.searched_specific_files,
3014
 
                                             source_details[1]):
3015
 
                    self.search_specific_files.add(source_details[1])
3016
 
                # generate the old path; this is needed for stating later
3017
 
                # as well.
3018
 
                old_path = source_details[1]
3019
 
                old_dirname, old_basename = os.path.split(old_path)
3020
 
                path = pathjoin(entry[0][0], entry[0][1])
3021
 
                old_entry = self.state._get_entry(self.source_index,
3022
 
                                             path_utf8=old_path)
3023
 
                # update the source details variable to be the real
3024
 
                # location.
3025
 
                if old_entry == (None, None):
3026
 
                    raise errors.CorruptDirstate(self.state._filename,
3027
 
                        "entry '%s/%s' is considered renamed from %r"
3028
 
                        " but source does not exist\n"
3029
 
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
3030
 
                source_details = old_entry[1][self.source_index]
3031
 
                source_minikind = source_details[0]
3032
 
            else:
3033
 
                old_dirname = entry[0][0]
3034
 
                old_basename = entry[0][1]
3035
 
                old_path = path = None
3036
 
            if path_info is None:
3037
 
                # the file is missing on disk, show as removed.
3038
 
                content_change = True
3039
 
                target_kind = None
3040
 
                target_exec = False
3041
 
            else:
3042
 
                # source and target are both versioned and disk file is present.
3043
 
                target_kind = path_info[2]
3044
 
                if target_kind == 'directory':
3045
 
                    if path is None:
3046
 
                        old_path = path = pathjoin(old_dirname, old_basename)
3047
 
                    self.new_dirname_to_file_id[path] = file_id
3048
 
                    if source_minikind != 'd':
3049
 
                        content_change = True
3050
 
                    else:
3051
 
                        # directories have no fingerprint
3052
 
                        content_change = False
3053
 
                    target_exec = False
3054
 
                elif target_kind == 'file':
3055
 
                    if source_minikind != 'f':
3056
 
                        content_change = True
3057
 
                    else:
3058
 
                        # If the size is the same, check the sha:
3059
 
                        if target_details[2] == source_details[2]:
3060
 
                            if link_or_sha1 is None:
3061
 
                                # Stat cache miss:
3062
 
                                statvalue, link_or_sha1 = \
3063
 
                                    self.state._sha1_provider.stat_and_sha1(
3064
 
                                    path_info[4])
3065
 
                                self.state._observed_sha1(entry, link_or_sha1,
3066
 
                                    statvalue)
3067
 
                            content_change = (link_or_sha1 != source_details[1])
3068
 
                        else:
3069
 
                            # Size changed, so must be different
3070
 
                            content_change = True
3071
 
                    # Target details is updated at update_entry time
3072
 
                    if self.use_filesystem_for_exec:
3073
 
                        # We don't need S_ISREG here, because we are sure
3074
 
                        # we are dealing with a file.
3075
 
                        target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
3076
 
                    else:
3077
 
                        target_exec = target_details[3]
3078
 
                elif target_kind == 'symlink':
3079
 
                    if source_minikind != 'l':
3080
 
                        content_change = True
3081
 
                    else:
3082
 
                        content_change = (link_or_sha1 != source_details[1])
3083
 
                    target_exec = False
3084
 
                elif target_kind == 'tree-reference':
3085
 
                    if source_minikind != 't':
3086
 
                        content_change = True
3087
 
                    else:
3088
 
                        content_change = False
3089
 
                    target_exec = False
3090
 
                else:
3091
 
                    raise Exception, "unknown kind %s" % path_info[2]
3092
 
            if source_minikind == 'd':
3093
 
                if path is None:
3094
 
                    old_path = path = pathjoin(old_dirname, old_basename)
3095
 
                self.old_dirname_to_file_id[old_path] = file_id
3096
 
            # parent id is the entry for the path in the target tree
3097
 
            if old_dirname == self.last_source_parent[0]:
3098
 
                source_parent_id = self.last_source_parent[1]
3099
 
            else:
3100
 
                try:
3101
 
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
3102
 
                except KeyError:
3103
 
                    source_parent_entry = self.state._get_entry(self.source_index,
3104
 
                                                           path_utf8=old_dirname)
3105
 
                    source_parent_id = source_parent_entry[0][2]
3106
 
                if source_parent_id == entry[0][2]:
3107
 
                    # This is the root, so the parent is None
3108
 
                    source_parent_id = None
3109
 
                else:
3110
 
                    self.last_source_parent[0] = old_dirname
3111
 
                    self.last_source_parent[1] = source_parent_id
3112
 
            new_dirname = entry[0][0]
3113
 
            if new_dirname == self.last_target_parent[0]:
3114
 
                target_parent_id = self.last_target_parent[1]
3115
 
            else:
3116
 
                try:
3117
 
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
3118
 
                except KeyError:
3119
 
                    # TODO: We don't always need to do the lookup, because the
3120
 
                    #       parent entry will be the same as the source entry.
3121
 
                    target_parent_entry = self.state._get_entry(self.target_index,
3122
 
                                                           path_utf8=new_dirname)
3123
 
                    if target_parent_entry == (None, None):
3124
 
                        raise AssertionError(
3125
 
                            "Could not find target parent in wt: %s\nparent of: %s"
3126
 
                            % (new_dirname, entry))
3127
 
                    target_parent_id = target_parent_entry[0][2]
3128
 
                if target_parent_id == entry[0][2]:
3129
 
                    # This is the root, so the parent is None
3130
 
                    target_parent_id = None
3131
 
                else:
3132
 
                    self.last_target_parent[0] = new_dirname
3133
 
                    self.last_target_parent[1] = target_parent_id
3134
 
 
3135
 
            source_exec = source_details[3]
3136
 
            if (self.include_unchanged
3137
 
                or content_change
3138
 
                or source_parent_id != target_parent_id
3139
 
                or old_basename != entry[0][1]
3140
 
                or source_exec != target_exec
3141
 
                ):
3142
 
                if old_path is None:
3143
 
                    old_path = path = pathjoin(old_dirname, old_basename)
3144
 
                    old_path_u = self.utf8_decode(old_path)[0]
3145
 
                    path_u = old_path_u
3146
 
                else:
3147
 
                    old_path_u = self.utf8_decode(old_path)[0]
3148
 
                    if old_path == path:
3149
 
                        path_u = old_path_u
3150
 
                    else:
3151
 
                        path_u = self.utf8_decode(path)[0]
3152
 
                source_kind = DirState._minikind_to_kind[source_minikind]
3153
 
                return (entry[0][2],
3154
 
                       (old_path_u, path_u),
3155
 
                       content_change,
3156
 
                       (True, True),
3157
 
                       (source_parent_id, target_parent_id),
3158
 
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3159
 
                       (source_kind, target_kind),
3160
 
                       (source_exec, target_exec))
3161
 
            else:
3162
 
                return self.uninteresting
3163
 
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3164
 
            # looks like a new file
3165
 
            path = pathjoin(entry[0][0], entry[0][1])
3166
 
            # parent id is the entry for the path in the target tree
3167
 
            # TODO: these are the same for an entire directory: cache em.
3168
 
            parent_id = self.state._get_entry(self.target_index,
3169
 
                                         path_utf8=entry[0][0])[0][2]
3170
 
            if parent_id == entry[0][2]:
3171
 
                parent_id = None
3172
 
            if path_info is not None:
3173
 
                # Present on disk:
3174
 
                if self.use_filesystem_for_exec:
3175
 
                    # We need S_ISREG here, because we aren't sure if this
3176
 
                    # is a file or not.
3177
 
                    target_exec = bool(
3178
 
                        stat.S_ISREG(path_info[3].st_mode)
3179
 
                        and stat.S_IEXEC & path_info[3].st_mode)
3180
 
                else:
3181
 
                    target_exec = target_details[3]
3182
 
                return (entry[0][2],
3183
 
                       (None, self.utf8_decode(path)[0]),
3184
 
                       True,
3185
 
                       (False, True),
3186
 
                       (None, parent_id),
3187
 
                       (None, self.utf8_decode(entry[0][1])[0]),
3188
 
                       (None, path_info[2]),
3189
 
                       (None, target_exec))
3190
 
            else:
3191
 
                # Its a missing file, report it as such.
3192
 
                return (entry[0][2],
3193
 
                       (None, self.utf8_decode(path)[0]),
3194
 
                       False,
3195
 
                       (False, True),
3196
 
                       (None, parent_id),
3197
 
                       (None, self.utf8_decode(entry[0][1])[0]),
3198
 
                       (None, None),
3199
 
                       (None, False))
3200
 
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3201
 
            # unversioned, possibly, or possibly not deleted: we dont care.
3202
 
            # if its still on disk, *and* theres no other entry at this
3203
 
            # path [we dont know this in this routine at the moment -
3204
 
            # perhaps we should change this - then it would be an unknown.
3205
 
            old_path = pathjoin(entry[0][0], entry[0][1])
3206
 
            # parent id is the entry for the path in the target tree
3207
 
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
3208
 
            if parent_id == entry[0][2]:
3209
 
                parent_id = None
3210
 
            return (entry[0][2],
3211
 
                   (self.utf8_decode(old_path)[0], None),
3212
 
                   True,
3213
 
                   (True, False),
3214
 
                   (parent_id, None),
3215
 
                   (self.utf8_decode(entry[0][1])[0], None),
3216
 
                   (DirState._minikind_to_kind[source_minikind], None),
3217
 
                   (source_details[3], None))
3218
 
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3219
 
            # a rename; could be a true rename, or a rename inherited from
3220
 
            # a renamed parent. TODO: handle this efficiently. Its not
3221
 
            # common case to rename dirs though, so a correct but slow
3222
 
            # implementation will do.
3223
 
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
3224
 
                self.search_specific_files.add(target_details[1])
3225
 
        elif source_minikind in 'ra' and target_minikind in 'ra':
3226
 
            # neither of the selected trees contain this file,
3227
 
            # so skip over it. This is not currently directly tested, but
3228
 
            # is indirectly via test_too_much.TestCommands.test_conflicts.
3229
 
            pass
3230
 
        else:
3231
 
            raise AssertionError("don't know how to compare "
3232
 
                "source_minikind=%r, target_minikind=%r"
3233
 
                % (source_minikind, target_minikind))
3234
 
            ## import pdb;pdb.set_trace()
3235
 
        return None
3236
 
 
3237
 
    def __iter__(self):
3238
 
        return self
3239
 
 
3240
 
    def iter_changes(self):
3241
 
        """Iterate over the changes."""
3242
 
        utf8_decode = cache_utf8._utf8_decode
3243
 
        _cmp_by_dirs = cmp_by_dirs
3244
 
        _process_entry = self._process_entry
3245
 
        uninteresting = self.uninteresting
3246
 
        search_specific_files = self.search_specific_files
3247
 
        searched_specific_files = self.searched_specific_files
3248
 
        splitpath = osutils.splitpath
3249
 
        # sketch:
3250
 
        # compare source_index and target_index at or under each element of search_specific_files.
3251
 
        # follow the following comparison table. Note that we only want to do diff operations when
3252
 
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo
3253
 
        # for the target.
3254
 
        # cases:
3255
 
        #
3256
 
        # Source | Target | disk | action
3257
 
        #   r    | fdlt   |      | add source to search, add id path move and perform
3258
 
        #        |        |      | diff check on source-target
3259
 
        #   r    | fdlt   |  a   | dangling file that was present in the basis.
3260
 
        #        |        |      | ???
3261
 
        #   r    |  a     |      | add source to search
3262
 
        #   r    |  a     |  a   |
3263
 
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
3264
 
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
3265
 
        #   a    | fdlt   |      | add new id
3266
 
        #   a    | fdlt   |  a   | dangling locally added file, skip
3267
 
        #   a    |  a     |      | not present in either tree, skip
3268
 
        #   a    |  a     |  a   | not present in any tree, skip
3269
 
        #   a    |  r     |      | not present in either tree at this path, skip as it
3270
 
        #        |        |      | may not be selected by the users list of paths.
3271
 
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
3272
 
        #        |        |      | may not be selected by the users list of paths.
3273
 
        #  fdlt  | fdlt   |      | content in both: diff them
3274
 
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
3275
 
        #  fdlt  |  a     |      | unversioned: output deleted id for now
3276
 
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
3277
 
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
3278
 
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
3279
 
        #        |        |      | this id at the other path.
3280
 
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
3281
 
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
3282
 
        #        |        |      | this id at the other path.
3283
 
 
3284
 
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
3285
 
        #       keeping a cache of directories that we have seen.
3286
 
 
3287
 
        while search_specific_files:
3288
 
            # TODO: the pending list should be lexically sorted?  the
3289
 
            # interface doesn't require it.
3290
 
            current_root = search_specific_files.pop()
3291
 
            current_root_unicode = current_root.decode('utf8')
3292
 
            searched_specific_files.add(current_root)
3293
 
            # process the entries for this containing directory: the rest will be
3294
 
            # found by their parents recursively.
3295
 
            root_entries = self.state._entries_for_path(current_root)
3296
 
            root_abspath = self.tree.abspath(current_root_unicode)
3297
 
            try:
3298
 
                root_stat = os.lstat(root_abspath)
3299
 
            except OSError, e:
3300
 
                if e.errno == errno.ENOENT:
3301
 
                    # the path does not exist: let _process_entry know that.
3302
 
                    root_dir_info = None
3303
 
                else:
3304
 
                    # some other random error: hand it up.
3305
 
                    raise
3306
 
            else:
3307
 
                root_dir_info = ('', current_root,
3308
 
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
3309
 
                    root_abspath)
3310
 
                if root_dir_info[2] == 'directory':
3311
 
                    if self.tree._directory_is_tree_reference(
3312
 
                        current_root.decode('utf8')):
3313
 
                        root_dir_info = root_dir_info[:2] + \
3314
 
                            ('tree-reference',) + root_dir_info[3:]
3315
 
 
3316
 
            if not root_entries and not root_dir_info:
3317
 
                # this specified path is not present at all, skip it.
3318
 
                continue
3319
 
            path_handled = False
3320
 
            for entry in root_entries:
3321
 
                result = _process_entry(entry, root_dir_info)
3322
 
                if result is not None:
3323
 
                    path_handled = True
3324
 
                    if result is not uninteresting:
3325
 
                        yield result
3326
 
            if self.want_unversioned and not path_handled and root_dir_info:
3327
 
                new_executable = bool(
3328
 
                    stat.S_ISREG(root_dir_info[3].st_mode)
3329
 
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
3330
 
                yield (None,
3331
 
                       (None, current_root_unicode),
3332
 
                       True,
3333
 
                       (False, False),
3334
 
                       (None, None),
3335
 
                       (None, splitpath(current_root_unicode)[-1]),
3336
 
                       (None, root_dir_info[2]),
3337
 
                       (None, new_executable)
3338
 
                      )
3339
 
            initial_key = (current_root, '', '')
3340
 
            block_index, _ = self.state._find_block_index_from_key(initial_key)
3341
 
            if block_index == 0:
3342
 
                # we have processed the total root already, but because the
3343
 
                # initial key matched it we should skip it here.
3344
 
                block_index +=1
3345
 
            if root_dir_info and root_dir_info[2] == 'tree-reference':
3346
 
                current_dir_info = None
3347
 
            else:
3348
 
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
3349
 
                try:
3350
 
                    current_dir_info = dir_iterator.next()
3351
 
                except OSError, e:
3352
 
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
3353
 
                    # python 2.5 has e.errno == EINVAL,
3354
 
                    #            and e.winerror == ERROR_DIRECTORY
3355
 
                    e_winerror = getattr(e, 'winerror', None)
3356
 
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
3357
 
                    # there may be directories in the inventory even though
3358
 
                    # this path is not a file on disk: so mark it as end of
3359
 
                    # iterator
3360
 
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
3361
 
                        current_dir_info = None
3362
 
                    elif (sys.platform == 'win32'
3363
 
                          and (e.errno in win_errors
3364
 
                               or e_winerror in win_errors)):
3365
 
                        current_dir_info = None
3366
 
                    else:
3367
 
                        raise
3368
 
                else:
3369
 
                    if current_dir_info[0][0] == '':
3370
 
                        # remove .bzr from iteration
3371
 
                        bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
3372
 
                        if current_dir_info[1][bzr_index][0] != '.bzr':
3373
 
                            raise AssertionError()
3374
 
                        del current_dir_info[1][bzr_index]
3375
 
            # walk until both the directory listing and the versioned metadata
3376
 
            # are exhausted.
3377
 
            if (block_index < len(self.state._dirblocks) and
3378
 
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
3379
 
                current_block = self.state._dirblocks[block_index]
3380
 
            else:
3381
 
                current_block = None
3382
 
            while (current_dir_info is not None or
3383
 
                   current_block is not None):
3384
 
                if (current_dir_info and current_block
3385
 
                    and current_dir_info[0][0] != current_block[0]):
3386
 
                    if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
3387
 
                        # filesystem data refers to paths not covered by the dirblock.
3388
 
                        # this has two possibilities:
3389
 
                        # A) it is versioned but empty, so there is no block for it
3390
 
                        # B) it is not versioned.
3391
 
 
3392
 
                        # if (A) then we need to recurse into it to check for
3393
 
                        # new unknown files or directories.
3394
 
                        # if (B) then we should ignore it, because we don't
3395
 
                        # recurse into unknown directories.
3396
 
                        path_index = 0
3397
 
                        while path_index < len(current_dir_info[1]):
3398
 
                                current_path_info = current_dir_info[1][path_index]
3399
 
                                if self.want_unversioned:
3400
 
                                    if current_path_info[2] == 'directory':
3401
 
                                        if self.tree._directory_is_tree_reference(
3402
 
                                            current_path_info[0].decode('utf8')):
3403
 
                                            current_path_info = current_path_info[:2] + \
3404
 
                                                ('tree-reference',) + current_path_info[3:]
3405
 
                                    new_executable = bool(
3406
 
                                        stat.S_ISREG(current_path_info[3].st_mode)
3407
 
                                        and stat.S_IEXEC & current_path_info[3].st_mode)
3408
 
                                    yield (None,
3409
 
                                        (None, utf8_decode(current_path_info[0])[0]),
3410
 
                                        True,
3411
 
                                        (False, False),
3412
 
                                        (None, None),
3413
 
                                        (None, utf8_decode(current_path_info[1])[0]),
3414
 
                                        (None, current_path_info[2]),
3415
 
                                        (None, new_executable))
3416
 
                                # dont descend into this unversioned path if it is
3417
 
                                # a dir
3418
 
                                if current_path_info[2] in ('directory',
3419
 
                                                            'tree-reference'):
3420
 
                                    del current_dir_info[1][path_index]
3421
 
                                    path_index -= 1
3422
 
                                path_index += 1
3423
 
 
3424
 
                        # This dir info has been handled, go to the next
3425
 
                        try:
3426
 
                            current_dir_info = dir_iterator.next()
3427
 
                        except StopIteration:
3428
 
                            current_dir_info = None
3429
 
                    else:
3430
 
                        # We have a dirblock entry for this location, but there
3431
 
                        # is no filesystem path for this. This is most likely
3432
 
                        # because a directory was removed from the disk.
3433
 
                        # We don't have to report the missing directory,
3434
 
                        # because that should have already been handled, but we
3435
 
                        # need to handle all of the files that are contained
3436
 
                        # within.
3437
 
                        for current_entry in current_block[1]:
3438
 
                            # entry referring to file not present on disk.
3439
 
                            # advance the entry only, after processing.
3440
 
                            result = _process_entry(current_entry, None)
3441
 
                            if result is not None:
3442
 
                                if result is not uninteresting:
3443
 
                                    yield result
3444
 
                        block_index +=1
3445
 
                        if (block_index < len(self.state._dirblocks) and
3446
 
                            osutils.is_inside(current_root,
3447
 
                                              self.state._dirblocks[block_index][0])):
3448
 
                            current_block = self.state._dirblocks[block_index]
3449
 
                        else:
3450
 
                            current_block = None
3451
 
                    continue
3452
 
                entry_index = 0
3453
 
                if current_block and entry_index < len(current_block[1]):
3454
 
                    current_entry = current_block[1][entry_index]
3455
 
                else:
3456
 
                    current_entry = None
3457
 
                advance_entry = True
3458
 
                path_index = 0
3459
 
                if current_dir_info and path_index < len(current_dir_info[1]):
3460
 
                    current_path_info = current_dir_info[1][path_index]
3461
 
                    if current_path_info[2] == 'directory':
3462
 
                        if self.tree._directory_is_tree_reference(
3463
 
                            current_path_info[0].decode('utf8')):
3464
 
                            current_path_info = current_path_info[:2] + \
3465
 
                                ('tree-reference',) + current_path_info[3:]
3466
 
                else:
3467
 
                    current_path_info = None
3468
 
                advance_path = True
3469
 
                path_handled = False
3470
 
                while (current_entry is not None or
3471
 
                    current_path_info is not None):
3472
 
                    if current_entry is None:
3473
 
                        # the check for path_handled when the path is advanced
3474
 
                        # will yield this path if needed.
3475
 
                        pass
3476
 
                    elif current_path_info is None:
3477
 
                        # no path is fine: the per entry code will handle it.
3478
 
                        result = _process_entry(current_entry, current_path_info)
3479
 
                        if result is not None:
3480
 
                            if result is not uninteresting:
3481
 
                                yield result
3482
 
                    elif (current_entry[0][1] != current_path_info[1]
3483
 
                          or current_entry[1][self.target_index][0] in 'ar'):
3484
 
                        # The current path on disk doesn't match the dirblock
3485
 
                        # record. Either the dirblock is marked as absent, or
3486
 
                        # the file on disk is not present at all in the
3487
 
                        # dirblock. Either way, report about the dirblock
3488
 
                        # entry, and let other code handle the filesystem one.
3489
 
 
3490
 
                        # Compare the basename for these files to determine
3491
 
                        # which comes first
3492
 
                        if current_path_info[1] < current_entry[0][1]:
3493
 
                            # extra file on disk: pass for now, but only
3494
 
                            # increment the path, not the entry
3495
 
                            advance_entry = False
3496
 
                        else:
3497
 
                            # entry referring to file not present on disk.
3498
 
                            # advance the entry only, after processing.
3499
 
                            result = _process_entry(current_entry, None)
3500
 
                            if result is not None:
3501
 
                                if result is not uninteresting:
3502
 
                                    yield result
3503
 
                            advance_path = False
3504
 
                    else:
3505
 
                        result = _process_entry(current_entry, current_path_info)
3506
 
                        if result is not None:
3507
 
                            path_handled = True
3508
 
                            if result is not uninteresting:
3509
 
                                yield result
3510
 
                    if advance_entry and current_entry is not None:
3511
 
                        entry_index += 1
3512
 
                        if entry_index < len(current_block[1]):
3513
 
                            current_entry = current_block[1][entry_index]
3514
 
                        else:
3515
 
                            current_entry = None
3516
 
                    else:
3517
 
                        advance_entry = True # reset the advance flaga
3518
 
                    if advance_path and current_path_info is not None:
3519
 
                        if not path_handled:
3520
 
                            # unversioned in all regards
3521
 
                            if self.want_unversioned:
3522
 
                                new_executable = bool(
3523
 
                                    stat.S_ISREG(current_path_info[3].st_mode)
3524
 
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
3525
 
                                try:
3526
 
                                    relpath_unicode = utf8_decode(current_path_info[0])[0]
3527
 
                                except UnicodeDecodeError:
3528
 
                                    raise errors.BadFilenameEncoding(
3529
 
                                        current_path_info[0], osutils._fs_enc)
3530
 
                                yield (None,
3531
 
                                    (None, relpath_unicode),
3532
 
                                    True,
3533
 
                                    (False, False),
3534
 
                                    (None, None),
3535
 
                                    (None, utf8_decode(current_path_info[1])[0]),
3536
 
                                    (None, current_path_info[2]),
3537
 
                                    (None, new_executable))
3538
 
                            # dont descend into this unversioned path if it is
3539
 
                            # a dir
3540
 
                            if current_path_info[2] in ('directory'):
3541
 
                                del current_dir_info[1][path_index]
3542
 
                                path_index -= 1
3543
 
                        # dont descend the disk iterator into any tree
3544
 
                        # paths.
3545
 
                        if current_path_info[2] == 'tree-reference':
3546
 
                            del current_dir_info[1][path_index]
3547
 
                            path_index -= 1
3548
 
                        path_index += 1
3549
 
                        if path_index < len(current_dir_info[1]):
3550
 
                            current_path_info = current_dir_info[1][path_index]
3551
 
                            if current_path_info[2] == 'directory':
3552
 
                                if self.tree._directory_is_tree_reference(
3553
 
                                    current_path_info[0].decode('utf8')):
3554
 
                                    current_path_info = current_path_info[:2] + \
3555
 
                                        ('tree-reference',) + current_path_info[3:]
3556
 
                        else:
3557
 
                            current_path_info = None
3558
 
                        path_handled = False
3559
 
                    else:
3560
 
                        advance_path = True # reset the advance flagg.
3561
 
                if current_block is not None:
3562
 
                    block_index += 1
3563
 
                    if (block_index < len(self.state._dirblocks) and
3564
 
                        osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
3565
 
                        current_block = self.state._dirblocks[block_index]
3566
 
                    else:
3567
 
                        current_block = None
3568
 
                if current_dir_info is not None:
3569
 
                    try:
3570
 
                        current_dir_info = dir_iterator.next()
3571
 
                    except StopIteration:
3572
 
                        current_dir_info = None
3573
 
_process_entry = ProcessEntryPython
3574
 
 
3575
 
 
3576
2286
# Try to load the compiled form if possible
3577
2287
try:
3578
2288
    from bzrlib._dirstate_helpers_c import (
3581
2291
        _bisect_path_left_c as _bisect_path_left,
3582
2292
        _bisect_path_right_c as _bisect_path_right,
3583
2293
        cmp_by_dirs_c as cmp_by_dirs,
3584
 
        ProcessEntryC as _process_entry,
3585
 
        update_entry as update_entry,
3586
2294
        )
3587
2295
except ImportError:
3588
2296
    from bzrlib._dirstate_helpers_py import (