~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006-2011 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""DirState objects record the state of a directory and its bzr metadata.
18
18
 
20
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
21
21
are not - this is done for clarity of reading. All string data is in utf8.
22
22
 
23
 
MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
24
 
NL = "\n";
25
 
NULL = "\0";
26
 
WHOLE_NUMBER = {digit}, digit;
27
 
BOOLEAN = "y" | "n";
28
 
REVISION_ID = a non-empty utf8 string;
29
 
 
30
 
dirstate format = header line, full checksum, row count, parent details,
31
 
 ghost_details, entries;
32
 
header line = "#bazaar dirstate flat format 3", NL;
33
 
full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
34
 
row count = "num_entries: ", WHOLE_NUMBER, NL;
35
 
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
36
 
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
37
 
entries = {entry};
38
 
entry = entry_key, current_entry_details, {parent_entry_details};
39
 
entry_key = dirname,  basename, fileid;
40
 
current_entry_details = common_entry_details, working_entry_details;
41
 
parent_entry_details = common_entry_details, history_entry_details;
42
 
common_entry_details = MINIKIND, fingerprint, size, executable
43
 
working_entry_details = packed_stat
44
 
history_entry_details = REVISION_ID;
45
 
executable = BOOLEAN;
46
 
size = WHOLE_NUMBER;
47
 
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
48
 
 
49
 
Given this definition, the following is useful to know:
50
 
entry (aka row) - all the data for a given key.
51
 
entry[0]: The key (dirname, basename, fileid)
52
 
entry[0][0]: dirname
53
 
entry[0][1]: basename
54
 
entry[0][2]: fileid
55
 
entry[1]: The tree(s) data for this path and id combination.
56
 
entry[1][0]: The current tree
57
 
entry[1][1]: The second tree
58
 
 
59
 
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
60
 
entry[1][0][0]: minikind
61
 
entry[1][0][1]: fingerprint
62
 
entry[1][0][2]: size
63
 
entry[1][0][3]: executable
64
 
entry[1][0][4]: packed_stat
65
 
OR (for non tree-0)
66
 
entry[1][1][4]: revision_id
 
23
::
 
24
 
 
25
    MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
 
26
    NL = "\\n";
 
27
    NULL = "\\0";
 
28
    WHOLE_NUMBER = {digit}, digit;
 
29
    BOOLEAN = "y" | "n";
 
30
    REVISION_ID = a non-empty utf8 string;
 
31
    
 
32
    dirstate format = header line, full checksum, row count, parent details,
 
33
     ghost_details, entries;
 
34
    header line = "#bazaar dirstate flat format 3", NL;
 
35
    full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
 
36
    row count = "num_entries: ", WHOLE_NUMBER, NL;
 
37
    parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
 
38
    ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
 
39
    entries = {entry};
 
40
    entry = entry_key, current_entry_details, {parent_entry_details};
 
41
    entry_key = dirname,  basename, fileid;
 
42
    current_entry_details = common_entry_details, working_entry_details;
 
43
    parent_entry_details = common_entry_details, history_entry_details;
 
44
    common_entry_details = MINIKIND, fingerprint, size, executable
 
45
    working_entry_details = packed_stat
 
46
    history_entry_details = REVISION_ID;
 
47
    executable = BOOLEAN;
 
48
    size = WHOLE_NUMBER;
 
49
    fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
50
 
 
51
Given this definition, the following is useful to know::
 
52
 
 
53
    entry (aka row) - all the data for a given key.
 
54
    entry[0]: The key (dirname, basename, fileid)
 
55
    entry[0][0]: dirname
 
56
    entry[0][1]: basename
 
57
    entry[0][2]: fileid
 
58
    entry[1]: The tree(s) data for this path and id combination.
 
59
    entry[1][0]: The current tree
 
60
    entry[1][1]: The second tree
 
61
 
 
62
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate::
 
63
 
 
64
    entry[1][0][0]: minikind
 
65
    entry[1][0][1]: fingerprint
 
66
    entry[1][0][2]: size
 
67
    entry[1][0][3]: executable
 
68
    entry[1][0][4]: packed_stat
 
69
 
 
70
OR (for non tree-0)::
 
71
 
 
72
    entry[1][1][4]: revision_id
67
73
 
68
74
There may be multiple rows at the root, one per id present in the root, so the
69
 
in memory root row is now:
70
 
self._dirblocks[0] -> ('', [entry ...]),
71
 
and the entries in there are
72
 
entries[0][0]: ''
73
 
entries[0][1]: ''
74
 
entries[0][2]: file_id
75
 
entries[1][0]: The tree data for the current tree for this fileid at /
76
 
etc.
77
 
 
78
 
Kinds:
79
 
'r' is a relocated entry: This path is not present in this tree with this id,
80
 
    but the id can be found at another location. The fingerprint is used to
81
 
    point to the target location.
82
 
'a' is an absent entry: In that tree the id is not present at this path.
83
 
'd' is a directory entry: This path in this tree is a directory with the
84
 
    current file id. There is no fingerprint for directories.
85
 
'f' is a file entry: As for directory, but its a file. The fingerprint is a
86
 
    sha1 value.
87
 
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
88
 
    link target.
89
 
't' is a reference to a nested subtree; the fingerprint is the referenced
90
 
    revision.
 
75
in memory root row is now::
 
76
 
 
77
    self._dirblocks[0] -> ('', [entry ...]),
 
78
 
 
79
and the entries in there are::
 
80
 
 
81
    entries[0][0]: ''
 
82
    entries[0][1]: ''
 
83
    entries[0][2]: file_id
 
84
    entries[1][0]: The tree data for the current tree for this fileid at /
 
85
    etc.
 
86
 
 
87
Kinds::
 
88
 
 
89
    'r' is a relocated entry: This path is not present in this tree with this
 
90
        id, but the id can be found at another location. The fingerprint is
 
91
        used to point to the target location.
 
92
    'a' is an absent entry: In that tree the id is not present at this path.
 
93
    'd' is a directory entry: This path in this tree is a directory with the
 
94
        current file id. There is no fingerprint for directories.
 
95
    'f' is a file entry: As for directory, but it's a file. The fingerprint is
 
96
        the sha1 value of the file's canonical form, i.e. after any read
 
97
        filters have been applied to the convenience form stored in the working
 
98
        tree.
 
99
    'l' is a symlink entry: As for directory, but a symlink. The fingerprint is
 
100
        the link target.
 
101
    't' is a reference to a nested subtree; the fingerprint is the referenced
 
102
        revision.
91
103
 
92
104
Ordering:
93
105
 
94
 
The entries on disk and in memory are ordered according to the following keys:
 
106
The entries on disk and in memory are ordered according to the following keys::
95
107
 
96
108
    directory, as a list of components
97
109
    filename
98
110
    file-id
99
111
 
100
112
--- Format 1 had the following different definition: ---
101
 
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
102
 
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target, 
103
 
    {PARENT ROW}
104
 
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
105
 
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
106
 
    SHA1
 
113
 
 
114
::
 
115
 
 
116
    rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
117
        WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
118
        {PARENT ROW}
 
119
    PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
120
        basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
121
        SHA1
107
122
 
108
123
PARENT ROW's are emitted for every parent that is not in the ghosts details
109
124
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
130
145
operations for the less common but still occurs a lot status/diff/commit
131
146
on specific files). Operations on specific files involve a scan for all
132
147
the children of a path, *in every involved tree*, which the current
133
 
format did not accommodate. 
 
148
format did not accommodate.
134
149
----
135
150
 
136
151
Design priorities:
137
 
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
138
 
 2) fall back current object model as needed.
139
 
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
 
152
 1. Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
153
 2. fall back current object model as needed.
 
154
 3. scale usably to the largest trees known today - say 50K entries. (mozilla
140
155
    is an example of this)
141
156
 
142
157
 
143
158
Locking:
 
159
 
144
160
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
145
161
 been modified, but will require that we flush/ignore cached stat-hit data
146
162
 because we won't want to restat all files on disk just because a lock was
147
163
 acquired, yet we cannot trust the data after the previous lock was released.
148
164
 
149
 
Memory representation:
 
165
Memory representation::
 
166
 
150
167
 vector of all directories, and vector of the childen ?
151
 
   i.e. 
152
 
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
 
168
   i.e.
 
169
     root_entrie = (direntry for root, [parent_direntries_for_root]),
153
170
     dirblocks = [
154
171
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
155
172
     ('dir', ['achild', 'cchild', 'echild'])
158
175
    - in-order for serialisation - this is 'dirblock' grouping.
159
176
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
160
177
      insert 10K elements from scratch does not generates O(N^2) memoves of 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 
 
178
      single vector, rather each individual, which tends to be limited to a
 
179
      manageable number. Will scale badly on trees with 10K entries in a
163
180
      single directory. compare with Inventory.InventoryDirectory which has
164
181
      a dictionary for the children. No bisect capability, can only probe for
165
182
      exact matches, or grab all elements and sort.
166
183
    - What's 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 
 
184
      we should have a net win regardless of optimality. So we are going to
168
185
      go with what seems reasonable.
 
186
 
169
187
open questions:
170
188
 
171
189
Maybe we should do a test profile of the core structure - 10K simulated
186
204
the file on disk, and then immediately discard, the overhead of object creation
187
205
becomes a significant cost.
188
206
 
189
 
Figures: Creating a tuple from from 3 elements was profiled at 0.0625
 
207
Figures: Creating a tuple from 3 elements was profiled at 0.0625
190
208
microseconds, whereas creating a object which is subclassed from tuple was
191
209
0.500 microseconds, and creating an object with 3 elements and slots was 3
192
210
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
203
221
import bisect
204
222
import binascii
205
223
import errno
 
224
import operator
206
225
import os
207
226
from stat import S_IEXEC
208
227
import stat
213
232
 
214
233
from bzrlib import (
215
234
    cache_utf8,
 
235
    config,
216
236
    debug,
217
237
    errors,
218
238
    inventory,
219
239
    lock,
220
240
    osutils,
 
241
    static_tuple,
221
242
    trace,
 
243
    urlutils,
222
244
    )
223
245
 
224
246
 
262
284
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
263
285
 
264
286
 
 
287
def _unpack_stat(packed_stat):
 
288
    """Turn a packed_stat back into the stat fields.
 
289
 
 
290
    This is meant as a debugging tool, should not be used in real code.
 
291
    """
 
292
    (st_size, st_mtime, st_ctime, st_dev, st_ino,
 
293
     st_mode) = struct.unpack('>LLLLLL', binascii.a2b_base64(packed_stat))
 
294
    return dict(st_size=st_size, st_mtime=st_mtime, st_ctime=st_ctime,
 
295
                st_dev=st_dev, st_ino=st_ino, st_mode=st_mode)
 
296
 
 
297
 
 
298
class SHA1Provider(object):
 
299
    """An interface for getting sha1s of a file."""
 
300
 
 
301
    def sha1(self, abspath):
 
302
        """Return the sha1 of a file given its absolute path.
 
303
 
 
304
        :param abspath:  May be a filesystem encoded absolute path
 
305
             or a unicode path.
 
306
        """
 
307
        raise NotImplementedError(self.sha1)
 
308
 
 
309
    def stat_and_sha1(self, abspath):
 
310
        """Return the stat and sha1 of a file given its absolute path.
 
311
        
 
312
        :param abspath:  May be a filesystem encoded absolute path
 
313
             or a unicode path.
 
314
 
 
315
        Note: the stat should be the stat of the physical file
 
316
        while the sha may be the sha of its canonical content.
 
317
        """
 
318
        raise NotImplementedError(self.stat_and_sha1)
 
319
 
 
320
 
 
321
class DefaultSHA1Provider(SHA1Provider):
 
322
    """A SHA1Provider that reads directly from the filesystem."""
 
323
 
 
324
    def sha1(self, abspath):
 
325
        """Return the sha1 of a file given its absolute path."""
 
326
        return osutils.sha_file_by_name(abspath)
 
327
 
 
328
    def stat_and_sha1(self, abspath):
 
329
        """Return the stat and sha1 of a file given its absolute path."""
 
330
        file_obj = file(abspath, 'rb')
 
331
        try:
 
332
            statvalue = os.fstat(file_obj.fileno())
 
333
            sha1 = osutils.sha_file(file_obj)
 
334
        finally:
 
335
            file_obj.close()
 
336
        return statvalue, sha1
 
337
 
 
338
 
265
339
class DirState(object):
266
340
    """Record directory and metadata state for fast access.
267
341
 
311
385
    NOT_IN_MEMORY = 0
312
386
    IN_MEMORY_UNMODIFIED = 1
313
387
    IN_MEMORY_MODIFIED = 2
 
388
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
314
389
 
315
390
    # A pack_stat (the x's) that is just noise and will never match the output
316
391
    # of base64 encode.
317
392
    NULLSTAT = 'x' * 32
318
 
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
393
    NULL_PARENT_DETAILS = static_tuple.StaticTuple('a', '', 0, False, '')
319
394
 
320
395
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
321
396
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
322
397
 
323
 
    def __init__(self, path):
 
398
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
324
399
        """Create a  DirState object.
325
400
 
326
401
        :param path: The path at which the dirstate file on disk should live.
 
402
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
403
        :param worth_saving_limit: when the exact number of hash changed
 
404
            entries is known, only bother saving the dirstate if more than
 
405
            this count of entries have changed.
 
406
            -1 means never save hash changes, 0 means always save hash changes.
327
407
        """
328
408
        # _header_state and _dirblock_state represent the current state
329
409
        # of the dirstate metadata and the per-row data respectiely.
331
411
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
332
412
        #   is the same as is on disk
333
413
        # IN_MEMORY_MODIFIED indicates that we have a modified version
334
 
        #   of what is on disk. 
 
414
        #   of what is on disk.
335
415
        # In future we will add more granularity, for instance _dirblock_state
336
416
        # will probably support partially-in-memory as a separate variable,
337
417
        # allowing for partially-in-memory unmodified and partially-in-memory
338
418
        # modified states.
339
419
        self._header_state = DirState.NOT_IN_MEMORY
340
420
        self._dirblock_state = DirState.NOT_IN_MEMORY
341
 
        # If true, an error has been detected while updating the dirstate, and 
 
421
        # If true, an error has been detected while updating the dirstate, and
342
422
        # for safety we're not going to commit to disk.
343
423
        self._changes_aborted = False
344
424
        self._dirblocks = []
355
435
        self._cutoff_time = None
356
436
        self._split_path_cache = {}
357
437
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
 
438
        self._sha1_provider = sha1_provider
358
439
        if 'hashcache' in debug.debug_flags:
359
440
            self._sha1_file = self._sha1_file_and_mutter
360
441
        else:
361
 
            self._sha1_file = osutils.sha_file_by_name
 
442
            self._sha1_file = self._sha1_provider.sha1
362
443
        # These two attributes provide a simple cache for lookups into the
363
444
        # dirstate in-memory vectors. By probing respectively for the last
364
445
        # block, and for the next entry, we save nearly 2 bisections per path
365
446
        # during commit.
366
447
        self._last_block_index = None
367
448
        self._last_entry_index = None
 
449
        # The set of known hash changes
 
450
        self._known_hash_changes = set()
 
451
        # How many hash changed entries can we have without saving
 
452
        self._worth_saving_limit = worth_saving_limit
 
453
        self._config_stack = config.LocationStack(urlutils.local_path_to_url(
 
454
            path))
368
455
 
369
456
    def __repr__(self):
370
457
        return "%s(%r)" % \
371
458
            (self.__class__.__name__, self._filename)
372
459
 
 
460
    def _mark_modified(self, hash_changed_entries=None, header_modified=False):
 
461
        """Mark this dirstate as modified.
 
462
 
 
463
        :param hash_changed_entries: if non-None, mark just these entries as
 
464
            having their hash modified.
 
465
        :param header_modified: mark the header modified as well, not just the
 
466
            dirblocks.
 
467
        """
 
468
        #trace.mutter_callsite(3, "modified hash entries: %s", hash_changed_entries)
 
469
        if hash_changed_entries:
 
470
            self._known_hash_changes.update([e[0] for e in hash_changed_entries])
 
471
            if self._dirblock_state in (DirState.NOT_IN_MEMORY,
 
472
                                        DirState.IN_MEMORY_UNMODIFIED):
 
473
                # If the dirstate is already marked a IN_MEMORY_MODIFIED, then
 
474
                # that takes precedence.
 
475
                self._dirblock_state = DirState.IN_MEMORY_HASH_MODIFIED
 
476
        else:
 
477
            # TODO: Since we now have a IN_MEMORY_HASH_MODIFIED state, we
 
478
            #       should fail noisily if someone tries to set
 
479
            #       IN_MEMORY_MODIFIED but we don't have a write-lock!
 
480
            # We don't know exactly what changed so disable smart saving
 
481
            self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
482
        if header_modified:
 
483
            self._header_state = DirState.IN_MEMORY_MODIFIED
 
484
 
 
485
    def _mark_unmodified(self):
 
486
        """Mark this dirstate as unmodified."""
 
487
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
488
        self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
489
        self._known_hash_changes = set()
 
490
 
373
491
    def add(self, path, file_id, kind, stat, fingerprint):
374
492
        """Add a path to be tracked.
375
493
 
376
494
        :param path: The path within the dirstate - '' is the root, 'foo' is the
377
 
            path foo within the root, 'foo/bar' is the path bar within foo 
 
495
            path foo within the root, 'foo/bar' is the path bar within foo
378
496
            within the root.
379
497
        :param file_id: The file id of the path being added.
380
 
        :param kind: The kind of the path, as a string like 'file', 
 
498
        :param kind: The kind of the path, as a string like 'file',
381
499
            'directory', etc.
382
500
        :param stat: The output of os.lstat for the path.
383
 
        :param fingerprint: The sha value of the file,
 
501
        :param fingerprint: The sha value of the file's canonical form (i.e.
 
502
            after any read filters have been applied),
384
503
            or the target of a symlink,
385
504
            or the referenced revision id for tree-references,
386
505
            or '' for directories.
387
506
        """
388
507
        # adding a file:
389
 
        # find the block its in. 
 
508
        # find the block its in.
390
509
        # find the location in the block.
391
510
        # check its not there
392
511
        # add it.
405
524
        # in the parent, or according to the special treatment for the root
406
525
        if basename == '.' or basename == '..':
407
526
            raise errors.InvalidEntryName(path)
408
 
        # now that we've normalised, we need the correct utf8 path and 
 
527
        # now that we've normalised, we need the correct utf8 path and
409
528
        # dirname and basename elements. This single encode and split should be
410
529
        # faster than three separate encodes.
411
530
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
439
558
            # check the path is not in the tree
440
559
            block = self._dirblocks[block_index][1]
441
560
            entry_index, _ = self._find_entry_index(first_key, block)
442
 
            while (entry_index < len(block) and 
 
561
            while (entry_index < len(block) and
443
562
                block[entry_index][0][0:2] == first_key[0:2]):
444
563
                if block[entry_index][1][0][0] not in 'ar':
445
564
                    # this path is in the dirstate in the current tree.
500
619
        if kind == 'directory':
501
620
           # insert a new dirblock
502
621
           self._ensure_block(block_index, entry_index, utf8path)
503
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
622
        self._mark_modified()
504
623
        if self._id_index:
505
 
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
 
624
            self._add_to_id_index(self._id_index, entry_key)
506
625
 
507
626
    def _bisect(self, paths):
508
627
        """Bisect through the disk structure for specific rows.
935
1054
 
936
1055
    def _discard_merge_parents(self):
937
1056
        """Discard any parents trees beyond the first.
938
 
        
 
1057
 
939
1058
        Note that if this fails the dirstate is corrupted.
940
1059
 
941
1060
        After this function returns the dirstate contains 2 trees, neither of
972
1091
 
973
1092
        self._ghosts = []
974
1093
        self._parents = [parents[0]]
975
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
976
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1094
        self._mark_modified(header_modified=True)
977
1095
 
978
1096
    def _empty_parent_info(self):
979
1097
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1011
1129
                raise AssertionError("bad dirname %r" % dirname)
1012
1130
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
1013
1131
        if not present:
1014
 
            ## In future, when doing partial parsing, this should load and 
 
1132
            ## In future, when doing partial parsing, this should load and
1015
1133
            # populate the entire block.
1016
1134
            self._dirblocks.insert(block_index, (dirname, []))
1017
1135
        return block_index
1029
1147
        if new_entries[0][0][0:2] != ('', ''):
1030
1148
            raise AssertionError(
1031
1149
                "Missing root row %r" % (new_entries[0][0],))
1032
 
        # The two blocks here are deliberate: the root block and the 
 
1150
        # The two blocks here are deliberate: the root block and the
1033
1151
        # contents-of-root block.
1034
1152
        self._dirblocks = [('', []), ('', [])]
1035
1153
        current_block = self._dirblocks[0][1]
1108
1226
    def _fields_per_entry(self):
1109
1227
        """How many null separated fields should be in each entry row.
1110
1228
 
1111
 
        Each line now has an extra '\n' field which is not used
 
1229
        Each line now has an extra '\\n' field which is not used
1112
1230
        so we just skip over it
1113
 
        entry size:
 
1231
 
 
1232
        entry size::
1114
1233
            3 fields for the key
1115
1234
            + number of fields per tree_data (5) * tree count
1116
1235
            + newline
1159
1278
        # one to use it. we use _right here because there are two
1160
1279
        # '' blocks - the root, and the contents of root
1161
1280
        # we always have a minimum of 2 in self._dirblocks: root and
1162
 
        # root-contents, and for '', we get 2 back, so this is 
 
1281
        # root-contents, and for '', we get 2 back, so this is
1163
1282
        # simple and correct:
1164
1283
        present = (block_index < len(self._dirblocks) and
1165
1284
            self._dirblocks[block_index][0] == key[0])
1194
1313
        return entry_index, present
1195
1314
 
1196
1315
    @staticmethod
1197
 
    def from_tree(tree, dir_state_filename):
 
1316
    def from_tree(tree, dir_state_filename, sha1_provider=None):
1198
1317
        """Create a dirstate from a bzr Tree.
1199
1318
 
1200
1319
        :param tree: The tree which should provide parent information and
1201
1320
            inventory ids.
 
1321
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
1322
            If None, a DefaultSHA1Provider is used.
1202
1323
        :return: a DirState object which is currently locked for writing.
1203
1324
            (it was locked by DirState.initialize)
1204
1325
        """
1205
 
        result = DirState.initialize(dir_state_filename)
 
1326
        result = DirState.initialize(dir_state_filename,
 
1327
            sha1_provider=sha1_provider)
1206
1328
        try:
1207
1329
            tree.lock_read()
1208
1330
            try:
1226
1348
            raise
1227
1349
        return result
1228
1350
 
 
1351
    def _check_delta_is_valid(self, delta):
 
1352
        return list(inventory._check_delta_unique_ids(
 
1353
                    inventory._check_delta_unique_old_paths(
 
1354
                    inventory._check_delta_unique_new_paths(
 
1355
                    inventory._check_delta_ids_match_entry(
 
1356
                    inventory._check_delta_ids_are_valid(
 
1357
                    inventory._check_delta_new_path_entry_both_or_None(delta)))))))
 
1358
 
1229
1359
    def update_by_delta(self, delta):
1230
1360
        """Apply an inventory delta to the dirstate for tree 0
1231
1361
 
 
1362
        This is the workhorse for apply_inventory_delta in dirstate based
 
1363
        trees.
 
1364
 
1232
1365
        :param delta: An inventory delta.  See Inventory.apply_delta for
1233
1366
            details.
1234
1367
        """
1235
1368
        self._read_dirblocks_if_needed()
 
1369
        encode = cache_utf8.encode
1236
1370
        insertions = {}
1237
1371
        removals = {}
1238
 
        for old_path, new_path, file_id, inv_entry in sorted(delta, reverse=True):
 
1372
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1373
        # items or items placed under files/links/tree-references. We get
 
1374
        # references from every item in the delta that is not a deletion and
 
1375
        # is not itself the root.
 
1376
        parents = set()
 
1377
        # Added ids must not be in the dirstate already. This set holds those
 
1378
        # ids.
 
1379
        new_ids = set()
 
1380
        # This loop transforms the delta to single atomic operations that can
 
1381
        # be executed and validated.
 
1382
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
 
1383
        for old_path, new_path, file_id, inv_entry in delta:
1239
1384
            if (file_id in insertions) or (file_id in removals):
1240
 
                raise AssertionError("repeated file id in delta %r" % (file_id,))
 
1385
                self._raise_invalid(old_path or new_path, file_id,
 
1386
                    "repeated file_id")
1241
1387
            if old_path is not None:
1242
1388
                old_path = old_path.encode('utf-8')
1243
1389
                removals[file_id] = old_path
 
1390
            else:
 
1391
                new_ids.add(file_id)
1244
1392
            if new_path is not None:
 
1393
                if inv_entry is None:
 
1394
                    self._raise_invalid(new_path, file_id,
 
1395
                        "new_path with no entry")
1245
1396
                new_path = new_path.encode('utf-8')
1246
 
                dirname, basename = osutils.split(new_path)
1247
 
                key = (dirname, basename, file_id)
 
1397
                dirname_utf8, basename = osutils.split(new_path)
 
1398
                if basename:
 
1399
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1400
                key = (dirname_utf8, basename, file_id)
1248
1401
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1249
1402
                if minikind == 't':
1250
 
                    fingerprint = inv_entry.reference_revision
 
1403
                    fingerprint = inv_entry.reference_revision or ''
1251
1404
                else:
1252
1405
                    fingerprint = ''
1253
1406
                insertions[file_id] = (key, minikind, inv_entry.executable,
1262
1415
                    minikind = child[1][0][0]
1263
1416
                    fingerprint = child[1][0][4]
1264
1417
                    executable = child[1][0][3]
1265
 
                    old_child_path = osutils.pathjoin(child[0][0],
1266
 
                                                      child[0][1])
 
1418
                    old_child_path = osutils.pathjoin(child_dirname,
 
1419
                                                      child_basename)
1267
1420
                    removals[child[0][2]] = old_child_path
1268
1421
                    child_suffix = child_dirname[len(old_path):]
1269
1422
                    new_child_dirname = (new_path + child_suffix)
1270
1423
                    key = (new_child_dirname, child_basename, child[0][2])
1271
 
                    new_child_path = os.path.join(new_child_dirname,
1272
 
                                                  child_basename)
 
1424
                    new_child_path = osutils.pathjoin(new_child_dirname,
 
1425
                                                      child_basename)
1273
1426
                    insertions[child[0][2]] = (key, minikind, executable,
1274
1427
                                               fingerprint, new_child_path)
1275
 
        self._apply_removals(removals.values())
1276
 
        self._apply_insertions(insertions.values())
 
1428
        self._check_delta_ids_absent(new_ids, delta, 0)
 
1429
        try:
 
1430
            self._apply_removals(removals.iteritems())
 
1431
            self._apply_insertions(insertions.values())
 
1432
            # Validate parents
 
1433
            self._after_delta_check_parents(parents, 0)
 
1434
        except errors.BzrError, e:
 
1435
            self._changes_aborted = True
 
1436
            if 'integrity error' not in str(e):
 
1437
                raise
 
1438
            # _get_entry raises BzrError when a request is inconsistent; we
 
1439
            # want such errors to be shown as InconsistentDelta - and that 
 
1440
            # fits the behaviour we trigger.
 
1441
            raise errors.InconsistentDeltaDelta(delta,
 
1442
                "error from _get_entry. %s" % (e,))
1277
1443
 
1278
1444
    def _apply_removals(self, removals):
1279
 
        for path in sorted(removals, reverse=True):
 
1445
        for file_id, path in sorted(removals, reverse=True,
 
1446
            key=operator.itemgetter(1)):
1280
1447
            dirname, basename = osutils.split(path)
1281
1448
            block_i, entry_i, d_present, f_present = \
1282
1449
                self._get_block_entry_index(dirname, basename, 0)
1283
 
            entry = self._dirblocks[block_i][1][entry_i]
 
1450
            try:
 
1451
                entry = self._dirblocks[block_i][1][entry_i]
 
1452
            except IndexError:
 
1453
                self._raise_invalid(path, file_id,
 
1454
                    "Wrong path for old path.")
 
1455
            if not f_present or entry[1][0][0] in 'ar':
 
1456
                self._raise_invalid(path, file_id,
 
1457
                    "Wrong path for old path.")
 
1458
            if file_id != entry[0][2]:
 
1459
                self._raise_invalid(path, file_id,
 
1460
                    "Attempt to remove path has wrong id - found %r."
 
1461
                    % entry[0][2])
1284
1462
            self._make_absent(entry)
1285
1463
            # See if we have a malformed delta: deleting a directory must not
1286
1464
            # leave crud behind. This increases the number of bisects needed
1294
1472
                # be due to it being in a parent tree, or a corrupt delta.
1295
1473
                for child_entry in self._dirblocks[block_i][1]:
1296
1474
                    if child_entry[1][0][0] not in ('r', 'a'):
1297
 
                        raise errors.InconsistentDelta(path, entry[0][2],
 
1475
                        self._raise_invalid(path, entry[0][2],
1298
1476
                            "The file id was deleted but its children were "
1299
1477
                            "not deleted.")
1300
1478
 
1301
1479
    def _apply_insertions(self, adds):
1302
 
        for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
1303
 
            self.update_minimal(key, minikind, executable, fingerprint,
1304
 
                                path_utf8=path_utf8)
 
1480
        try:
 
1481
            for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
 
1482
                self.update_minimal(key, minikind, executable, fingerprint,
 
1483
                                    path_utf8=path_utf8)
 
1484
        except errors.NotVersionedError:
 
1485
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
 
1486
                "Missing parent")
1305
1487
 
1306
1488
    def update_basis_by_delta(self, delta, new_revid):
1307
1489
        """Update the parents of this tree after a commit.
1314
1496
        Note that an exception during the operation of this method will leave
1315
1497
        the dirstate in a corrupt state where it should not be saved.
1316
1498
 
1317
 
        Finally, we expect all changes to be synchronising the basis tree with
1318
 
        the working tree.
1319
 
 
1320
1499
        :param new_revid: The new revision id for the trees parent.
1321
1500
        :param delta: An inventory delta (see apply_inventory_delta) describing
1322
1501
            the changes from the current left most parent revision to new_revid.
1334
1513
 
1335
1514
        self._parents[0] = new_revid
1336
1515
 
1337
 
        delta = sorted(delta, reverse=True)
 
1516
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
1338
1517
        adds = []
1339
1518
        changes = []
1340
1519
        deletes = []
1351
1530
        # At the same time, to reduce interface friction we convert the input
1352
1531
        # inventory entries to dirstate.
1353
1532
        root_only = ('', '')
 
1533
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1534
        # items or items placed under files/links/tree-references. We get
 
1535
        # references from every item in the delta that is not a deletion and
 
1536
        # is not itself the root.
 
1537
        parents = set()
 
1538
        # Added ids must not be in the dirstate already. This set holds those
 
1539
        # ids.
 
1540
        new_ids = set()
1354
1541
        for old_path, new_path, file_id, inv_entry in delta:
1355
 
            if old_path is None:
1356
 
                adds.append((None, encode(new_path), file_id,
 
1542
            if inv_entry is not None and file_id != inv_entry.file_id:
 
1543
                self._raise_invalid(new_path, file_id,
 
1544
                    "mismatched entry file_id %r" % inv_entry)
 
1545
            if new_path is None:
 
1546
                new_path_utf8 = None
 
1547
            else:
 
1548
                if inv_entry is None:
 
1549
                    self._raise_invalid(new_path, file_id,
 
1550
                        "new_path with no entry")
 
1551
                new_path_utf8 = encode(new_path)
 
1552
                # note the parent for validation
 
1553
                dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
 
1554
                if basename_utf8:
 
1555
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1556
            if old_path is None:
 
1557
                old_path_utf8 = None
 
1558
            else:
 
1559
                old_path_utf8 = encode(old_path)
 
1560
            if old_path is None:
 
1561
                adds.append((None, new_path_utf8, file_id,
1357
1562
                    inv_to_entry(inv_entry), True))
 
1563
                new_ids.add(file_id)
1358
1564
            elif new_path is None:
1359
 
                deletes.append((encode(old_path), None, file_id, None, True))
1360
 
            elif (old_path, new_path) != root_only:
 
1565
                deletes.append((old_path_utf8, None, file_id, None, True))
 
1566
            elif (old_path, new_path) == root_only:
 
1567
                # change things in-place
 
1568
                # Note: the case of a parent directory changing its file_id
 
1569
                #       tends to break optimizations here, because officially
 
1570
                #       the file has actually been moved, it just happens to
 
1571
                #       end up at the same path. If we can figure out how to
 
1572
                #       handle that case, we can avoid a lot of add+delete
 
1573
                #       pairs for objects that stay put.
 
1574
                # elif old_path == new_path:
 
1575
                changes.append((old_path_utf8, new_path_utf8, file_id,
 
1576
                                inv_to_entry(inv_entry)))
 
1577
            else:
1361
1578
                # Renames:
1362
1579
                # Because renames must preserve their children we must have
1363
1580
                # processed all relocations and removes before hand. The sort
1372
1589
                # for 'r' items on every pass.
1373
1590
                self._update_basis_apply_deletes(deletes)
1374
1591
                deletes = []
1375
 
                new_path_utf8 = encode(new_path)
1376
1592
                # Split into an add/delete pair recursively.
1377
 
                adds.append((None, new_path_utf8, file_id,
1378
 
                    inv_to_entry(inv_entry), False))
 
1593
                adds.append((old_path_utf8, new_path_utf8, file_id,
 
1594
                             inv_to_entry(inv_entry), False))
1379
1595
                # Expunge deletes that we've seen so that deleted/renamed
1380
1596
                # children of a rename directory are handled correctly.
1381
 
                new_deletes = reversed(list(self._iter_child_entries(1,
1382
 
                    encode(old_path))))
 
1597
                new_deletes = reversed(list(
 
1598
                    self._iter_child_entries(1, old_path_utf8)))
1383
1599
                # Remove the current contents of the tree at orig_path, and
1384
1600
                # reinsert at the correct new path.
1385
1601
                for entry in new_deletes:
1386
 
                    if entry[0][0]:
1387
 
                        source_path = entry[0][0] + '/' + entry[0][1]
 
1602
                    child_dirname, child_basename, child_file_id = entry[0]
 
1603
                    if child_dirname:
 
1604
                        source_path = child_dirname + '/' + child_basename
1388
1605
                    else:
1389
 
                        source_path = entry[0][1]
 
1606
                        source_path = child_basename
1390
1607
                    if new_path_utf8:
1391
1608
                        target_path = new_path_utf8 + source_path[len(old_path):]
1392
1609
                    else:
1393
1610
                        if old_path == '':
1394
1611
                            raise AssertionError("cannot rename directory to"
1395
 
                                " itself")
 
1612
                                                 " itself")
1396
1613
                        target_path = source_path[len(old_path) + 1:]
1397
1614
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1398
1615
                    deletes.append(
1399
1616
                        (source_path, target_path, entry[0][2], None, False))
1400
 
                deletes.append(
1401
 
                    (encode(old_path), new_path, file_id, None, False))
1402
 
            else:
1403
 
                # changes to just the root should not require remove/insertion
1404
 
                # of everything.
1405
 
                changes.append((encode(old_path), encode(new_path), file_id,
1406
 
                    inv_to_entry(inv_entry)))
1407
 
 
1408
 
        # Finish expunging deletes/first half of renames.
1409
 
        self._update_basis_apply_deletes(deletes)
1410
 
        # Reinstate second half of renames and new paths.
1411
 
        self._update_basis_apply_adds(adds)
1412
 
        # Apply in-situ changes.
1413
 
        self._update_basis_apply_changes(changes)
1414
 
 
1415
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1416
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1617
                deletes.append((old_path_utf8, new_path, file_id, None, False))
 
1618
        self._check_delta_ids_absent(new_ids, delta, 1)
 
1619
        try:
 
1620
            # Finish expunging deletes/first half of renames.
 
1621
            self._update_basis_apply_deletes(deletes)
 
1622
            # Reinstate second half of renames and new paths.
 
1623
            self._update_basis_apply_adds(adds)
 
1624
            # Apply in-situ changes.
 
1625
            self._update_basis_apply_changes(changes)
 
1626
            # Validate parents
 
1627
            self._after_delta_check_parents(parents, 1)
 
1628
        except errors.BzrError, e:
 
1629
            self._changes_aborted = True
 
1630
            if 'integrity error' not in str(e):
 
1631
                raise
 
1632
            # _get_entry raises BzrError when a request is inconsistent; we
 
1633
            # want such errors to be shown as InconsistentDelta - and that
 
1634
            # fits the behaviour we trigger.
 
1635
            raise errors.InconsistentDeltaDelta(delta,
 
1636
                "error from _get_entry. %s" % (e,))
 
1637
 
 
1638
        self._mark_modified(header_modified=True)
1417
1639
        self._id_index = None
1418
1640
        return
1419
1641
 
 
1642
    def _check_delta_ids_absent(self, new_ids, delta, tree_index):
 
1643
        """Check that none of the file_ids in new_ids are present in a tree."""
 
1644
        if not new_ids:
 
1645
            return
 
1646
        id_index = self._get_id_index()
 
1647
        for file_id in new_ids:
 
1648
            for key in id_index.get(file_id, ()):
 
1649
                block_i, entry_i, d_present, f_present = \
 
1650
                    self._get_block_entry_index(key[0], key[1], tree_index)
 
1651
                if not f_present:
 
1652
                    # In a different tree
 
1653
                    continue
 
1654
                entry = self._dirblocks[block_i][1][entry_i]
 
1655
                if entry[0][2] != file_id:
 
1656
                    # Different file_id, so not what we want.
 
1657
                    continue
 
1658
                self._raise_invalid(("%s/%s" % key[0:2]).decode('utf8'), file_id,
 
1659
                    "This file_id is new in the delta but already present in "
 
1660
                    "the target")
 
1661
 
 
1662
    def _raise_invalid(self, path, file_id, reason):
 
1663
        self._changes_aborted = True
 
1664
        raise errors.InconsistentDelta(path, file_id, reason)
 
1665
 
1420
1666
    def _update_basis_apply_adds(self, adds):
1421
1667
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1422
1668
 
1430
1676
        """
1431
1677
        # Adds are accumulated partly from renames, so can be in any input
1432
1678
        # order - sort it.
1433
 
        adds.sort()
 
1679
        # TODO: we may want to sort in dirblocks order. That way each entry
 
1680
        #       will end up in the same directory, allowing the _get_entry
 
1681
        #       fast-path for looking up 2 items in the same dir work.
 
1682
        adds.sort(key=lambda x: x[1])
1434
1683
        # adds is now in lexographic order, which places all parents before
1435
1684
        # their children, so we can process it linearly.
1436
1685
        absent = 'ar'
 
1686
        st = static_tuple.StaticTuple
1437
1687
        for old_path, new_path, file_id, new_details, real_add in adds:
1438
 
            # the entry for this file_id must be in tree 0.
1439
 
            entry = self._get_entry(0, file_id, new_path)
1440
 
            if entry[0] is None or entry[0][2] != file_id:
1441
 
                self._changes_aborted = True
1442
 
                raise errors.InconsistentDelta(new_path, file_id,
1443
 
                    'working tree does not contain new entry')
1444
 
            if real_add and entry[1][1][0] not in absent:
1445
 
                self._changes_aborted = True
1446
 
                raise errors.InconsistentDelta(new_path, file_id,
1447
 
                    'The entry was considered to be a genuinely new record,'
1448
 
                    ' but there was already an old record for it.')
1449
 
            # We don't need to update the target of an 'r' because the handling
1450
 
            # of renames turns all 'r' situations into a delete at the original
1451
 
            # location.
1452
 
            entry[1][1] = new_details
 
1688
            dirname, basename = osutils.split(new_path)
 
1689
            entry_key = st(dirname, basename, file_id)
 
1690
            block_index, present = self._find_block_index_from_key(entry_key)
 
1691
            if not present:
 
1692
                self._raise_invalid(new_path, file_id,
 
1693
                    "Unable to find block for this record."
 
1694
                    " Was the parent added?")
 
1695
            block = self._dirblocks[block_index][1]
 
1696
            entry_index, present = self._find_entry_index(entry_key, block)
 
1697
            if real_add:
 
1698
                if old_path is not None:
 
1699
                    self._raise_invalid(new_path, file_id,
 
1700
                        'considered a real add but still had old_path at %s'
 
1701
                        % (old_path,))
 
1702
            if present:
 
1703
                entry = block[entry_index]
 
1704
                basis_kind = entry[1][1][0]
 
1705
                if basis_kind == 'a':
 
1706
                    entry[1][1] = new_details
 
1707
                elif basis_kind == 'r':
 
1708
                    raise NotImplementedError()
 
1709
                else:
 
1710
                    self._raise_invalid(new_path, file_id,
 
1711
                        "An entry was marked as a new add"
 
1712
                        " but the basis target already existed")
 
1713
            else:
 
1714
                # The exact key was not found in the block. However, we need to
 
1715
                # check if there is a key next to us that would have matched.
 
1716
                # We only need to check 2 locations, because there are only 2
 
1717
                # trees present.
 
1718
                for maybe_index in range(entry_index-1, entry_index+1):
 
1719
                    if maybe_index < 0 or maybe_index >= len(block):
 
1720
                        continue
 
1721
                    maybe_entry = block[maybe_index]
 
1722
                    if maybe_entry[0][:2] != (dirname, basename):
 
1723
                        # Just a random neighbor
 
1724
                        continue
 
1725
                    if maybe_entry[0][2] == file_id:
 
1726
                        raise AssertionError(
 
1727
                            '_find_entry_index didnt find a key match'
 
1728
                            ' but walking the data did, for %s'
 
1729
                            % (entry_key,))
 
1730
                    basis_kind = maybe_entry[1][1][0]
 
1731
                    if basis_kind not in 'ar':
 
1732
                        self._raise_invalid(new_path, file_id,
 
1733
                            "we have an add record for path, but the path"
 
1734
                            " is already present with another file_id %s"
 
1735
                            % (maybe_entry[0][2],))
 
1736
 
 
1737
                entry = (entry_key, [DirState.NULL_PARENT_DETAILS,
 
1738
                                     new_details])
 
1739
                block.insert(entry_index, entry)
 
1740
 
 
1741
            active_kind = entry[1][0][0]
 
1742
            if active_kind == 'a':
 
1743
                # The active record shows up as absent, this could be genuine,
 
1744
                # or it could be present at some other location. We need to
 
1745
                # verify.
 
1746
                id_index = self._get_id_index()
 
1747
                # The id_index may not be perfectly accurate for tree1, because
 
1748
                # we haven't been keeping it updated. However, it should be
 
1749
                # fine for tree0, and that gives us enough info for what we
 
1750
                # need
 
1751
                keys = id_index.get(file_id, ())
 
1752
                for key in keys:
 
1753
                    block_i, entry_i, d_present, f_present = \
 
1754
                        self._get_block_entry_index(key[0], key[1], 0)
 
1755
                    if not f_present:
 
1756
                        continue
 
1757
                    active_entry = self._dirblocks[block_i][1][entry_i]
 
1758
                    if (active_entry[0][2] != file_id):
 
1759
                        # Some other file is at this path, we don't need to
 
1760
                        # link it.
 
1761
                        continue
 
1762
                    real_active_kind = active_entry[1][0][0]
 
1763
                    if real_active_kind in 'ar':
 
1764
                        # We found a record, which was not *this* record,
 
1765
                        # which matches the file_id, but is not actually
 
1766
                        # present. Something seems *really* wrong.
 
1767
                        self._raise_invalid(new_path, file_id,
 
1768
                            "We found a tree0 entry that doesnt make sense")
 
1769
                    # Now, we've found a tree0 entry which matches the file_id
 
1770
                    # but is at a different location. So update them to be
 
1771
                    # rename records.
 
1772
                    active_dir, active_name = active_entry[0][:2]
 
1773
                    if active_dir:
 
1774
                        active_path = active_dir + '/' + active_name
 
1775
                    else:
 
1776
                        active_path = active_name
 
1777
                    active_entry[1][1] = st('r', new_path, 0, False, '')
 
1778
                    entry[1][0] = st('r', active_path, 0, False, '')
 
1779
            elif active_kind == 'r':
 
1780
                raise NotImplementedError()
 
1781
 
 
1782
            new_kind = new_details[0]
 
1783
            if new_kind == 'd':
 
1784
                self._ensure_block(block_index, entry_index, new_path)
1453
1785
 
1454
1786
    def _update_basis_apply_changes(self, changes):
1455
1787
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1460
1792
        absent = 'ar'
1461
1793
        for old_path, new_path, file_id, new_details in changes:
1462
1794
            # the entry for this file_id must be in tree 0.
1463
 
            entry = self._get_entry(0, file_id, new_path)
1464
 
            if entry[0] is None or entry[0][2] != file_id:
1465
 
                self._changes_aborted = True
1466
 
                raise errors.InconsistentDelta(new_path, file_id,
1467
 
                    'working tree does not contain new entry')
1468
 
            if (entry[1][0][0] in absent or
1469
 
                entry[1][1][0] in absent):
1470
 
                self._changes_aborted = True
1471
 
                raise errors.InconsistentDelta(new_path, file_id,
1472
 
                    'changed considered absent')
 
1795
            entry = self._get_entry(1, file_id, new_path)
 
1796
            if entry[0] is None or entry[1][1][0] in 'ar':
 
1797
                self._raise_invalid(new_path, file_id,
 
1798
                    'changed entry considered not present')
1473
1799
            entry[1][1] = new_details
1474
1800
 
1475
1801
    def _update_basis_apply_deletes(self, deletes):
1487
1813
        null = DirState.NULL_PARENT_DETAILS
1488
1814
        for old_path, new_path, file_id, _, real_delete in deletes:
1489
1815
            if real_delete != (new_path is None):
1490
 
                raise AssertionError("bad delete delta")
 
1816
                self._raise_invalid(old_path, file_id, "bad delete delta")
1491
1817
            # the entry for this file_id must be in tree 1.
1492
1818
            dirname, basename = osutils.split(old_path)
1493
1819
            block_index, entry_index, dir_present, file_present = \
1494
1820
                self._get_block_entry_index(dirname, basename, 1)
1495
1821
            if not file_present:
1496
 
                self._changes_aborted = True
1497
 
                raise errors.InconsistentDelta(old_path, file_id,
 
1822
                self._raise_invalid(old_path, file_id,
1498
1823
                    'basis tree does not contain removed entry')
1499
1824
            entry = self._dirblocks[block_index][1][entry_index]
 
1825
            # The state of the entry in the 'active' WT
 
1826
            active_kind = entry[1][0][0]
1500
1827
            if entry[0][2] != file_id:
1501
 
                self._changes_aborted = True
1502
 
                raise errors.InconsistentDelta(old_path, file_id,
 
1828
                self._raise_invalid(old_path, file_id,
1503
1829
                    'mismatched file_id in tree 1')
1504
 
            if real_delete:
1505
 
                if entry[1][0][0] != 'a':
1506
 
                    self._changes_aborted = True
1507
 
                    raise errors.InconsistentDelta(old_path, file_id,
1508
 
                            'This was marked as a real delete, but the WT state'
1509
 
                            ' claims that it still exists and is versioned.')
 
1830
            dir_block = ()
 
1831
            old_kind = entry[1][1][0]
 
1832
            if active_kind in 'ar':
 
1833
                # The active tree doesn't have this file_id.
 
1834
                # The basis tree is changing this record. If this is a
 
1835
                # rename, then we don't want the record here at all
 
1836
                # anymore. If it is just an in-place change, we want the
 
1837
                # record here, but we'll add it if we need to. So we just
 
1838
                # delete it
 
1839
                if active_kind == 'r':
 
1840
                    active_path = entry[1][0][1]
 
1841
                    active_entry = self._get_entry(0, file_id, active_path)
 
1842
                    if active_entry[1][1][0] != 'r':
 
1843
                        self._raise_invalid(old_path, file_id,
 
1844
                            "Dirstate did not have matching rename entries")
 
1845
                    elif active_entry[1][0][0] in 'ar':
 
1846
                        self._raise_invalid(old_path, file_id,
 
1847
                            "Dirstate had a rename pointing at an inactive"
 
1848
                            " tree0")
 
1849
                    active_entry[1][1] = null
1510
1850
                del self._dirblocks[block_index][1][entry_index]
 
1851
                if old_kind == 'd':
 
1852
                    # This was a directory, and the active tree says it
 
1853
                    # doesn't exist, and now the basis tree says it doesn't
 
1854
                    # exist. Remove its dirblock if present
 
1855
                    (dir_block_index,
 
1856
                     present) = self._find_block_index_from_key(
 
1857
                        (old_path, '', ''))
 
1858
                    if present:
 
1859
                        dir_block = self._dirblocks[dir_block_index][1]
 
1860
                        if not dir_block:
 
1861
                            # This entry is empty, go ahead and just remove it
 
1862
                            del self._dirblocks[dir_block_index]
1511
1863
            else:
1512
 
                if entry[1][0][0] == 'a':
1513
 
                    self._changes_aborted = True
1514
 
                    raise errors.InconsistentDelta(old_path, file_id,
1515
 
                        'The entry was considered a rename, but the source path'
1516
 
                        ' is marked as absent.')
1517
 
                    # For whatever reason, we were asked to rename an entry
1518
 
                    # that was originally marked as deleted. This could be
1519
 
                    # because we are renaming the parent directory, and the WT
1520
 
                    # current state has the file marked as deleted.
1521
 
                elif entry[1][0][0] == 'r':
1522
 
                    # implement the rename
1523
 
                    del self._dirblocks[block_index][1][entry_index]
1524
 
                else:
1525
 
                    # it is being resurrected here, so blank it out temporarily.
1526
 
                    self._dirblocks[block_index][1][entry_index][1][1] = null
 
1864
                # There is still an active record, so just mark this
 
1865
                # removed.
 
1866
                entry[1][1] = null
 
1867
                block_i, entry_i, d_present, f_present = \
 
1868
                    self._get_block_entry_index(old_path, '', 1)
 
1869
                if d_present:
 
1870
                    dir_block = self._dirblocks[block_i][1]
 
1871
            for child_entry in dir_block:
 
1872
                child_basis_kind = child_entry[1][1][0]
 
1873
                if child_basis_kind not in 'ar':
 
1874
                    self._raise_invalid(old_path, file_id,
 
1875
                        "The file id was deleted but its children were "
 
1876
                        "not deleted.")
 
1877
 
 
1878
    def _after_delta_check_parents(self, parents, index):
 
1879
        """Check that parents required by the delta are all intact.
 
1880
        
 
1881
        :param parents: An iterable of (path_utf8, file_id) tuples which are
 
1882
            required to be present in tree 'index' at path_utf8 with id file_id
 
1883
            and be a directory.
 
1884
        :param index: The column in the dirstate to check for parents in.
 
1885
        """
 
1886
        for dirname_utf8, file_id in parents:
 
1887
            # Get the entry - the ensures that file_id, dirname_utf8 exists and
 
1888
            # has the right file id.
 
1889
            entry = self._get_entry(index, file_id, dirname_utf8)
 
1890
            if entry[1] is None:
 
1891
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1892
                    file_id, "This parent is not present.")
 
1893
            # Parents of things must be directories
 
1894
            if entry[1][index][0] != 'd':
 
1895
                self._raise_invalid(dirname_utf8.decode('utf8'),
 
1896
                    file_id, "This parent is not a directory.")
1527
1897
 
1528
1898
    def _observed_sha1(self, entry, sha1, stat_value,
1529
1899
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1544
1914
                self._sha_cutoff_time()
1545
1915
            if (stat_value.st_mtime < self._cutoff_time
1546
1916
                and stat_value.st_ctime < self._cutoff_time):
1547
 
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
1548
 
                    packed_stat)
1549
 
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1917
                entry[1][0] = ('f', sha1, stat_value.st_size, entry[1][0][3],
 
1918
                               packed_stat)
 
1919
                self._mark_modified([entry])
1550
1920
 
1551
1921
    def _sha_cutoff_time(self):
1552
1922
        """Return cutoff time.
1569
1939
        # when -Dhashcache is turned on, this is monkey-patched in to log
1570
1940
        # file reads
1571
1941
        trace.mutter("dirstate sha1 " + abspath)
1572
 
        return osutils.sha_file_by_name(abspath)
 
1942
        return self._sha1_provider.sha1(abspath)
1573
1943
 
1574
1944
    def _is_executable(self, mode, old_executable):
1575
1945
        """Is this file executable?"""
1588
1958
        #       already in memory. However, this really needs to be done at a
1589
1959
        #       higher level, because there either won't be anything on disk,
1590
1960
        #       or the thing on disk will be a file.
1591
 
        return os.readlink(abspath.encode(osutils._fs_enc))
 
1961
        fs_encoding = osutils._fs_enc
 
1962
        if isinstance(abspath, unicode):
 
1963
            # abspath is defined as the path to pass to lstat. readlink is
 
1964
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
 
1965
            # encoding), so we need to encode ourselves knowing that unicode
 
1966
            # paths are produced by UnicodeDirReader on purpose.
 
1967
            abspath = abspath.encode(fs_encoding)
 
1968
        target = os.readlink(abspath)
 
1969
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1970
            # Change encoding if needed
 
1971
            target = target.decode(fs_encoding).encode('UTF-8')
 
1972
        return target
1592
1973
 
1593
1974
    def get_ghosts(self):
1594
1975
        """Return a list of the parent tree revision ids that are ghosts."""
1599
1980
        """Serialise the entire dirstate to a sequence of lines."""
1600
1981
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1601
1982
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1602
 
            # read whats on disk.
 
1983
            # read what's on disk.
1603
1984
            self._state_file.seek(0)
1604
1985
            return self._state_file.readlines()
1605
1986
        lines = []
1606
1987
        lines.append(self._get_parents_line(self.get_parent_ids()))
1607
1988
        lines.append(self._get_ghosts_line(self._ghosts))
1608
 
        # append the root line which is special cased
1609
 
        lines.extend(map(self._entry_to_line, self._iter_entries()))
 
1989
        lines.extend(self._get_entry_lines())
1610
1990
        return self._get_output_lines(lines)
1611
1991
 
1612
1992
    def _get_ghosts_line(self, ghost_ids):
1617
1997
        """Create a line for the state file for parents information."""
1618
1998
        return '\0'.join([str(len(parent_ids))] + parent_ids)
1619
1999
 
 
2000
    def _get_entry_lines(self):
 
2001
        """Create lines for entries."""
 
2002
        return map(self._entry_to_line, self._iter_entries())
 
2003
 
1620
2004
    def _get_fields_to_entry(self):
1621
2005
        """Get a function which converts entry fields into a entry record.
1622
2006
 
1740
2124
            entry_index += 1
1741
2125
        return block_index, entry_index, True, False
1742
2126
 
1743
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
 
2127
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
 
2128
                   include_deleted=False):
1744
2129
        """Get the dirstate entry for path in tree tree_index.
1745
2130
 
1746
2131
        If either file_id or path is supplied, it is used as the key to lookup.
1762
2147
        self._read_dirblocks_if_needed()
1763
2148
        if path_utf8 is not None:
1764
2149
            if type(path_utf8) is not str:
1765
 
                raise AssertionError('path_utf8 is not a str: %s %s'
 
2150
                raise errors.BzrError('path_utf8 is not a str: %s %r'
1766
2151
                    % (type(path_utf8), path_utf8))
1767
2152
            # path lookups are faster
1768
2153
            dirname, basename = osutils.split(path_utf8)
1780
2165
                                          ' tree_index, file_id and path')
1781
2166
            return entry
1782
2167
        else:
1783
 
            possible_keys = self._get_id_index().get(fileid_utf8, None)
 
2168
            possible_keys = self._get_id_index().get(fileid_utf8, ())
1784
2169
            if not possible_keys:
1785
2170
                return None, None
1786
2171
            for key in possible_keys:
1797
2182
                entry_index, present = self._find_entry_index(key, block)
1798
2183
                if present:
1799
2184
                    entry = self._dirblocks[block_index][1][entry_index]
 
2185
                    # TODO: We might want to assert that entry[0][2] ==
 
2186
                    #       fileid_utf8.
1800
2187
                    if entry[1][tree_index][0] in 'fdlt':
1801
 
                        # this is the result we are looking for: the  
 
2188
                        # this is the result we are looking for: the
1802
2189
                        # real home of this file_id in this tree.
1803
2190
                        return entry
1804
2191
                    if entry[1][tree_index][0] == 'a':
1818
2205
            return None, None
1819
2206
 
1820
2207
    @classmethod
1821
 
    def initialize(cls, path):
 
2208
    def initialize(cls, path, sha1_provider=None):
1822
2209
        """Create a new dirstate on path.
1823
2210
 
1824
2211
        The new dirstate will be an empty tree - that is it has no parents,
1825
2212
        and only a root node - which has id ROOT_ID.
1826
2213
 
1827
2214
        :param path: The name of the file for the dirstate.
 
2215
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2216
            If None, a DefaultSHA1Provider is used.
1828
2217
        :return: A write-locked DirState object.
1829
2218
        """
1830
2219
        # This constructs a new DirState object on a path, sets the _state_file
1832
2221
        # stock empty dirstate information - a root with ROOT_ID, no children,
1833
2222
        # and no parents. Finally it calls save() to ensure that this data will
1834
2223
        # persist.
1835
 
        result = cls(path)
 
2224
        if sha1_provider is None:
 
2225
            sha1_provider = DefaultSHA1Provider()
 
2226
        result = cls(path, sha1_provider)
1836
2227
        # root dir and root dir contents with no children.
1837
2228
        empty_tree_dirblocks = [('', []), ('', [])]
1838
2229
        # a new root directory, with a NULLSTAT.
1866
2257
            size = 0
1867
2258
            executable = False
1868
2259
        elif kind == 'symlink':
1869
 
            # We don't support non-ascii targets for symlinks yet.
1870
 
            fingerprint = str(inv_entry.symlink_target or '')
 
2260
            if inv_entry.symlink_target is None:
 
2261
                fingerprint = ''
 
2262
            else:
 
2263
                fingerprint = inv_entry.symlink_target.encode('utf8')
1871
2264
            size = 0
1872
2265
            executable = False
1873
2266
        elif kind == 'file':
1880
2273
            executable = False
1881
2274
        else:
1882
2275
            raise Exception("can't pack %s" % inv_entry)
1883
 
        return (minikind, fingerprint, size, executable, tree_data)
 
2276
        return static_tuple.StaticTuple(minikind, fingerprint, size,
 
2277
                                        executable, tree_data)
1884
2278
 
1885
2279
    def _iter_child_entries(self, tree_index, path_utf8):
1886
2280
        """Iterate over all the entries that are children of path_utf.
1887
2281
 
1888
 
        This only returns entries that are present (not in 'a', 'r') in 
 
2282
        This only returns entries that are present (not in 'a', 'r') in
1889
2283
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
1890
2284
        results may differ from that obtained if paths were statted to
1891
2285
        determine what ones were directories.
1922
2316
                        else:
1923
2317
                            path = entry[0][1]
1924
2318
                        next_pending_dirs.append(path)
1925
 
    
 
2319
 
1926
2320
    def _iter_entries(self):
1927
2321
        """Iterate over all the entries in the dirstate.
1928
2322
 
1935
2329
                yield entry
1936
2330
 
1937
2331
    def _get_id_index(self):
1938
 
        """Get an id index of self._dirblocks."""
 
2332
        """Get an id index of self._dirblocks.
 
2333
 
 
2334
        This maps from file_id => [(directory, name, file_id)] entries where
 
2335
        that file_id appears in one of the trees.
 
2336
        """
1939
2337
        if self._id_index is None:
1940
2338
            id_index = {}
1941
2339
            for key, tree_details in self._iter_entries():
1942
 
                id_index.setdefault(key[2], set()).add(key)
 
2340
                self._add_to_id_index(id_index, key)
1943
2341
            self._id_index = id_index
1944
2342
        return self._id_index
1945
2343
 
 
2344
    def _add_to_id_index(self, id_index, entry_key):
 
2345
        """Add this entry to the _id_index mapping."""
 
2346
        # This code used to use a set for every entry in the id_index. However,
 
2347
        # it is *rare* to have more than one entry. So a set is a large
 
2348
        # overkill. And even when we do, we won't ever have more than the
 
2349
        # number of parent trees. Which is still a small number (rarely >2). As
 
2350
        # such, we use a simple tuple, and do our own uniqueness checks. While
 
2351
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
 
2352
        # cause quadratic failure.
 
2353
        file_id = entry_key[2]
 
2354
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
 
2355
        if file_id not in id_index:
 
2356
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
 
2357
        else:
 
2358
            entry_keys = id_index[file_id]
 
2359
            if entry_key not in entry_keys:
 
2360
                id_index[file_id] = entry_keys + (entry_key,)
 
2361
 
 
2362
    def _remove_from_id_index(self, id_index, entry_key):
 
2363
        """Remove this entry from the _id_index mapping.
 
2364
 
 
2365
        It is an programming error to call this when the entry_key is not
 
2366
        already present.
 
2367
        """
 
2368
        file_id = entry_key[2]
 
2369
        entry_keys = list(id_index[file_id])
 
2370
        entry_keys.remove(entry_key)
 
2371
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
 
2372
 
1946
2373
    def _get_output_lines(self, lines):
1947
2374
        """Format lines for final output.
1948
2375
 
1968
2395
        """The number of parent entries in each record row."""
1969
2396
        return len(self._parents) - len(self._ghosts)
1970
2397
 
1971
 
    @staticmethod
1972
 
    def on_file(path):
1973
 
        """Construct a DirState on the file at path path.
 
2398
    @classmethod
 
2399
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
 
2400
        """Construct a DirState on the file at path "path".
1974
2401
 
 
2402
        :param path: The path at which the dirstate file on disk should live.
 
2403
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2404
            If None, a DefaultSHA1Provider is used.
 
2405
        :param worth_saving_limit: when the exact number of hash changed
 
2406
            entries is known, only bother saving the dirstate if more than
 
2407
            this count of entries have changed. -1 means never save.
1975
2408
        :return: An unlocked DirState object, associated with the given path.
1976
2409
        """
1977
 
        result = DirState(path)
 
2410
        if sha1_provider is None:
 
2411
            sha1_provider = DefaultSHA1Provider()
 
2412
        result = cls(path, sha1_provider,
 
2413
                     worth_saving_limit=worth_saving_limit)
1978
2414
        return result
1979
2415
 
1980
2416
    def _read_dirblocks_if_needed(self):
1981
2417
        """Read in all the dirblocks from the file if they are not in memory.
1982
 
        
 
2418
 
1983
2419
        This populates self._dirblocks, and sets self._dirblock_state to
1984
2420
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
1985
2421
        loading.
2072
2508
            trace.mutter('Not saving DirState because '
2073
2509
                    '_changes_aborted is set.')
2074
2510
            return
2075
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
2076
 
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2511
        # TODO: Since we now distinguish IN_MEMORY_MODIFIED from
 
2512
        #       IN_MEMORY_HASH_MODIFIED, we should only fail quietly if we fail
 
2513
        #       to save an IN_MEMORY_HASH_MODIFIED, and fail *noisily* if we
 
2514
        #       fail to save IN_MEMORY_MODIFIED
 
2515
        if not self._worth_saving():
 
2516
            return
2077
2517
 
2078
 
            grabbed_write_lock = False
2079
 
            if self._lock_state != 'w':
2080
 
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2081
 
                # Switch over to the new lock, as the old one may be closed.
 
2518
        grabbed_write_lock = False
 
2519
        if self._lock_state != 'w':
 
2520
            grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
 
2521
            # Switch over to the new lock, as the old one may be closed.
 
2522
            # TODO: jam 20070315 We should validate the disk file has
 
2523
            #       not changed contents, since temporary_write_lock may
 
2524
            #       not be an atomic operation.
 
2525
            self._lock_token = new_lock
 
2526
            self._state_file = new_lock.f
 
2527
            if not grabbed_write_lock:
 
2528
                # We couldn't grab a write lock, so we switch back to a read one
 
2529
                return
 
2530
        try:
 
2531
            lines = self.get_lines()
 
2532
            self._state_file.seek(0)
 
2533
            self._state_file.writelines(lines)
 
2534
            self._state_file.truncate()
 
2535
            self._state_file.flush()
 
2536
            self._maybe_fdatasync()
 
2537
            self._mark_unmodified()
 
2538
        finally:
 
2539
            if grabbed_write_lock:
 
2540
                self._lock_token = self._lock_token.restore_read_lock()
 
2541
                self._state_file = self._lock_token.f
2082
2542
                # TODO: jam 20070315 We should validate the disk file has
2083
 
                #       not changed contents. Since temporary_write_lock may
2084
 
                #       not be an atomic operation.
2085
 
                self._lock_token = new_lock
2086
 
                self._state_file = new_lock.f
2087
 
                if not grabbed_write_lock:
2088
 
                    # We couldn't grab a write lock, so we switch back to a read one
2089
 
                    return
2090
 
            try:
2091
 
                self._state_file.seek(0)
2092
 
                self._state_file.writelines(self.get_lines())
2093
 
                self._state_file.truncate()
2094
 
                self._state_file.flush()
2095
 
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
2096
 
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
2097
 
            finally:
2098
 
                if grabbed_write_lock:
2099
 
                    self._lock_token = self._lock_token.restore_read_lock()
2100
 
                    self._state_file = self._lock_token.f
2101
 
                    # TODO: jam 20070315 We should validate the disk file has
2102
 
                    #       not changed contents. Since restore_read_lock may
2103
 
                    #       not be an atomic operation.
 
2543
                #       not changed contents. Since restore_read_lock may
 
2544
                #       not be an atomic operation.                
 
2545
 
 
2546
    def _maybe_fdatasync(self):
 
2547
        """Flush to disk if possible and if not configured off."""
 
2548
        if self._config_stack.get('dirstate.fdatasync'):
 
2549
            osutils.fdatasync(self._state_file.fileno())
 
2550
 
 
2551
    def _worth_saving(self):
 
2552
        """Is it worth saving the dirstate or not?"""
 
2553
        if (self._header_state == DirState.IN_MEMORY_MODIFIED
 
2554
            or self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2555
            return True
 
2556
        if self._dirblock_state == DirState.IN_MEMORY_HASH_MODIFIED:
 
2557
            if self._worth_saving_limit == -1:
 
2558
                # We never save hash changes when the limit is -1
 
2559
                return False
 
2560
            # If we're using smart saving and only a small number of
 
2561
            # entries have changed their hash, don't bother saving. John has
 
2562
            # suggested using a heuristic here based on the size of the
 
2563
            # changed files and/or tree. For now, we go with a configurable
 
2564
            # number of changes, keeping the calculation time
 
2565
            # as low overhead as possible. (This also keeps all existing
 
2566
            # tests passing as the default is 0, i.e. always save.)
 
2567
            if len(self._known_hash_changes) >= self._worth_saving_limit:
 
2568
                return True
 
2569
        return False
2104
2570
 
2105
2571
    def _set_data(self, parent_ids, dirblocks):
2106
2572
        """Set the full dirstate data in memory.
2110
2576
 
2111
2577
        :param parent_ids: A list of parent tree revision ids.
2112
2578
        :param dirblocks: A list containing one tuple for each directory in the
2113
 
            tree. Each tuple contains the directory path and a list of entries 
 
2579
            tree. Each tuple contains the directory path and a list of entries
2114
2580
            found in that directory.
2115
2581
        """
2116
2582
        # our memory copy is now authoritative.
2117
2583
        self._dirblocks = dirblocks
2118
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
2119
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2584
        self._mark_modified(header_modified=True)
2120
2585
        self._parents = list(parent_ids)
2121
2586
        self._id_index = None
2122
2587
        self._packed_stat_index = None
2142
2607
        self._make_absent(entry)
2143
2608
        self.update_minimal(('', '', new_id), 'd',
2144
2609
            path_utf8='', packed_stat=entry[1][0][4])
2145
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2610
        self._mark_modified()
 
2611
        # XXX: This was added by Ian, we need to make sure there
 
2612
        #      are tests for it, because it isn't in bzr.dev TRUNK
 
2613
        #      It looks like the only place it is called is in setting the root
 
2614
        #      id of the tree. So probably we never had an _id_index when we
 
2615
        #      don't even have a root yet.
2146
2616
        if self._id_index is not None:
2147
 
            self._id_index.setdefault(new_id, set()).add(entry[0])
 
2617
            self._add_to_id_index(self._id_index, entry[0])
2148
2618
 
2149
2619
    def set_parent_trees(self, trees, ghosts):
2150
2620
        """Set the parent trees for the dirstate.
2151
2621
 
2152
2622
        :param trees: A list of revision_id, tree tuples. tree must be provided
2153
 
            even if the revision_id refers to a ghost: supply an empty tree in 
 
2623
            even if the revision_id refers to a ghost: supply an empty tree in
2154
2624
            this case.
2155
2625
        :param ghosts: A list of the revision_ids that are ghosts at the time
2156
2626
            of setting.
2157
 
        """ 
2158
 
        # TODO: generate a list of parent indexes to preserve to save 
 
2627
        """
 
2628
        # TODO: generate a list of parent indexes to preserve to save
2159
2629
        # processing specific parent trees. In the common case one tree will
2160
2630
        # be preserved - the left most parent.
2161
2631
        # TODO: if the parent tree is a dirstate, we might want to walk them
2166
2636
        # map and then walk the new parent trees only, mapping them into the
2167
2637
        # dirstate. Walk the dirstate at the same time to remove unreferenced
2168
2638
        # entries.
2169
 
        # for now: 
2170
 
        # sketch: loop over all entries in the dirstate, cherry picking 
 
2639
        # for now:
 
2640
        # sketch: loop over all entries in the dirstate, cherry picking
2171
2641
        # entries from the parent trees, if they are not ghost trees.
2172
2642
        # after we finish walking the dirstate, all entries not in the dirstate
2173
2643
        # are deletes, so we want to append them to the end as per the design
2178
2648
        #   links. We dont't trivially use the inventory from other trees
2179
2649
        #   because this leads to either double touching, or to accessing
2180
2650
        #   missing keys,
2181
 
        # - find other keys containing a path 
2182
 
        # We accumulate each entry via this dictionary, including the root 
 
2651
        # - find other keys containing a path
 
2652
        # We accumulate each entry via this dictionary, including the root
2183
2653
        by_path = {}
2184
2654
        id_index = {}
2185
2655
        # we could do parallel iterators, but because file id data may be
2189
2659
        # parent, but for now the common cases are adding a new parent (merge),
2190
2660
        # and replacing completely (commit), and commit is more common: so
2191
2661
        # optimise merge later.
2192
 
        
 
2662
 
2193
2663
        # ---- start generation of full tree mapping data
2194
2664
        # what trees should we use?
2195
2665
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2196
 
        # how many trees do we end up with 
 
2666
        # how many trees do we end up with
2197
2667
        parent_count = len(parent_trees)
 
2668
        st = static_tuple.StaticTuple
2198
2669
 
2199
2670
        # one: the current tree
2200
2671
        for entry in self._iter_entries():
2203
2674
                continue
2204
2675
            by_path[entry[0]] = [entry[1][0]] + \
2205
2676
                [DirState.NULL_PARENT_DETAILS] * parent_count
2206
 
            id_index[entry[0][2]] = set([entry[0]])
2207
 
        
 
2677
            # TODO: Possibly inline this, since we know it isn't present yet
 
2678
            #       id_index[entry[0][2]] = (entry[0],)
 
2679
            self._add_to_id_index(id_index, entry[0])
 
2680
 
2208
2681
        # now the parent trees:
2209
2682
        for tree_index, tree in enumerate(parent_trees):
2210
2683
            # the index is off by one, adjust it.
2215
2688
            # the suffix is from tree_index+1:parent_count+1.
2216
2689
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2217
2690
            # now stitch in all the entries from this tree
2218
 
            for path, entry in tree.inventory.iter_entries_by_dir():
 
2691
            last_dirname = None
 
2692
            for path, entry in tree.iter_entries_by_dir():
2219
2693
                # here we process each trees details for each item in the tree.
2220
2694
                # we first update any existing entries for the id at other paths,
2221
2695
                # then we either create or update the entry for the id at the
2224
2698
                # avoid checking all known paths for the id when generating a
2225
2699
                # new entry at this path: by adding the id->path mapping last,
2226
2700
                # all the mappings are valid and have correct relocation
2227
 
                # records where needed. 
 
2701
                # records where needed.
2228
2702
                file_id = entry.file_id
2229
2703
                path_utf8 = path.encode('utf8')
2230
2704
                dirname, basename = osutils.split(path_utf8)
2231
 
                new_entry_key = (dirname, basename, file_id)
 
2705
                if dirname == last_dirname:
 
2706
                    # Try to re-use objects as much as possible
 
2707
                    dirname = last_dirname
 
2708
                else:
 
2709
                    last_dirname = dirname
 
2710
                new_entry_key = st(dirname, basename, file_id)
2232
2711
                # tree index consistency: All other paths for this id in this tree
2233
2712
                # index must point to the correct path.
2234
 
                for entry_key in id_index.setdefault(file_id, set()):
 
2713
                entry_keys = id_index.get(file_id, ())
 
2714
                for entry_key in entry_keys:
2235
2715
                    # TODO:PROFILING: It might be faster to just update
2236
2716
                    # rather than checking if we need to, and then overwrite
2237
2717
                    # the one we are located at.
2240
2720
                        # other trees, so put absent pointers there
2241
2721
                        # This is the vertical axis in the matrix, all pointing
2242
2722
                        # to the real path.
2243
 
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
2244
 
                # by path consistency: Insert into an existing path record (trivial), or 
2245
 
                # add a new one with relocation pointers for the other tree indexes.
2246
 
                if new_entry_key in id_index[file_id]:
2247
 
                    # there is already an entry where this data belongs, just insert it.
 
2723
                        by_path[entry_key][tree_index] = st('r', path_utf8, 0,
 
2724
                                                            False, '')
 
2725
                # by path consistency: Insert into an existing path record
 
2726
                # (trivial), or add a new one with relocation pointers for the
 
2727
                # other tree indexes.
 
2728
                if new_entry_key in entry_keys:
 
2729
                    # there is already an entry where this data belongs, just
 
2730
                    # insert it.
2248
2731
                    by_path[new_entry_key][tree_index] = \
2249
2732
                        self._inv_entry_to_details(entry)
2250
2733
                else:
2254
2737
                    new_details = []
2255
2738
                    for lookup_index in xrange(tree_index):
2256
2739
                        # boundary case: this is the first occurence of file_id
2257
 
                        # so there are no id_indexs, possibly take this out of
 
2740
                        # so there are no id_indexes, possibly take this out of
2258
2741
                        # the loop?
2259
 
                        if not len(id_index[file_id]):
 
2742
                        if not len(entry_keys):
2260
2743
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2261
2744
                        else:
2262
2745
                            # grab any one entry, use it to find the right path.
2263
 
                            # TODO: optimise this to reduce memory use in highly 
2264
 
                            # fragmented situations by reusing the relocation
2265
 
                            # records.
2266
 
                            a_key = iter(id_index[file_id]).next()
 
2746
                            a_key = iter(entry_keys).next()
2267
2747
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
2268
 
                                # its a pointer or missing statement, use it as is.
 
2748
                                # its a pointer or missing statement, use it as
 
2749
                                # is.
2269
2750
                                new_details.append(by_path[a_key][lookup_index])
2270
2751
                            else:
2271
2752
                                # we have the right key, make a pointer to it.
2272
2753
                                real_path = ('/'.join(a_key[0:2])).strip('/')
2273
 
                                new_details.append(('r', real_path, 0, False, ''))
 
2754
                                new_details.append(st('r', real_path, 0, False,
 
2755
                                                      ''))
2274
2756
                    new_details.append(self._inv_entry_to_details(entry))
2275
2757
                    new_details.extend(new_location_suffix)
2276
2758
                    by_path[new_entry_key] = new_details
2277
 
                    id_index[file_id].add(new_entry_key)
 
2759
                    self._add_to_id_index(id_index, new_entry_key)
2278
2760
        # --- end generation of full tree mappings
2279
2761
 
2280
2762
        # sort and output all the entries
2282
2764
        self._entries_to_current_state(new_entries)
2283
2765
        self._parents = [rev_id for rev_id, tree in trees]
2284
2766
        self._ghosts = list(ghosts)
2285
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
2286
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2767
        self._mark_modified(header_modified=True)
2287
2768
        self._id_index = id_index
2288
2769
 
2289
2770
    def _sort_entries(self, entry_list):
2293
2774
        try to keep everything in sorted blocks all the time, but sometimes
2294
2775
        it's easier to sort after the fact.
2295
2776
        """
2296
 
        def _key(entry):
 
2777
        # When sorting, we usually have 10x more entries than directories. (69k
 
2778
        # total entries, 4k directories). So cache the results of splitting.
 
2779
        # Saving time and objects. Also, use StaticTuple to avoid putting all
 
2780
        # of these object into python's garbage collector.
 
2781
        split_dirs = {}
 
2782
        def _key(entry, _split_dirs=split_dirs, _st=static_tuple.StaticTuple):
2297
2783
            # sort by: directory parts, file name, file id
2298
 
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
 
2784
            dirpath, fname, file_id = entry[0]
 
2785
            try:
 
2786
                split = _split_dirs[dirpath]
 
2787
            except KeyError:
 
2788
                split = _st.from_sequence(dirpath.split('/'))
 
2789
                _split_dirs[dirpath] = split
 
2790
            return _st(split, fname, file_id)
2299
2791
        return sorted(entry_list, key=_key)
2300
2792
 
2301
2793
    def set_state_from_inventory(self, new_inv):
2302
 
        """Set new_inv as the current state. 
 
2794
        """Set new_inv as the current state.
2303
2795
 
2304
2796
        This API is called by tree transform, and will usually occur with
2305
2797
        existing parent trees.
2309
2801
        if 'evil' in debug.debug_flags:
2310
2802
            trace.mutter_callsite(1,
2311
2803
                "set_state_from_inventory called; please mutate the tree instead")
 
2804
        tracing = 'dirstate' in debug.debug_flags
 
2805
        if tracing:
 
2806
            trace.mutter("set_state_from_inventory trace:")
2312
2807
        self._read_dirblocks_if_needed()
2313
2808
        # sketch:
2314
 
        # Two iterators: current data and new data, both in dirblock order. 
 
2809
        # Two iterators: current data and new data, both in dirblock order.
2315
2810
        # We zip them together, which tells about entries that are new in the
2316
2811
        # inventory, or removed in the inventory, or present in both and
2317
 
        # possibly changed.  
 
2812
        # possibly changed.
2318
2813
        #
2319
2814
        # You might think we could just synthesize a new dirstate directly
2320
2815
        # since we're processing it in the right order.  However, we need to
2323
2818
        new_iterator = new_inv.iter_entries_by_dir()
2324
2819
        # we will be modifying the dirstate, so we need a stable iterator. In
2325
2820
        # future we might write one, for now we just clone the state into a
2326
 
        # list - which is a shallow copy.
 
2821
        # list using a copy so that we see every original item and don't have
 
2822
        # to adjust the position when items are inserted or deleted in the
 
2823
        # underlying dirstate.
2327
2824
        old_iterator = iter(list(self._iter_entries()))
2328
2825
        # both must have roots so this is safe:
2329
2826
        current_new = new_iterator.next()
2363
2860
            # we make both end conditions explicit
2364
2861
            if not current_old:
2365
2862
                # old is finished: insert current_new into the state.
 
2863
                if tracing:
 
2864
                    trace.mutter("Appending from new '%s'.",
 
2865
                        new_path_utf8.decode('utf8'))
2366
2866
                self.update_minimal(new_entry_key, current_new_minikind,
2367
2867
                    executable=current_new[1].executable,
2368
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
 
2868
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2869
                    fullscan=True)
2369
2870
                current_new = advance(new_iterator)
2370
2871
            elif not current_new:
2371
2872
                # new is finished
 
2873
                if tracing:
 
2874
                    trace.mutter("Truncating from old '%s/%s'.",
 
2875
                        current_old[0][0].decode('utf8'),
 
2876
                        current_old[0][1].decode('utf8'))
2372
2877
                self._make_absent(current_old)
2373
2878
                current_old = advance(old_iterator)
2374
2879
            elif new_entry_key == current_old[0]:
2381
2886
                # kind has changed.
2382
2887
                if (current_old[1][0][3] != current_new[1].executable or
2383
2888
                    current_old[1][0][0] != current_new_minikind):
 
2889
                    if tracing:
 
2890
                        trace.mutter("Updating in-place change '%s'.",
 
2891
                            new_path_utf8.decode('utf8'))
2384
2892
                    self.update_minimal(current_old[0], current_new_minikind,
2385
2893
                        executable=current_new[1].executable,
2386
 
                        path_utf8=new_path_utf8, fingerprint=fingerprint)
 
2894
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2895
                        fullscan=True)
2387
2896
                # both sides are dealt with, move on
2388
2897
                current_old = advance(old_iterator)
2389
2898
                current_new = advance(new_iterator)
2392
2901
                      and new_entry_key[1:] < current_old[0][1:])):
2393
2902
                # new comes before:
2394
2903
                # add a entry for this and advance new
 
2904
                if tracing:
 
2905
                    trace.mutter("Inserting from new '%s'.",
 
2906
                        new_path_utf8.decode('utf8'))
2395
2907
                self.update_minimal(new_entry_key, current_new_minikind,
2396
2908
                    executable=current_new[1].executable,
2397
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
 
2909
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2910
                    fullscan=True)
2398
2911
                current_new = advance(new_iterator)
2399
2912
            else:
2400
2913
                # we've advanced past the place where the old key would be,
2401
2914
                # without seeing it in the new list.  so it must be gone.
 
2915
                if tracing:
 
2916
                    trace.mutter("Deleting from old '%s/%s'.",
 
2917
                        current_old[0][0].decode('utf8'),
 
2918
                        current_old[0][1].decode('utf8'))
2402
2919
                self._make_absent(current_old)
2403
2920
                current_old = advance(old_iterator)
2404
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2921
        self._mark_modified()
2405
2922
        self._id_index = None
2406
2923
        self._packed_stat_index = None
 
2924
        if tracing:
 
2925
            trace.mutter("set_state_from_inventory complete.")
 
2926
 
 
2927
    def set_state_from_scratch(self, working_inv, parent_trees, parent_ghosts):
 
2928
        """Wipe the currently stored state and set it to something new.
 
2929
 
 
2930
        This is a hard-reset for the data we are working with.
 
2931
        """
 
2932
        # Technically, we really want a write lock, but until we write, we
 
2933
        # don't really need it.
 
2934
        self._requires_lock()
 
2935
        # root dir and root dir contents with no children. We have to have a
 
2936
        # root for set_state_from_inventory to work correctly.
 
2937
        empty_root = (('', '', inventory.ROOT_ID),
 
2938
                      [('d', '', 0, False, DirState.NULLSTAT)])
 
2939
        empty_tree_dirblocks = [('', [empty_root]), ('', [])]
 
2940
        self._set_data([], empty_tree_dirblocks)
 
2941
        self.set_state_from_inventory(working_inv)
 
2942
        self.set_parent_trees(parent_trees, parent_ghosts)
2407
2943
 
2408
2944
    def _make_absent(self, current_old):
2409
2945
        """Mark current_old - an entry - as absent for tree 0.
2435
2971
            block[1].pop(entry_index)
2436
2972
            # if we have an id_index in use, remove this key from it for this id.
2437
2973
            if self._id_index is not None:
2438
 
                self._id_index[current_old[0][2]].remove(current_old[0])
 
2974
                self._remove_from_id_index(self._id_index, current_old[0])
2439
2975
        # update all remaining keys for this id to record it as absent. The
2440
2976
        # existing details may either be the record we are marking as deleted
2441
2977
        # (if there were other trees with the id present at this path), or may
2454
2990
            if update_tree_details[0][0] == 'a': # absent
2455
2991
                raise AssertionError('bad row %r' % (update_tree_details,))
2456
2992
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2457
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2993
        self._mark_modified()
2458
2994
        return last_reference
2459
2995
 
2460
2996
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
2461
 
                       packed_stat=None, size=0, path_utf8=None):
 
2997
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
2462
2998
        """Update an entry to the state in tree 0.
2463
2999
 
2464
3000
        This will either create a new entry at 'key' or update an existing one.
2469
3005
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
2470
3006
                'directory'), etc.
2471
3007
        :param executable: Should the executable bit be set?
2472
 
        :param fingerprint: Simple fingerprint for new entry: sha1 for files, 
2473
 
            referenced revision id for subtrees, etc.
 
3008
        :param fingerprint: Simple fingerprint for new entry: canonical-form
 
3009
            sha1 for files, referenced revision id for subtrees, etc.
2474
3010
        :param packed_stat: Packed stat value for new entry.
2475
3011
        :param size: Size information for new entry
2476
3012
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
2477
3013
                extra computation.
 
3014
        :param fullscan: If True then a complete scan of the dirstate is being
 
3015
            done and checking for duplicate rows should not be done. This
 
3016
            should only be set by set_state_from_inventory and similar methods.
2478
3017
 
2479
3018
        If packed_stat and fingerprint are not given, they're invalidated in
2480
3019
        the entry.
2489
3028
        new_details = (minikind, fingerprint, size, executable, packed_stat)
2490
3029
        id_index = self._get_id_index()
2491
3030
        if not present:
 
3031
            # New record. Check there isn't a entry at this path already.
 
3032
            if not fullscan:
 
3033
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
 
3034
                while low_index < len(block):
 
3035
                    entry = block[low_index]
 
3036
                    if entry[0][0:2] == key[0:2]:
 
3037
                        if entry[1][0][0] not in 'ar':
 
3038
                            # This entry has the same path (but a different id) as
 
3039
                            # the new entry we're adding, and is present in ths
 
3040
                            # tree.
 
3041
                            self._raise_invalid(
 
3042
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
 
3043
                                "Attempt to add item at path already occupied by "
 
3044
                                "id %r" % entry[0][2])
 
3045
                        low_index += 1
 
3046
                    else:
 
3047
                        break
2492
3048
            # new entry, synthesis cross reference here,
2493
 
            existing_keys = id_index.setdefault(key[2], set())
 
3049
            existing_keys = id_index.get(key[2], ())
2494
3050
            if not existing_keys:
2495
3051
                # not currently in the state, simplest case
2496
3052
                new_entry = key, [new_details] + self._empty_parent_info()
2499
3055
                # grab one of them and use it to generate parent
2500
3056
                # relocation/absent entries.
2501
3057
                new_entry = key, [new_details]
2502
 
                for other_key in existing_keys:
 
3058
                # existing_keys can be changed as we iterate.
 
3059
                for other_key in tuple(existing_keys):
2503
3060
                    # change the record at other to be a pointer to this new
2504
3061
                    # record. The loop looks similar to the change to
2505
3062
                    # relocations when updating an existing record but its not:
2506
3063
                    # the test for existing kinds is different: this can be
2507
3064
                    # factored out to a helper though.
2508
 
                    other_block_index, present = self._find_block_index_from_key(other_key)
2509
 
                    if not present:
2510
 
                        raise AssertionError('could not find block for %s' % (other_key,))
2511
 
                    other_entry_index, present = self._find_entry_index(other_key,
2512
 
                                            self._dirblocks[other_block_index][1])
2513
 
                    if not present:
2514
 
                        raise AssertionError('could not find entry for %s' % (other_key,))
 
3065
                    other_block_index, present = self._find_block_index_from_key(
 
3066
                        other_key)
 
3067
                    if not present:
 
3068
                        raise AssertionError('could not find block for %s' % (
 
3069
                            other_key,))
 
3070
                    other_block = self._dirblocks[other_block_index][1]
 
3071
                    other_entry_index, present = self._find_entry_index(
 
3072
                        other_key, other_block)
 
3073
                    if not present:
 
3074
                        raise AssertionError(
 
3075
                            'update_minimal: could not find other entry for %s'
 
3076
                            % (other_key,))
2515
3077
                    if path_utf8 is None:
2516
3078
                        raise AssertionError('no path')
2517
 
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
2518
 
                        ('r', path_utf8, 0, False, '')
 
3079
                    # Turn this other location into a reference to the new
 
3080
                    # location. This also updates the aliased iterator
 
3081
                    # (current_old in set_state_from_inventory) so that the old
 
3082
                    # entry, if not already examined, is skipped over by that
 
3083
                    # loop.
 
3084
                    other_entry = other_block[other_entry_index]
 
3085
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
 
3086
                    if self._maybe_remove_row(other_block, other_entry_index,
 
3087
                                              id_index):
 
3088
                        # If the row holding this was removed, we need to
 
3089
                        # recompute where this entry goes
 
3090
                        entry_index, _ = self._find_entry_index(key, block)
2519
3091
 
 
3092
                # This loop:
 
3093
                # adds a tuple to the new details for each column
 
3094
                #  - either by copying an existing relocation pointer inside that column
 
3095
                #  - or by creating a new pointer to the right row inside that column
2520
3096
                num_present_parents = self._num_present_parents()
 
3097
                if num_present_parents:
 
3098
                    # TODO: This re-evaluates the existing_keys set, do we need
 
3099
                    #       to do that ourselves?
 
3100
                    other_key = list(existing_keys)[0]
2521
3101
                for lookup_index in xrange(1, num_present_parents + 1):
2522
3102
                    # grab any one entry, use it to find the right path.
2523
 
                    # TODO: optimise this to reduce memory use in highly 
 
3103
                    # TODO: optimise this to reduce memory use in highly
2524
3104
                    # fragmented situations by reusing the relocation
2525
3105
                    # records.
2526
3106
                    update_block_index, present = \
2530
3110
                    update_entry_index, present = \
2531
3111
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
2532
3112
                    if not present:
2533
 
                        raise AssertionError('could not find entry for %s' % (other_key,))
 
3113
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
2534
3114
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
2535
3115
                    if update_details[0] in 'ar': # relocated, absent
2536
3116
                        # its a pointer or absent in lookup_index's tree, use
2541
3121
                        pointer_path = osutils.pathjoin(*other_key[0:2])
2542
3122
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
2543
3123
            block.insert(entry_index, new_entry)
2544
 
            existing_keys.add(key)
 
3124
            self._add_to_id_index(id_index, key)
2545
3125
        else:
2546
 
            # Does the new state matter? 
 
3126
            # Does the new state matter?
2547
3127
            block[entry_index][1][0] = new_details
2548
3128
            # parents cannot be affected by what we do.
2549
 
            # other occurences of this id can be found 
 
3129
            # other occurences of this id can be found
2550
3130
            # from the id index.
2551
3131
            # ---
2552
3132
            # tree index consistency: All other paths for this id in this tree
2556
3136
            # converted to relocated.
2557
3137
            if path_utf8 is None:
2558
3138
                raise AssertionError('no path')
2559
 
            for entry_key in id_index.setdefault(key[2], set()):
 
3139
            existing_keys = id_index.get(key[2], ())
 
3140
            if key not in existing_keys:
 
3141
                raise AssertionError('We found the entry in the blocks, but'
 
3142
                    ' the key is not in the id_index.'
 
3143
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
 
3144
            for entry_key in existing_keys:
2560
3145
                # TODO:PROFILING: It might be faster to just update
2561
3146
                # rather than checking if we need to, and then overwrite
2562
3147
                # the one we are located at.
2580
3165
            if not present:
2581
3166
                self._dirblocks.insert(block_index, (subdir_key[0], []))
2582
3167
 
2583
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3168
        self._mark_modified()
 
3169
 
 
3170
    def _maybe_remove_row(self, block, index, id_index):
 
3171
        """Remove index if it is absent or relocated across the row.
 
3172
        
 
3173
        id_index is updated accordingly.
 
3174
        :return: True if we removed the row, False otherwise
 
3175
        """
 
3176
        present_in_row = False
 
3177
        entry = block[index]
 
3178
        for column in entry[1]:
 
3179
            if column[0] not in 'ar':
 
3180
                present_in_row = True
 
3181
                break
 
3182
        if not present_in_row:
 
3183
            block.pop(index)
 
3184
            self._remove_from_id_index(id_index, entry[0])
 
3185
            return True
 
3186
        return False
2584
3187
 
2585
3188
    def _validate(self):
2586
3189
        """Check that invariants on the dirblock are correct.
2587
3190
 
2588
 
        This can be useful in debugging; it shouldn't be necessary in 
 
3191
        This can be useful in debugging; it shouldn't be necessary in
2589
3192
        normal code.
2590
3193
 
2591
3194
        This must be called with a lock held.
2660
3263
        # For each file id, for each tree: either
2661
3264
        # the file id is not present at all; all rows with that id in the
2662
3265
        # key have it marked as 'absent'
2663
 
        # OR the file id is present under exactly one name; any other entries 
 
3266
        # OR the file id is present under exactly one name; any other entries
2664
3267
        # that mention that id point to the correct name.
2665
3268
        #
2666
3269
        # We check this with a dict per tree pointing either to the present
2713
3316
                        # absent; should not occur anywhere else
2714
3317
                        this_tree_map[file_id] = None, this_path
2715
3318
                    elif minikind == 'r':
2716
 
                        # relocation, must occur at expected location 
 
3319
                        # relocation, must occur at expected location
2717
3320
                        this_tree_map[file_id] = tree_state[1], this_path
2718
3321
                    else:
2719
3322
                        this_tree_map[file_id] = this_path, this_path
2721
3324
            if absent_positions == tree_count:
2722
3325
                raise AssertionError(
2723
3326
                    "entry %r has no data for any tree." % (entry,))
 
3327
        if self._id_index is not None:
 
3328
            for file_id, entry_keys in self._id_index.iteritems():
 
3329
                for entry_key in entry_keys:
 
3330
                    if entry_key[2] != file_id:
 
3331
                        raise AssertionError(
 
3332
                            'file_id %r did not match entry key %s'
 
3333
                            % (file_id, entry_key))
 
3334
                if len(entry_keys) != len(set(entry_keys)):
 
3335
                    raise AssertionError(
 
3336
                        'id_index contained non-unique data for %s'
 
3337
                        % (entry_keys,))
2724
3338
 
2725
3339
    def _wipe_state(self):
2726
3340
        """Forget all state information about the dirstate."""
2807
3421
    (saved_minikind, saved_link_or_sha1, saved_file_size,
2808
3422
     saved_executable, saved_packed_stat) = entry[1][0]
2809
3423
 
 
3424
    if minikind == 'd' and saved_minikind == 't':
 
3425
        minikind = 't'
2810
3426
    if (minikind == saved_minikind
2811
3427
        and packed_stat == saved_packed_stat):
2812
3428
        # The stat hasn't changed since we saved, so we can re-use the
2821
3437
    # If we have gotten this far, that means that we need to actually
2822
3438
    # process this entry.
2823
3439
    link_or_sha1 = None
 
3440
    worth_saving = True
2824
3441
    if minikind == 'f':
2825
3442
        executable = state._is_executable(stat_value.st_mode,
2826
3443
                                         saved_executable)
2830
3447
            and stat_value.st_ctime < state._cutoff_time
2831
3448
            and len(entry[1]) > 1
2832
3449
            and entry[1][1][0] != 'a'):
2833
 
                # Could check for size changes for further optimised
2834
 
                # avoidance of sha1's. However the most prominent case of
2835
 
                # over-shaing is during initial add, which this catches.
 
3450
            # Could check for size changes for further optimised
 
3451
            # avoidance of sha1's. However the most prominent case of
 
3452
            # over-shaing is during initial add, which this catches.
 
3453
            # Besides, if content filtering happens, size and sha
 
3454
            # are calculated at the same time, so checking just the size
 
3455
            # gains nothing w.r.t. performance.
2836
3456
            link_or_sha1 = state._sha1_file(abspath)
2837
3457
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
2838
3458
                           executable, packed_stat)
2839
3459
        else:
2840
3460
            entry[1][0] = ('f', '', stat_value.st_size,
2841
3461
                           executable, DirState.NULLSTAT)
 
3462
            worth_saving = False
2842
3463
    elif minikind == 'd':
2843
3464
        link_or_sha1 = None
2844
3465
        entry[1][0] = ('d', '', 0, False, packed_stat)
2850
3471
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
2851
3472
            state._ensure_block(block_index, entry_index,
2852
3473
                               osutils.pathjoin(entry[0][0], entry[0][1]))
 
3474
        else:
 
3475
            worth_saving = False
2853
3476
    elif minikind == 'l':
 
3477
        if saved_minikind == 'l':
 
3478
            worth_saving = False
2854
3479
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
2855
3480
        if state._cutoff_time is None:
2856
3481
            state._sha_cutoff_time()
2861
3486
        else:
2862
3487
            entry[1][0] = ('l', '', stat_value.st_size,
2863
3488
                           False, DirState.NULLSTAT)
2864
 
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3489
    if worth_saving:
 
3490
        state._mark_modified([entry])
2865
3491
    return link_or_sha1
2866
 
update_entry = py_update_entry
2867
3492
 
2868
3493
 
2869
3494
class ProcessEntryPython(object):
2870
3495
 
2871
 
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id", "uninteresting",
 
3496
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
2872
3497
        "last_source_parent", "last_target_parent", "include_unchanged",
2873
 
        "use_filesystem_for_exec", "utf8_decode", "searched_specific_files",
2874
 
        "search_specific_files", "state", "source_index", "target_index",
2875
 
        "want_unversioned", "tree"]
 
3498
        "partial", "use_filesystem_for_exec", "utf8_decode",
 
3499
        "searched_specific_files", "search_specific_files",
 
3500
        "searched_exact_paths", "search_specific_file_parents", "seen_ids",
 
3501
        "state", "source_index", "target_index", "want_unversioned", "tree"]
2876
3502
 
2877
3503
    def __init__(self, include_unchanged, use_filesystem_for_exec,
2878
3504
        search_specific_files, state, source_index, target_index,
2879
3505
        want_unversioned, tree):
2880
3506
        self.old_dirname_to_file_id = {}
2881
3507
        self.new_dirname_to_file_id = {}
2882
 
        # Just a sentry, so that _process_entry can say that this
2883
 
        # record is handled, but isn't interesting to process (unchanged)
2884
 
        self.uninteresting = object()
 
3508
        # Are we doing a partial iter_changes?
 
3509
        self.partial = search_specific_files != set([''])
2885
3510
        # Using a list so that we can access the values and change them in
2886
3511
        # nested scope. Each one is [path, file_id, entry]
2887
3512
        self.last_source_parent = [None, None]
2890
3515
        self.use_filesystem_for_exec = use_filesystem_for_exec
2891
3516
        self.utf8_decode = cache_utf8._utf8_decode
2892
3517
        # for all search_indexs in each path at or under each element of
2893
 
        # search_specific_files, if the detail is relocated: add the id, and add the
2894
 
        # relocated path as one to search if its not searched already. If the
2895
 
        # detail is not relocated, add the id.
 
3518
        # search_specific_files, if the detail is relocated: add the id, and
 
3519
        # add the relocated path as one to search if its not searched already.
 
3520
        # If the detail is not relocated, add the id.
2896
3521
        self.searched_specific_files = set()
 
3522
        # When we search exact paths without expanding downwards, we record
 
3523
        # that here.
 
3524
        self.searched_exact_paths = set()
2897
3525
        self.search_specific_files = search_specific_files
 
3526
        # The parents up to the root of the paths we are searching.
 
3527
        # After all normal paths are returned, these specific items are returned.
 
3528
        self.search_specific_file_parents = set()
 
3529
        # The ids we've sent out in the delta.
 
3530
        self.seen_ids = set()
2898
3531
        self.state = state
2899
3532
        self.source_index = source_index
2900
3533
        self.target_index = target_index
 
3534
        if target_index != 0:
 
3535
            # A lot of code in here depends on target_index == 0
 
3536
            raise errors.BzrError('unsupported target index')
2901
3537
        self.want_unversioned = want_unversioned
2902
3538
        self.tree = tree
2903
3539
 
2905
3541
        """Compare an entry and real disk to generate delta information.
2906
3542
 
2907
3543
        :param path_info: top_relpath, basename, kind, lstat, abspath for
2908
 
            the path of entry. If None, then the path is considered absent.
2909
 
            (Perhaps we should pass in a concrete entry for this ?)
 
3544
            the path of entry. If None, then the path is considered absent in 
 
3545
            the target (Perhaps we should pass in a concrete entry for this ?)
2910
3546
            Basename is returned as a utf8 string because we expect this
2911
3547
            tuple will be ignored, and don't want to take the time to
2912
3548
            decode.
2913
 
        :return: None if these don't match
2914
 
                 A tuple of information about the change, or
2915
 
                 the object 'uninteresting' if these match, but are
2916
 
                 basically identical.
 
3549
        :return: (iter_changes_result, changed). If the entry has not been
 
3550
            handled then changed is None. Otherwise it is False if no content
 
3551
            or metadata changes have occurred, and True if any content or
 
3552
            metadata change has occurred. If self.include_unchanged is True then
 
3553
            if changed is not None, iter_changes_result will always be a result
 
3554
            tuple. Otherwise, iter_changes_result is None unless changed is
 
3555
            True.
2917
3556
        """
2918
3557
        if self.source_index is None:
2919
3558
            source_details = DirState.NULL_PARENT_DETAILS
2987
3626
                    if source_minikind != 'f':
2988
3627
                        content_change = True
2989
3628
                    else:
2990
 
                        # If the size is the same, check the sha:
2991
 
                        if target_details[2] == source_details[2]:
2992
 
                            if link_or_sha1 is None:
2993
 
                                # Stat cache miss:
2994
 
                                file_obj = file(path_info[4], 'rb')
2995
 
                                try:
2996
 
                                    statvalue = os.fstat(file_obj.fileno())
2997
 
                                    link_or_sha1 = osutils.sha_file(file_obj)
2998
 
                                finally:
2999
 
                                    file_obj.close()
3000
 
                                self.state._observed_sha1(entry, link_or_sha1,
3001
 
                                    statvalue)
3002
 
                            content_change = (link_or_sha1 != source_details[1])
3003
 
                        else:
3004
 
                            # Size changed, so must be different
3005
 
                            content_change = True
 
3629
                        # Check the sha. We can't just rely on the size as
 
3630
                        # content filtering may mean differ sizes actually
 
3631
                        # map to the same content
 
3632
                        if link_or_sha1 is None:
 
3633
                            # Stat cache miss:
 
3634
                            statvalue, link_or_sha1 = \
 
3635
                                self.state._sha1_provider.stat_and_sha1(
 
3636
                                path_info[4])
 
3637
                            self.state._observed_sha1(entry, link_or_sha1,
 
3638
                                statvalue)
 
3639
                        content_change = (link_or_sha1 != source_details[1])
3006
3640
                    # Target details is updated at update_entry time
3007
3641
                    if self.use_filesystem_for_exec:
3008
3642
                        # We don't need S_ISREG here, because we are sure
3023
3657
                        content_change = False
3024
3658
                    target_exec = False
3025
3659
                else:
3026
 
                    raise Exception, "unknown kind %s" % path_info[2]
 
3660
                    if path is None:
 
3661
                        path = pathjoin(old_dirname, old_basename)
 
3662
                    raise errors.BadFileKindError(path, path_info[2])
3027
3663
            if source_minikind == 'd':
3028
3664
                if path is None:
3029
3665
                    old_path = path = pathjoin(old_dirname, old_basename)
3030
3666
                self.old_dirname_to_file_id[old_path] = file_id
3031
3667
            # parent id is the entry for the path in the target tree
3032
 
            if old_dirname == self.last_source_parent[0]:
 
3668
            if old_basename and old_dirname == self.last_source_parent[0]:
3033
3669
                source_parent_id = self.last_source_parent[1]
3034
3670
            else:
3035
3671
                try:
3045
3681
                    self.last_source_parent[0] = old_dirname
3046
3682
                    self.last_source_parent[1] = source_parent_id
3047
3683
            new_dirname = entry[0][0]
3048
 
            if new_dirname == self.last_target_parent[0]:
 
3684
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
3049
3685
                target_parent_id = self.last_target_parent[1]
3050
3686
            else:
3051
3687
                try:
3068
3704
                    self.last_target_parent[1] = target_parent_id
3069
3705
 
3070
3706
            source_exec = source_details[3]
3071
 
            if (self.include_unchanged
3072
 
                or content_change
 
3707
            changed = (content_change
3073
3708
                or source_parent_id != target_parent_id
3074
3709
                or old_basename != entry[0][1]
3075
3710
                or source_exec != target_exec
3076
 
                ):
 
3711
                )
 
3712
            if not changed and not self.include_unchanged:
 
3713
                return None, False
 
3714
            else:
3077
3715
                if old_path is None:
3078
3716
                    old_path = path = pathjoin(old_dirname, old_basename)
3079
3717
                    old_path_u = self.utf8_decode(old_path)[0]
3092
3730
                       (source_parent_id, target_parent_id),
3093
3731
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3094
3732
                       (source_kind, target_kind),
3095
 
                       (source_exec, target_exec))
3096
 
            else:
3097
 
                return self.uninteresting
 
3733
                       (source_exec, target_exec)), changed
3098
3734
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3099
3735
            # looks like a new file
3100
3736
            path = pathjoin(entry[0][0], entry[0][1])
3121
3757
                       (None, parent_id),
3122
3758
                       (None, self.utf8_decode(entry[0][1])[0]),
3123
3759
                       (None, path_info[2]),
3124
 
                       (None, target_exec))
 
3760
                       (None, target_exec)), True
3125
3761
            else:
3126
3762
                # Its a missing file, report it as such.
3127
3763
                return (entry[0][2],
3131
3767
                       (None, parent_id),
3132
3768
                       (None, self.utf8_decode(entry[0][1])[0]),
3133
3769
                       (None, None),
3134
 
                       (None, False))
 
3770
                       (None, False)), True
3135
3771
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3136
3772
            # unversioned, possibly, or possibly not deleted: we dont care.
3137
3773
            # if its still on disk, *and* theres no other entry at this
3149
3785
                   (parent_id, None),
3150
3786
                   (self.utf8_decode(entry[0][1])[0], None),
3151
3787
                   (DirState._minikind_to_kind[source_minikind], None),
3152
 
                   (source_details[3], None))
 
3788
                   (source_details[3], None)), True
3153
3789
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3154
3790
            # a rename; could be a true rename, or a rename inherited from
3155
3791
            # a renamed parent. TODO: handle this efficiently. Its not
3166
3802
            raise AssertionError("don't know how to compare "
3167
3803
                "source_minikind=%r, target_minikind=%r"
3168
3804
                % (source_minikind, target_minikind))
3169
 
            ## import pdb;pdb.set_trace()
3170
 
        return None
 
3805
        return None, None
3171
3806
 
3172
3807
    def __iter__(self):
3173
3808
        return self
3174
3809
 
 
3810
    def _gather_result_for_consistency(self, result):
 
3811
        """Check a result we will yield to make sure we are consistent later.
 
3812
        
 
3813
        This gathers result's parents into a set to output later.
 
3814
 
 
3815
        :param result: A result tuple.
 
3816
        """
 
3817
        if not self.partial or not result[0]:
 
3818
            return
 
3819
        self.seen_ids.add(result[0])
 
3820
        new_path = result[1][1]
 
3821
        if new_path:
 
3822
            # Not the root and not a delete: queue up the parents of the path.
 
3823
            self.search_specific_file_parents.update(
 
3824
                osutils.parent_directories(new_path.encode('utf8')))
 
3825
            # Add the root directory which parent_directories does not
 
3826
            # provide.
 
3827
            self.search_specific_file_parents.add('')
 
3828
 
3175
3829
    def iter_changes(self):
3176
3830
        """Iterate over the changes."""
3177
3831
        utf8_decode = cache_utf8._utf8_decode
3178
3832
        _cmp_by_dirs = cmp_by_dirs
3179
3833
        _process_entry = self._process_entry
3180
 
        uninteresting = self.uninteresting
3181
3834
        search_specific_files = self.search_specific_files
3182
3835
        searched_specific_files = self.searched_specific_files
3183
3836
        splitpath = osutils.splitpath
3184
 
        # sketch: 
 
3837
        # sketch:
3185
3838
        # compare source_index and target_index at or under each element of search_specific_files.
3186
3839
        # follow the following comparison table. Note that we only want to do diff operations when
3187
 
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
 
3840
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo
3188
3841
        # for the target.
3189
3842
        # cases:
3190
 
        # 
 
3843
        #
3191
3844
        # Source | Target | disk | action
3192
3845
        #   r    | fdlt   |      | add source to search, add id path move and perform
3193
3846
        #        |        |      | diff check on source-target
3194
 
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
 
3847
        #   r    | fdlt   |  a   | dangling file that was present in the basis.
3195
3848
        #        |        |      | ???
3196
3849
        #   r    |  a     |      | add source to search
3197
 
        #   r    |  a     |  a   | 
 
3850
        #   r    |  a     |  a   |
3198
3851
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
3199
3852
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
3200
3853
        #   a    | fdlt   |      | add new id
3253
3906
                continue
3254
3907
            path_handled = False
3255
3908
            for entry in root_entries:
3256
 
                result = _process_entry(entry, root_dir_info)
3257
 
                if result is not None:
 
3909
                result, changed = _process_entry(entry, root_dir_info)
 
3910
                if changed is not None:
3258
3911
                    path_handled = True
3259
 
                    if result is not uninteresting:
 
3912
                    if changed:
 
3913
                        self._gather_result_for_consistency(result)
 
3914
                    if changed or self.include_unchanged:
3260
3915
                        yield result
3261
3916
            if self.want_unversioned and not path_handled and root_dir_info:
3262
3917
                new_executable = bool(
3308
3963
                            raise AssertionError()
3309
3964
                        del current_dir_info[1][bzr_index]
3310
3965
            # walk until both the directory listing and the versioned metadata
3311
 
            # are exhausted. 
 
3966
            # are exhausted.
3312
3967
            if (block_index < len(self.state._dirblocks) and
3313
3968
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
3314
3969
                current_block = self.state._dirblocks[block_index]
3372
4027
                        for current_entry in current_block[1]:
3373
4028
                            # entry referring to file not present on disk.
3374
4029
                            # advance the entry only, after processing.
3375
 
                            result = _process_entry(current_entry, None)
3376
 
                            if result is not None:
3377
 
                                if result is not uninteresting:
 
4030
                            result, changed = _process_entry(current_entry, None)
 
4031
                            if changed is not None:
 
4032
                                if changed:
 
4033
                                    self._gather_result_for_consistency(result)
 
4034
                                if changed or self.include_unchanged:
3378
4035
                                    yield result
3379
4036
                        block_index +=1
3380
4037
                        if (block_index < len(self.state._dirblocks) and
3405
4062
                while (current_entry is not None or
3406
4063
                    current_path_info is not None):
3407
4064
                    if current_entry is None:
3408
 
                        # the check for path_handled when the path is adnvaced
 
4065
                        # the check for path_handled when the path is advanced
3409
4066
                        # will yield this path if needed.
3410
4067
                        pass
3411
4068
                    elif current_path_info is None:
3412
4069
                        # no path is fine: the per entry code will handle it.
3413
 
                        result = _process_entry(current_entry, current_path_info)
3414
 
                        if result is not None:
3415
 
                            if result is not uninteresting:
 
4070
                        result, changed = _process_entry(current_entry, current_path_info)
 
4071
                        if changed is not None:
 
4072
                            if changed:
 
4073
                                self._gather_result_for_consistency(result)
 
4074
                            if changed or self.include_unchanged:
3416
4075
                                yield result
3417
4076
                    elif (current_entry[0][1] != current_path_info[1]
3418
4077
                          or current_entry[1][self.target_index][0] in 'ar'):
3431
4090
                        else:
3432
4091
                            # entry referring to file not present on disk.
3433
4092
                            # advance the entry only, after processing.
3434
 
                            result = _process_entry(current_entry, None)
3435
 
                            if result is not None:
3436
 
                                if result is not uninteresting:
 
4093
                            result, changed = _process_entry(current_entry, None)
 
4094
                            if changed is not None:
 
4095
                                if changed:
 
4096
                                    self._gather_result_for_consistency(result)
 
4097
                                if changed or self.include_unchanged:
3437
4098
                                    yield result
3438
4099
                            advance_path = False
3439
4100
                    else:
3440
 
                        result = _process_entry(current_entry, current_path_info)
3441
 
                        if result is not None:
 
4101
                        result, changed = _process_entry(current_entry, current_path_info)
 
4102
                        if changed is not None:
3442
4103
                            path_handled = True
3443
 
                            if result is not uninteresting:
 
4104
                            if changed:
 
4105
                                self._gather_result_for_consistency(result)
 
4106
                            if changed or self.include_unchanged:
3444
4107
                                yield result
3445
4108
                    if advance_entry and current_entry is not None:
3446
4109
                        entry_index += 1
3475
4138
                            if current_path_info[2] in ('directory'):
3476
4139
                                del current_dir_info[1][path_index]
3477
4140
                                path_index -= 1
3478
 
                        # dont descend the disk iterator into any tree 
 
4141
                        # dont descend the disk iterator into any tree
3479
4142
                        # paths.
3480
4143
                        if current_path_info[2] == 'tree-reference':
3481
4144
                            del current_dir_info[1][path_index]
3505
4168
                        current_dir_info = dir_iterator.next()
3506
4169
                    except StopIteration:
3507
4170
                        current_dir_info = None
3508
 
_process_entry = ProcessEntryPython
 
4171
        for result in self._iter_specific_file_parents():
 
4172
            yield result
 
4173
 
 
4174
    def _iter_specific_file_parents(self):
 
4175
        """Iter over the specific file parents."""
 
4176
        while self.search_specific_file_parents:
 
4177
            # Process the parent directories for the paths we were iterating.
 
4178
            # Even in extremely large trees this should be modest, so currently
 
4179
            # no attempt is made to optimise.
 
4180
            path_utf8 = self.search_specific_file_parents.pop()
 
4181
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
 
4182
                # We've examined this path.
 
4183
                continue
 
4184
            if path_utf8 in self.searched_exact_paths:
 
4185
                # We've examined this path.
 
4186
                continue
 
4187
            path_entries = self.state._entries_for_path(path_utf8)
 
4188
            # We need either one or two entries. If the path in
 
4189
            # self.target_index has moved (so the entry in source_index is in
 
4190
            # 'ar') then we need to also look for the entry for this path in
 
4191
            # self.source_index, to output the appropriate delete-or-rename.
 
4192
            selected_entries = []
 
4193
            found_item = False
 
4194
            for candidate_entry in path_entries:
 
4195
                # Find entries present in target at this path:
 
4196
                if candidate_entry[1][self.target_index][0] not in 'ar':
 
4197
                    found_item = True
 
4198
                    selected_entries.append(candidate_entry)
 
4199
                # Find entries present in source at this path:
 
4200
                elif (self.source_index is not None and
 
4201
                    candidate_entry[1][self.source_index][0] not in 'ar'):
 
4202
                    found_item = True
 
4203
                    if candidate_entry[1][self.target_index][0] == 'a':
 
4204
                        # Deleted, emit it here.
 
4205
                        selected_entries.append(candidate_entry)
 
4206
                    else:
 
4207
                        # renamed, emit it when we process the directory it
 
4208
                        # ended up at.
 
4209
                        self.search_specific_file_parents.add(
 
4210
                            candidate_entry[1][self.target_index][1])
 
4211
            if not found_item:
 
4212
                raise AssertionError(
 
4213
                    "Missing entry for specific path parent %r, %r" % (
 
4214
                    path_utf8, path_entries))
 
4215
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
 
4216
            for entry in selected_entries:
 
4217
                if entry[0][2] in self.seen_ids:
 
4218
                    continue
 
4219
                result, changed = self._process_entry(entry, path_info)
 
4220
                if changed is None:
 
4221
                    raise AssertionError(
 
4222
                        "Got entry<->path mismatch for specific path "
 
4223
                        "%r entry %r path_info %r " % (
 
4224
                        path_utf8, entry, path_info))
 
4225
                # Only include changes - we're outside the users requested
 
4226
                # expansion.
 
4227
                if changed:
 
4228
                    self._gather_result_for_consistency(result)
 
4229
                    if (result[6][0] == 'directory' and
 
4230
                        result[6][1] != 'directory'):
 
4231
                        # This stopped being a directory, the old children have
 
4232
                        # to be included.
 
4233
                        if entry[1][self.source_index][0] == 'r':
 
4234
                            # renamed, take the source path
 
4235
                            entry_path_utf8 = entry[1][self.source_index][1]
 
4236
                        else:
 
4237
                            entry_path_utf8 = path_utf8
 
4238
                        initial_key = (entry_path_utf8, '', '')
 
4239
                        block_index, _ = self.state._find_block_index_from_key(
 
4240
                            initial_key)
 
4241
                        if block_index == 0:
 
4242
                            # The children of the root are in block index 1.
 
4243
                            block_index +=1
 
4244
                        current_block = None
 
4245
                        if block_index < len(self.state._dirblocks):
 
4246
                            current_block = self.state._dirblocks[block_index]
 
4247
                            if not osutils.is_inside(
 
4248
                                entry_path_utf8, current_block[0]):
 
4249
                                # No entries for this directory at all.
 
4250
                                current_block = None
 
4251
                        if current_block is not None:
 
4252
                            for entry in current_block[1]:
 
4253
                                if entry[1][self.source_index][0] in 'ar':
 
4254
                                    # Not in the source tree, so doesn't have to be
 
4255
                                    # included.
 
4256
                                    continue
 
4257
                                # Path of the entry itself.
 
4258
 
 
4259
                                self.search_specific_file_parents.add(
 
4260
                                    osutils.pathjoin(*entry[0][:2]))
 
4261
                if changed or self.include_unchanged:
 
4262
                    yield result
 
4263
            self.searched_exact_paths.add(path_utf8)
 
4264
 
 
4265
    def _path_info(self, utf8_path, unicode_path):
 
4266
        """Generate path_info for unicode_path.
 
4267
 
 
4268
        :return: None if unicode_path does not exist, or a path_info tuple.
 
4269
        """
 
4270
        abspath = self.tree.abspath(unicode_path)
 
4271
        try:
 
4272
            stat = os.lstat(abspath)
 
4273
        except OSError, e:
 
4274
            if e.errno == errno.ENOENT:
 
4275
                # the path does not exist.
 
4276
                return None
 
4277
            else:
 
4278
                raise
 
4279
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
 
4280
        dir_info = (utf8_path, utf8_basename,
 
4281
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
 
4282
            abspath)
 
4283
        if dir_info[2] == 'directory':
 
4284
            if self.tree._directory_is_tree_reference(
 
4285
                unicode_path):
 
4286
                self.root_dir_info = self.root_dir_info[:2] + \
 
4287
                    ('tree-reference',) + self.root_dir_info[3:]
 
4288
        return dir_info
3509
4289
 
3510
4290
 
3511
4291
# Try to load the compiled form if possible
3512
4292
try:
3513
 
    from bzrlib._dirstate_helpers_c import (
3514
 
        _read_dirblocks_c as _read_dirblocks,
3515
 
        bisect_dirblock_c as bisect_dirblock,
3516
 
        _bisect_path_left_c as _bisect_path_left,
3517
 
        _bisect_path_right_c as _bisect_path_right,
3518
 
        cmp_by_dirs_c as cmp_by_dirs,
 
4293
    from bzrlib._dirstate_helpers_pyx import (
 
4294
        _read_dirblocks,
 
4295
        bisect_dirblock,
 
4296
        _bisect_path_left,
 
4297
        _bisect_path_right,
 
4298
        cmp_by_dirs,
3519
4299
        ProcessEntryC as _process_entry,
3520
4300
        update_entry as update_entry,
3521
4301
        )
3522
 
except ImportError:
 
4302
except ImportError, e:
 
4303
    osutils.failed_to_load_extension(e)
3523
4304
    from bzrlib._dirstate_helpers_py import (
3524
 
        _read_dirblocks_py as _read_dirblocks,
3525
 
        bisect_dirblock_py as bisect_dirblock,
3526
 
        _bisect_path_left_py as _bisect_path_left,
3527
 
        _bisect_path_right_py as _bisect_path_right,
3528
 
        cmp_by_dirs_py as cmp_by_dirs,
 
4305
        _read_dirblocks,
 
4306
        bisect_dirblock,
 
4307
        _bisect_path_left,
 
4308
        _bisect_path_right,
 
4309
        cmp_by_dirs,
3529
4310
        )
 
4311
    # FIXME: It would be nice to be able to track moved lines so that the
 
4312
    # corresponding python code can be moved to the _dirstate_helpers_py
 
4313
    # module. I don't want to break the history for this important piece of
 
4314
    # code so I left the code here -- vila 20090622
 
4315
    update_entry = py_update_entry
 
4316
    _process_entry = ProcessEntryPython