~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: Vincent Ladeuil
  • Date: 2009-05-04 14:48:21 UTC
  • mto: (4349.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 4350.
  • Revision ID: v.ladeuil+lp@free.fr-20090504144821-39dvqkikmd3zqkdg
Handle servers proposing several authentication schemes.

* bzrlib/transport/http/_urllib2_wrappers.py:
(AbstractAuthHandler.auth_required): Several schemes can be
proposed by the server, try to match each one in turn.
(BasicAuthHandler.auth_match): Delete dead code.

* bzrlib/tests/test_http.py:
(load_tests): Separate proxy and http authentication tests as they
require different server setups.
(TestAuth.create_transport_readonly_server): Simplified by using
parameter provided by load_tests.
(TestAuth.test_changing_nonce): Adapt to new parametrization.
(TestProxyAuth.create_transport_readonly_server): Deleted.

* bzrlib/tests/http_utils.py:
(DigestAndBasicAuthRequestHandler, HTTPBasicAndDigestAuthServer,
ProxyBasicAndDigestAuthServer): Add a test server proposing both
basic and digest auth schemes but accepting only digest as valid.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2011 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 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
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
 
::
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
 
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
73
67
 
74
68
There may be multiple rows at the root, one per id present in the root, so the
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.
 
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 it's a file. The fingerprint is the
 
86
    sha1 value of the file's canonical form, i.e. after any read filters have
 
87
    been applied to the convenience form stored in the working tree.
 
88
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
 
89
    link target.
 
90
't' is a reference to a nested subtree; the fingerprint is the referenced
 
91
    revision.
103
92
 
104
93
Ordering:
105
94
 
106
 
The entries on disk and in memory are ordered according to the following keys::
 
95
The entries on disk and in memory are ordered according to the following keys:
107
96
 
108
97
    directory, as a list of components
109
98
    filename
110
99
    file-id
111
100
 
112
101
--- Format 1 had the following different definition: ---
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
 
102
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
103
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
 
104
    {PARENT ROW}
 
105
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
106
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
107
    SHA1
122
108
 
123
109
PARENT ROW's are emitted for every parent that is not in the ghosts details
124
110
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
149
135
----
150
136
 
151
137
Design priorities:
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
 
138
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
139
 2) fall back current object model as needed.
 
140
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
155
141
    is an example of this)
156
142
 
157
143
 
158
144
Locking:
159
 
 
160
145
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
161
146
 been modified, but will require that we flush/ignore cached stat-hit data
162
147
 because we won't want to restat all files on disk just because a lock was
163
148
 acquired, yet we cannot trust the data after the previous lock was released.
164
149
 
165
 
Memory representation::
166
 
 
 
150
Memory representation:
167
151
 vector of all directories, and vector of the childen ?
168
152
   i.e.
169
153
     root_entrie = (direntry for root, [parent_direntries_for_root]),
183
167
    - What's the risk of error here? Once we have the base format being processed
184
168
      we should have a net win regardless of optimality. So we are going to
185
169
      go with what seems reasonable.
186
 
 
187
170
open questions:
188
171
 
189
172
Maybe we should do a test profile of the core structure - 10K simulated
221
204
import bisect
222
205
import binascii
223
206
import errno
224
 
import operator
225
207
import os
226
208
from stat import S_IEXEC
227
209
import stat
237
219
    inventory,
238
220
    lock,
239
221
    osutils,
240
 
    static_tuple,
241
222
    trace,
242
223
    )
243
224
 
282
263
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
283
264
 
284
265
 
285
 
def _unpack_stat(packed_stat):
286
 
    """Turn a packed_stat back into the stat fields.
287
 
 
288
 
    This is meant as a debugging tool, should not be used in real code.
289
 
    """
290
 
    (st_size, st_mtime, st_ctime, st_dev, st_ino,
291
 
     st_mode) = struct.unpack('>LLLLLL', binascii.a2b_base64(packed_stat))
292
 
    return dict(st_size=st_size, st_mtime=st_mtime, st_ctime=st_ctime,
293
 
                st_dev=st_dev, st_ino=st_ino, st_mode=st_mode)
294
 
 
295
 
 
296
266
class SHA1Provider(object):
297
267
    """An interface for getting sha1s of a file."""
298
268
 
383
353
    NOT_IN_MEMORY = 0
384
354
    IN_MEMORY_UNMODIFIED = 1
385
355
    IN_MEMORY_MODIFIED = 2
386
 
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
387
356
 
388
357
    # A pack_stat (the x's) that is just noise and will never match the output
389
358
    # of base64 encode.
390
359
    NULLSTAT = 'x' * 32
391
 
    NULL_PARENT_DETAILS = static_tuple.StaticTuple('a', '', 0, False, '')
 
360
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
392
361
 
393
362
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
394
363
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
395
364
 
396
 
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
 
365
    def __init__(self, path, sha1_provider):
397
366
        """Create a  DirState object.
398
367
 
399
368
        :param path: The path at which the dirstate file on disk should live.
400
369
        :param sha1_provider: an object meeting the SHA1Provider interface.
401
 
        :param worth_saving_limit: when the exact number of hash changed
402
 
            entries is known, only bother saving the dirstate if more than
403
 
            this count of entries have changed.
404
 
            -1 means never save hash changes, 0 means always save hash changes.
405
370
        """
406
371
        # _header_state and _dirblock_state represent the current state
407
372
        # of the dirstate metadata and the per-row data respectiely.
444
409
        # during commit.
445
410
        self._last_block_index = None
446
411
        self._last_entry_index = None
447
 
        # The set of known hash changes
448
 
        self._known_hash_changes = set()
449
 
        # How many hash changed entries can we have without saving
450
 
        self._worth_saving_limit = worth_saving_limit
451
412
 
452
413
    def __repr__(self):
453
414
        return "%s(%r)" % \
454
415
            (self.__class__.__name__, self._filename)
455
416
 
456
 
    def _mark_modified(self, hash_changed_entries=None, header_modified=False):
457
 
        """Mark this dirstate as modified.
458
 
 
459
 
        :param hash_changed_entries: if non-None, mark just these entries as
460
 
            having their hash modified.
461
 
        :param header_modified: mark the header modified as well, not just the
462
 
            dirblocks.
463
 
        """
464
 
        #trace.mutter_callsite(3, "modified hash entries: %s", hash_changed_entries)
465
 
        if hash_changed_entries:
466
 
            self._known_hash_changes.update([e[0] for e in hash_changed_entries])
467
 
            if self._dirblock_state in (DirState.NOT_IN_MEMORY,
468
 
                                        DirState.IN_MEMORY_UNMODIFIED):
469
 
                # If the dirstate is already marked a IN_MEMORY_MODIFIED, then
470
 
                # that takes precedence.
471
 
                self._dirblock_state = DirState.IN_MEMORY_HASH_MODIFIED
472
 
        else:
473
 
            # TODO: Since we now have a IN_MEMORY_HASH_MODIFIED state, we
474
 
            #       should fail noisily if someone tries to set
475
 
            #       IN_MEMORY_MODIFIED but we don't have a write-lock!
476
 
            # We don't know exactly what changed so disable smart saving
477
 
            self._dirblock_state = DirState.IN_MEMORY_MODIFIED
478
 
        if header_modified:
479
 
            self._header_state = DirState.IN_MEMORY_MODIFIED
480
 
 
481
 
    def _mark_unmodified(self):
482
 
        """Mark this dirstate as unmodified."""
483
 
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
484
 
        self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
485
 
        self._known_hash_changes = set()
486
 
 
487
417
    def add(self, path, file_id, kind, stat, fingerprint):
488
418
        """Add a path to be tracked.
489
419
 
615
545
        if kind == 'directory':
616
546
           # insert a new dirblock
617
547
           self._ensure_block(block_index, entry_index, utf8path)
618
 
        self._mark_modified()
 
548
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
619
549
        if self._id_index:
620
 
            self._add_to_id_index(self._id_index, entry_key)
 
550
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
621
551
 
622
552
    def _bisect(self, paths):
623
553
        """Bisect through the disk structure for specific rows.
1087
1017
 
1088
1018
        self._ghosts = []
1089
1019
        self._parents = [parents[0]]
1090
 
        self._mark_modified(header_modified=True)
 
1020
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1021
        self._header_state = DirState.IN_MEMORY_MODIFIED
1091
1022
 
1092
1023
    def _empty_parent_info(self):
1093
1024
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1222
1153
    def _fields_per_entry(self):
1223
1154
        """How many null separated fields should be in each entry row.
1224
1155
 
1225
 
        Each line now has an extra '\\n' field which is not used
 
1156
        Each line now has an extra '\n' field which is not used
1226
1157
        so we just skip over it
1227
 
 
1228
 
        entry size::
 
1158
        entry size:
1229
1159
            3 fields for the key
1230
1160
            + number of fields per tree_data (5) * tree count
1231
1161
            + newline
1344
1274
            raise
1345
1275
        return result
1346
1276
 
1347
 
    def _check_delta_is_valid(self, delta):
1348
 
        return list(inventory._check_delta_unique_ids(
1349
 
                    inventory._check_delta_unique_old_paths(
1350
 
                    inventory._check_delta_unique_new_paths(
1351
 
                    inventory._check_delta_ids_match_entry(
1352
 
                    inventory._check_delta_ids_are_valid(
1353
 
                    inventory._check_delta_new_path_entry_both_or_None(delta)))))))
1354
 
 
1355
1277
    def update_by_delta(self, delta):
1356
1278
        """Apply an inventory delta to the dirstate for tree 0
1357
1279
 
1358
 
        This is the workhorse for apply_inventory_delta in dirstate based
1359
 
        trees.
1360
 
 
1361
1280
        :param delta: An inventory delta.  See Inventory.apply_delta for
1362
1281
            details.
1363
1282
        """
1364
1283
        self._read_dirblocks_if_needed()
1365
 
        encode = cache_utf8.encode
1366
1284
        insertions = {}
1367
1285
        removals = {}
1368
 
        # Accumulate parent references (path_utf8, id), to check for parentless
1369
 
        # items or items placed under files/links/tree-references. We get
1370
 
        # references from every item in the delta that is not a deletion and
1371
 
        # is not itself the root.
1372
 
        parents = set()
1373
 
        # Added ids must not be in the dirstate already. This set holds those
1374
 
        # ids.
1375
 
        new_ids = set()
1376
 
        # This loop transforms the delta to single atomic operations that can
1377
 
        # be executed and validated.
1378
 
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
1379
 
        for old_path, new_path, file_id, inv_entry in delta:
 
1286
        for old_path, new_path, file_id, inv_entry in sorted(delta, reverse=True):
1380
1287
            if (file_id in insertions) or (file_id in removals):
1381
 
                self._raise_invalid(old_path or new_path, file_id,
1382
 
                    "repeated file_id")
 
1288
                raise AssertionError("repeated file id in delta %r" % (file_id,))
1383
1289
            if old_path is not None:
1384
1290
                old_path = old_path.encode('utf-8')
1385
1291
                removals[file_id] = old_path
1386
 
            else:
1387
 
                new_ids.add(file_id)
1388
1292
            if new_path is not None:
1389
 
                if inv_entry is None:
1390
 
                    self._raise_invalid(new_path, file_id,
1391
 
                        "new_path with no entry")
1392
1293
                new_path = new_path.encode('utf-8')
1393
 
                dirname_utf8, basename = osutils.split(new_path)
1394
 
                if basename:
1395
 
                    parents.add((dirname_utf8, inv_entry.parent_id))
1396
 
                key = (dirname_utf8, basename, file_id)
 
1294
                dirname, basename = osutils.split(new_path)
 
1295
                key = (dirname, basename, file_id)
1397
1296
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1398
1297
                if minikind == 't':
1399
 
                    fingerprint = inv_entry.reference_revision or ''
 
1298
                    fingerprint = inv_entry.reference_revision
1400
1299
                else:
1401
1300
                    fingerprint = ''
1402
1301
                insertions[file_id] = (key, minikind, inv_entry.executable,
1411
1310
                    minikind = child[1][0][0]
1412
1311
                    fingerprint = child[1][0][4]
1413
1312
                    executable = child[1][0][3]
1414
 
                    old_child_path = osutils.pathjoin(child_dirname,
1415
 
                                                      child_basename)
 
1313
                    old_child_path = osutils.pathjoin(child[0][0],
 
1314
                                                      child[0][1])
1416
1315
                    removals[child[0][2]] = old_child_path
1417
1316
                    child_suffix = child_dirname[len(old_path):]
1418
1317
                    new_child_dirname = (new_path + child_suffix)
1419
1318
                    key = (new_child_dirname, child_basename, child[0][2])
1420
 
                    new_child_path = osutils.pathjoin(new_child_dirname,
1421
 
                                                      child_basename)
 
1319
                    new_child_path = os.path.join(new_child_dirname,
 
1320
                                                  child_basename)
1422
1321
                    insertions[child[0][2]] = (key, minikind, executable,
1423
1322
                                               fingerprint, new_child_path)
1424
 
        self._check_delta_ids_absent(new_ids, delta, 0)
1425
 
        try:
1426
 
            self._apply_removals(removals.iteritems())
1427
 
            self._apply_insertions(insertions.values())
1428
 
            # Validate parents
1429
 
            self._after_delta_check_parents(parents, 0)
1430
 
        except errors.BzrError, e:
1431
 
            self._changes_aborted = True
1432
 
            if 'integrity error' not in str(e):
1433
 
                raise
1434
 
            # _get_entry raises BzrError when a request is inconsistent; we
1435
 
            # want such errors to be shown as InconsistentDelta - and that 
1436
 
            # fits the behaviour we trigger.
1437
 
            raise errors.InconsistentDeltaDelta(delta,
1438
 
                "error from _get_entry. %s" % (e,))
 
1323
        self._apply_removals(removals.values())
 
1324
        self._apply_insertions(insertions.values())
1439
1325
 
1440
1326
    def _apply_removals(self, removals):
1441
 
        for file_id, path in sorted(removals, reverse=True,
1442
 
            key=operator.itemgetter(1)):
 
1327
        for path in sorted(removals, reverse=True):
1443
1328
            dirname, basename = osutils.split(path)
1444
1329
            block_i, entry_i, d_present, f_present = \
1445
1330
                self._get_block_entry_index(dirname, basename, 0)
1446
 
            try:
1447
 
                entry = self._dirblocks[block_i][1][entry_i]
1448
 
            except IndexError:
1449
 
                self._raise_invalid(path, file_id,
1450
 
                    "Wrong path for old path.")
1451
 
            if not f_present or entry[1][0][0] in 'ar':
1452
 
                self._raise_invalid(path, file_id,
1453
 
                    "Wrong path for old path.")
1454
 
            if file_id != entry[0][2]:
1455
 
                self._raise_invalid(path, file_id,
1456
 
                    "Attempt to remove path has wrong id - found %r."
1457
 
                    % entry[0][2])
 
1331
            entry = self._dirblocks[block_i][1][entry_i]
1458
1332
            self._make_absent(entry)
1459
1333
            # See if we have a malformed delta: deleting a directory must not
1460
1334
            # leave crud behind. This increases the number of bisects needed
1468
1342
                # be due to it being in a parent tree, or a corrupt delta.
1469
1343
                for child_entry in self._dirblocks[block_i][1]:
1470
1344
                    if child_entry[1][0][0] not in ('r', 'a'):
1471
 
                        self._raise_invalid(path, entry[0][2],
 
1345
                        raise errors.InconsistentDelta(path, entry[0][2],
1472
1346
                            "The file id was deleted but its children were "
1473
1347
                            "not deleted.")
1474
1348
 
1475
1349
    def _apply_insertions(self, adds):
1476
 
        try:
1477
 
            for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
1478
 
                self.update_minimal(key, minikind, executable, fingerprint,
1479
 
                                    path_utf8=path_utf8)
1480
 
        except errors.NotVersionedError:
1481
 
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
1482
 
                "Missing parent")
 
1350
        for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
 
1351
            self.update_minimal(key, minikind, executable, fingerprint,
 
1352
                                path_utf8=path_utf8)
1483
1353
 
1484
1354
    def update_basis_by_delta(self, delta, new_revid):
1485
1355
        """Update the parents of this tree after a commit.
1492
1362
        Note that an exception during the operation of this method will leave
1493
1363
        the dirstate in a corrupt state where it should not be saved.
1494
1364
 
 
1365
        Finally, we expect all changes to be synchronising the basis tree with
 
1366
        the working tree.
 
1367
 
1495
1368
        :param new_revid: The new revision id for the trees parent.
1496
1369
        :param delta: An inventory delta (see apply_inventory_delta) describing
1497
1370
            the changes from the current left most parent revision to new_revid.
1509
1382
 
1510
1383
        self._parents[0] = new_revid
1511
1384
 
1512
 
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
 
1385
        delta = sorted(delta, reverse=True)
1513
1386
        adds = []
1514
1387
        changes = []
1515
1388
        deletes = []
1526
1399
        # At the same time, to reduce interface friction we convert the input
1527
1400
        # inventory entries to dirstate.
1528
1401
        root_only = ('', '')
1529
 
        # Accumulate parent references (path_utf8, id), to check for parentless
1530
 
        # items or items placed under files/links/tree-references. We get
1531
 
        # references from every item in the delta that is not a deletion and
1532
 
        # is not itself the root.
1533
 
        parents = set()
1534
 
        # Added ids must not be in the dirstate already. This set holds those
1535
 
        # ids.
1536
 
        new_ids = set()
1537
1402
        for old_path, new_path, file_id, inv_entry in delta:
1538
 
            if inv_entry is not None and file_id != inv_entry.file_id:
1539
 
                self._raise_invalid(new_path, file_id,
1540
 
                    "mismatched entry file_id %r" % inv_entry)
1541
 
            if new_path is None:
1542
 
                new_path_utf8 = None
1543
 
            else:
1544
 
                if inv_entry is None:
1545
 
                    self._raise_invalid(new_path, file_id,
1546
 
                        "new_path with no entry")
1547
 
                new_path_utf8 = encode(new_path)
1548
 
                # note the parent for validation
1549
 
                dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
1550
 
                if basename_utf8:
1551
 
                    parents.add((dirname_utf8, inv_entry.parent_id))
1552
 
            if old_path is None:
1553
 
                old_path_utf8 = None
1554
 
            else:
1555
 
                old_path_utf8 = encode(old_path)
1556
 
            if old_path is None:
1557
 
                adds.append((None, new_path_utf8, file_id,
 
1403
            if old_path is None:
 
1404
                adds.append((None, encode(new_path), file_id,
1558
1405
                    inv_to_entry(inv_entry), True))
1559
 
                new_ids.add(file_id)
1560
1406
            elif new_path is None:
1561
 
                deletes.append((old_path_utf8, None, file_id, None, True))
1562
 
            elif (old_path, new_path) == root_only:
1563
 
                # change things in-place
1564
 
                # Note: the case of a parent directory changing its file_id
1565
 
                #       tends to break optimizations here, because officially
1566
 
                #       the file has actually been moved, it just happens to
1567
 
                #       end up at the same path. If we can figure out how to
1568
 
                #       handle that case, we can avoid a lot of add+delete
1569
 
                #       pairs for objects that stay put.
1570
 
                # elif old_path == new_path:
1571
 
                changes.append((old_path_utf8, new_path_utf8, file_id,
1572
 
                                inv_to_entry(inv_entry)))
1573
 
            else:
 
1407
                deletes.append((encode(old_path), None, file_id, None, True))
 
1408
            elif (old_path, new_path) != root_only:
1574
1409
                # Renames:
1575
1410
                # Because renames must preserve their children we must have
1576
1411
                # processed all relocations and removes before hand. The sort
1585
1420
                # for 'r' items on every pass.
1586
1421
                self._update_basis_apply_deletes(deletes)
1587
1422
                deletes = []
 
1423
                new_path_utf8 = encode(new_path)
1588
1424
                # Split into an add/delete pair recursively.
1589
 
                adds.append((old_path_utf8, new_path_utf8, file_id,
1590
 
                             inv_to_entry(inv_entry), False))
 
1425
                adds.append((None, new_path_utf8, file_id,
 
1426
                    inv_to_entry(inv_entry), False))
1591
1427
                # Expunge deletes that we've seen so that deleted/renamed
1592
1428
                # children of a rename directory are handled correctly.
1593
 
                new_deletes = reversed(list(
1594
 
                    self._iter_child_entries(1, old_path_utf8)))
 
1429
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1430
                    encode(old_path))))
1595
1431
                # Remove the current contents of the tree at orig_path, and
1596
1432
                # reinsert at the correct new path.
1597
1433
                for entry in new_deletes:
1598
 
                    child_dirname, child_basename, child_file_id = entry[0]
1599
 
                    if child_dirname:
1600
 
                        source_path = child_dirname + '/' + child_basename
 
1434
                    if entry[0][0]:
 
1435
                        source_path = entry[0][0] + '/' + entry[0][1]
1601
1436
                    else:
1602
 
                        source_path = child_basename
 
1437
                        source_path = entry[0][1]
1603
1438
                    if new_path_utf8:
1604
1439
                        target_path = new_path_utf8 + source_path[len(old_path):]
1605
1440
                    else:
1606
1441
                        if old_path == '':
1607
1442
                            raise AssertionError("cannot rename directory to"
1608
 
                                                 " itself")
 
1443
                                " itself")
1609
1444
                        target_path = source_path[len(old_path) + 1:]
1610
1445
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1611
1446
                    deletes.append(
1612
1447
                        (source_path, target_path, entry[0][2], None, False))
1613
 
                deletes.append((old_path_utf8, new_path, file_id, None, False))
1614
 
        self._check_delta_ids_absent(new_ids, delta, 1)
1615
 
        try:
1616
 
            # Finish expunging deletes/first half of renames.
1617
 
            self._update_basis_apply_deletes(deletes)
1618
 
            # Reinstate second half of renames and new paths.
1619
 
            self._update_basis_apply_adds(adds)
1620
 
            # Apply in-situ changes.
1621
 
            self._update_basis_apply_changes(changes)
1622
 
            # Validate parents
1623
 
            self._after_delta_check_parents(parents, 1)
1624
 
        except errors.BzrError, e:
1625
 
            self._changes_aborted = True
1626
 
            if 'integrity error' not in str(e):
1627
 
                raise
1628
 
            # _get_entry raises BzrError when a request is inconsistent; we
1629
 
            # want such errors to be shown as InconsistentDelta - and that
1630
 
            # fits the behaviour we trigger.
1631
 
            raise errors.InconsistentDeltaDelta(delta,
1632
 
                "error from _get_entry. %s" % (e,))
1633
 
 
1634
 
        self._mark_modified(header_modified=True)
 
1448
                deletes.append(
 
1449
                    (encode(old_path), new_path, file_id, None, False))
 
1450
            else:
 
1451
                # changes to just the root should not require remove/insertion
 
1452
                # of everything.
 
1453
                changes.append((encode(old_path), encode(new_path), file_id,
 
1454
                    inv_to_entry(inv_entry)))
 
1455
 
 
1456
        # Finish expunging deletes/first half of renames.
 
1457
        self._update_basis_apply_deletes(deletes)
 
1458
        # Reinstate second half of renames and new paths.
 
1459
        self._update_basis_apply_adds(adds)
 
1460
        # Apply in-situ changes.
 
1461
        self._update_basis_apply_changes(changes)
 
1462
 
 
1463
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1464
        self._header_state = DirState.IN_MEMORY_MODIFIED
1635
1465
        self._id_index = None
1636
1466
        return
1637
1467
 
1638
 
    def _check_delta_ids_absent(self, new_ids, delta, tree_index):
1639
 
        """Check that none of the file_ids in new_ids are present in a tree."""
1640
 
        if not new_ids:
1641
 
            return
1642
 
        id_index = self._get_id_index()
1643
 
        for file_id in new_ids:
1644
 
            for key in id_index.get(file_id, ()):
1645
 
                block_i, entry_i, d_present, f_present = \
1646
 
                    self._get_block_entry_index(key[0], key[1], tree_index)
1647
 
                if not f_present:
1648
 
                    # In a different tree
1649
 
                    continue
1650
 
                entry = self._dirblocks[block_i][1][entry_i]
1651
 
                if entry[0][2] != file_id:
1652
 
                    # Different file_id, so not what we want.
1653
 
                    continue
1654
 
                self._raise_invalid(("%s/%s" % key[0:2]).decode('utf8'), file_id,
1655
 
                    "This file_id is new in the delta but already present in "
1656
 
                    "the target")
1657
 
 
1658
 
    def _raise_invalid(self, path, file_id, reason):
1659
 
        self._changes_aborted = True
1660
 
        raise errors.InconsistentDelta(path, file_id, reason)
1661
 
 
1662
1468
    def _update_basis_apply_adds(self, adds):
1663
1469
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1664
1470
 
1672
1478
        """
1673
1479
        # Adds are accumulated partly from renames, so can be in any input
1674
1480
        # order - sort it.
1675
 
        # TODO: we may want to sort in dirblocks order. That way each entry
1676
 
        #       will end up in the same directory, allowing the _get_entry
1677
 
        #       fast-path for looking up 2 items in the same dir work.
1678
 
        adds.sort(key=lambda x: x[1])
 
1481
        adds.sort()
1679
1482
        # adds is now in lexographic order, which places all parents before
1680
1483
        # their children, so we can process it linearly.
1681
1484
        absent = 'ar'
1682
 
        st = static_tuple.StaticTuple
1683
1485
        for old_path, new_path, file_id, new_details, real_add in adds:
1684
 
            dirname, basename = osutils.split(new_path)
1685
 
            entry_key = st(dirname, basename, file_id)
1686
 
            block_index, present = self._find_block_index_from_key(entry_key)
1687
 
            if not present:
1688
 
                self._raise_invalid(new_path, file_id,
1689
 
                    "Unable to find block for this record."
1690
 
                    " Was the parent added?")
1691
 
            block = self._dirblocks[block_index][1]
1692
 
            entry_index, present = self._find_entry_index(entry_key, block)
1693
 
            if real_add:
1694
 
                if old_path is not None:
1695
 
                    self._raise_invalid(new_path, file_id,
1696
 
                        'considered a real add but still had old_path at %s'
1697
 
                        % (old_path,))
1698
 
            if present:
1699
 
                entry = block[entry_index]
1700
 
                basis_kind = entry[1][1][0]
1701
 
                if basis_kind == 'a':
1702
 
                    entry[1][1] = new_details
1703
 
                elif basis_kind == 'r':
1704
 
                    raise NotImplementedError()
1705
 
                else:
1706
 
                    self._raise_invalid(new_path, file_id,
1707
 
                        "An entry was marked as a new add"
1708
 
                        " but the basis target already existed")
1709
 
            else:
1710
 
                # The exact key was not found in the block. However, we need to
1711
 
                # check if there is a key next to us that would have matched.
1712
 
                # We only need to check 2 locations, because there are only 2
1713
 
                # trees present.
1714
 
                for maybe_index in range(entry_index-1, entry_index+1):
1715
 
                    if maybe_index < 0 or maybe_index >= len(block):
1716
 
                        continue
1717
 
                    maybe_entry = block[maybe_index]
1718
 
                    if maybe_entry[0][:2] != (dirname, basename):
1719
 
                        # Just a random neighbor
1720
 
                        continue
1721
 
                    if maybe_entry[0][2] == file_id:
1722
 
                        raise AssertionError(
1723
 
                            '_find_entry_index didnt find a key match'
1724
 
                            ' but walking the data did, for %s'
1725
 
                            % (entry_key,))
1726
 
                    basis_kind = maybe_entry[1][1][0]
1727
 
                    if basis_kind not in 'ar':
1728
 
                        self._raise_invalid(new_path, file_id,
1729
 
                            "we have an add record for path, but the path"
1730
 
                            " is already present with another file_id %s"
1731
 
                            % (maybe_entry[0][2],))
1732
 
 
1733
 
                entry = (entry_key, [DirState.NULL_PARENT_DETAILS,
1734
 
                                     new_details])
1735
 
                block.insert(entry_index, entry)
1736
 
 
1737
 
            active_kind = entry[1][0][0]
1738
 
            if active_kind == 'a':
1739
 
                # The active record shows up as absent, this could be genuine,
1740
 
                # or it could be present at some other location. We need to
1741
 
                # verify.
1742
 
                id_index = self._get_id_index()
1743
 
                # The id_index may not be perfectly accurate for tree1, because
1744
 
                # we haven't been keeping it updated. However, it should be
1745
 
                # fine for tree0, and that gives us enough info for what we
1746
 
                # need
1747
 
                keys = id_index.get(file_id, ())
1748
 
                for key in keys:
1749
 
                    block_i, entry_i, d_present, f_present = \
1750
 
                        self._get_block_entry_index(key[0], key[1], 0)
1751
 
                    if not f_present:
1752
 
                        continue
1753
 
                    active_entry = self._dirblocks[block_i][1][entry_i]
1754
 
                    if (active_entry[0][2] != file_id):
1755
 
                        # Some other file is at this path, we don't need to
1756
 
                        # link it.
1757
 
                        continue
1758
 
                    real_active_kind = active_entry[1][0][0]
1759
 
                    if real_active_kind in 'ar':
1760
 
                        # We found a record, which was not *this* record,
1761
 
                        # which matches the file_id, but is not actually
1762
 
                        # present. Something seems *really* wrong.
1763
 
                        self._raise_invalid(new_path, file_id,
1764
 
                            "We found a tree0 entry that doesnt make sense")
1765
 
                    # Now, we've found a tree0 entry which matches the file_id
1766
 
                    # but is at a different location. So update them to be
1767
 
                    # rename records.
1768
 
                    active_dir, active_name = active_entry[0][:2]
1769
 
                    if active_dir:
1770
 
                        active_path = active_dir + '/' + active_name
1771
 
                    else:
1772
 
                        active_path = active_name
1773
 
                    active_entry[1][1] = st('r', new_path, 0, False, '')
1774
 
                    entry[1][0] = st('r', active_path, 0, False, '')
1775
 
            elif active_kind == 'r':
1776
 
                raise NotImplementedError()
1777
 
 
1778
 
            new_kind = new_details[0]
1779
 
            if new_kind == 'd':
1780
 
                self._ensure_block(block_index, entry_index, new_path)
 
1486
            # the entry for this file_id must be in tree 0.
 
1487
            entry = self._get_entry(0, file_id, new_path)
 
1488
            if entry[0] is None or entry[0][2] != file_id:
 
1489
                self._changes_aborted = True
 
1490
                raise errors.InconsistentDelta(new_path, file_id,
 
1491
                    'working tree does not contain new entry')
 
1492
            if real_add and entry[1][1][0] not in absent:
 
1493
                self._changes_aborted = True
 
1494
                raise errors.InconsistentDelta(new_path, file_id,
 
1495
                    'The entry was considered to be a genuinely new record,'
 
1496
                    ' but there was already an old record for it.')
 
1497
            # We don't need to update the target of an 'r' because the handling
 
1498
            # of renames turns all 'r' situations into a delete at the original
 
1499
            # location.
 
1500
            entry[1][1] = new_details
1781
1501
 
1782
1502
    def _update_basis_apply_changes(self, changes):
1783
1503
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1788
1508
        absent = 'ar'
1789
1509
        for old_path, new_path, file_id, new_details in changes:
1790
1510
            # the entry for this file_id must be in tree 0.
1791
 
            entry = self._get_entry(1, file_id, new_path)
1792
 
            if entry[0] is None or entry[1][1][0] in 'ar':
1793
 
                self._raise_invalid(new_path, file_id,
1794
 
                    'changed entry considered not present')
 
1511
            entry = self._get_entry(0, file_id, new_path)
 
1512
            if entry[0] is None or entry[0][2] != file_id:
 
1513
                self._changes_aborted = True
 
1514
                raise errors.InconsistentDelta(new_path, file_id,
 
1515
                    'working tree does not contain new entry')
 
1516
            if (entry[1][0][0] in absent or
 
1517
                entry[1][1][0] in absent):
 
1518
                self._changes_aborted = True
 
1519
                raise errors.InconsistentDelta(new_path, file_id,
 
1520
                    'changed considered absent')
1795
1521
            entry[1][1] = new_details
1796
1522
 
1797
1523
    def _update_basis_apply_deletes(self, deletes):
1809
1535
        null = DirState.NULL_PARENT_DETAILS
1810
1536
        for old_path, new_path, file_id, _, real_delete in deletes:
1811
1537
            if real_delete != (new_path is None):
1812
 
                self._raise_invalid(old_path, file_id, "bad delete delta")
 
1538
                raise AssertionError("bad delete delta")
1813
1539
            # the entry for this file_id must be in tree 1.
1814
1540
            dirname, basename = osutils.split(old_path)
1815
1541
            block_index, entry_index, dir_present, file_present = \
1816
1542
                self._get_block_entry_index(dirname, basename, 1)
1817
1543
            if not file_present:
1818
 
                self._raise_invalid(old_path, file_id,
 
1544
                self._changes_aborted = True
 
1545
                raise errors.InconsistentDelta(old_path, file_id,
1819
1546
                    'basis tree does not contain removed entry')
1820
1547
            entry = self._dirblocks[block_index][1][entry_index]
1821
 
            # The state of the entry in the 'active' WT
1822
 
            active_kind = entry[1][0][0]
1823
1548
            if entry[0][2] != file_id:
1824
 
                self._raise_invalid(old_path, file_id,
 
1549
                self._changes_aborted = True
 
1550
                raise errors.InconsistentDelta(old_path, file_id,
1825
1551
                    'mismatched file_id in tree 1')
1826
 
            dir_block = ()
1827
 
            old_kind = entry[1][1][0]
1828
 
            if active_kind in 'ar':
1829
 
                # The active tree doesn't have this file_id.
1830
 
                # The basis tree is changing this record. If this is a
1831
 
                # rename, then we don't want the record here at all
1832
 
                # anymore. If it is just an in-place change, we want the
1833
 
                # record here, but we'll add it if we need to. So we just
1834
 
                # delete it
1835
 
                if active_kind == 'r':
1836
 
                    active_path = entry[1][0][1]
1837
 
                    active_entry = self._get_entry(0, file_id, active_path)
1838
 
                    if active_entry[1][1][0] != 'r':
1839
 
                        self._raise_invalid(old_path, file_id,
1840
 
                            "Dirstate did not have matching rename entries")
1841
 
                    elif active_entry[1][0][0] in 'ar':
1842
 
                        self._raise_invalid(old_path, file_id,
1843
 
                            "Dirstate had a rename pointing at an inactive"
1844
 
                            " tree0")
1845
 
                    active_entry[1][1] = null
 
1552
            if real_delete:
 
1553
                if entry[1][0][0] != 'a':
 
1554
                    self._changes_aborted = True
 
1555
                    raise errors.InconsistentDelta(old_path, file_id,
 
1556
                            'This was marked as a real delete, but the WT state'
 
1557
                            ' claims that it still exists and is versioned.')
1846
1558
                del self._dirblocks[block_index][1][entry_index]
1847
 
                if old_kind == 'd':
1848
 
                    # This was a directory, and the active tree says it
1849
 
                    # doesn't exist, and now the basis tree says it doesn't
1850
 
                    # exist. Remove its dirblock if present
1851
 
                    (dir_block_index,
1852
 
                     present) = self._find_block_index_from_key(
1853
 
                        (old_path, '', ''))
1854
 
                    if present:
1855
 
                        dir_block = self._dirblocks[dir_block_index][1]
1856
 
                        if not dir_block:
1857
 
                            # This entry is empty, go ahead and just remove it
1858
 
                            del self._dirblocks[dir_block_index]
1859
1559
            else:
1860
 
                # There is still an active record, so just mark this
1861
 
                # removed.
1862
 
                entry[1][1] = null
1863
 
                block_i, entry_i, d_present, f_present = \
1864
 
                    self._get_block_entry_index(old_path, '', 1)
1865
 
                if d_present:
1866
 
                    dir_block = self._dirblocks[block_i][1]
1867
 
            for child_entry in dir_block:
1868
 
                child_basis_kind = child_entry[1][1][0]
1869
 
                if child_basis_kind not in 'ar':
1870
 
                    self._raise_invalid(old_path, file_id,
1871
 
                        "The file id was deleted but its children were "
1872
 
                        "not deleted.")
1873
 
 
1874
 
    def _after_delta_check_parents(self, parents, index):
1875
 
        """Check that parents required by the delta are all intact.
1876
 
        
1877
 
        :param parents: An iterable of (path_utf8, file_id) tuples which are
1878
 
            required to be present in tree 'index' at path_utf8 with id file_id
1879
 
            and be a directory.
1880
 
        :param index: The column in the dirstate to check for parents in.
1881
 
        """
1882
 
        for dirname_utf8, file_id in parents:
1883
 
            # Get the entry - the ensures that file_id, dirname_utf8 exists and
1884
 
            # has the right file id.
1885
 
            entry = self._get_entry(index, file_id, dirname_utf8)
1886
 
            if entry[1] is None:
1887
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
1888
 
                    file_id, "This parent is not present.")
1889
 
            # Parents of things must be directories
1890
 
            if entry[1][index][0] != 'd':
1891
 
                self._raise_invalid(dirname_utf8.decode('utf8'),
1892
 
                    file_id, "This parent is not a directory.")
 
1560
                if entry[1][0][0] == 'a':
 
1561
                    self._changes_aborted = True
 
1562
                    raise errors.InconsistentDelta(old_path, file_id,
 
1563
                        'The entry was considered a rename, but the source path'
 
1564
                        ' is marked as absent.')
 
1565
                    # For whatever reason, we were asked to rename an entry
 
1566
                    # that was originally marked as deleted. This could be
 
1567
                    # because we are renaming the parent directory, and the WT
 
1568
                    # current state has the file marked as deleted.
 
1569
                elif entry[1][0][0] == 'r':
 
1570
                    # implement the rename
 
1571
                    del self._dirblocks[block_index][1][entry_index]
 
1572
                else:
 
1573
                    # it is being resurrected here, so blank it out temporarily.
 
1574
                    self._dirblocks[block_index][1][entry_index][1][1] = null
1893
1575
 
1894
1576
    def _observed_sha1(self, entry, sha1, stat_value,
1895
1577
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1910
1592
                self._sha_cutoff_time()
1911
1593
            if (stat_value.st_mtime < self._cutoff_time
1912
1594
                and stat_value.st_ctime < self._cutoff_time):
1913
 
                entry[1][0] = ('f', sha1, stat_value.st_size, entry[1][0][3],
1914
 
                               packed_stat)
1915
 
                self._mark_modified([entry])
 
1595
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
 
1596
                    packed_stat)
 
1597
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1916
1598
 
1917
1599
    def _sha_cutoff_time(self):
1918
1600
        """Return cutoff time.
1976
1658
        """Serialise the entire dirstate to a sequence of lines."""
1977
1659
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1978
1660
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1979
 
            # read what's on disk.
 
1661
            # read whats on disk.
1980
1662
            self._state_file.seek(0)
1981
1663
            return self._state_file.readlines()
1982
1664
        lines = []
1983
1665
        lines.append(self._get_parents_line(self.get_parent_ids()))
1984
1666
        lines.append(self._get_ghosts_line(self._ghosts))
1985
 
        lines.extend(self._get_entry_lines())
 
1667
        # append the root line which is special cased
 
1668
        lines.extend(map(self._entry_to_line, self._iter_entries()))
1986
1669
        return self._get_output_lines(lines)
1987
1670
 
1988
1671
    def _get_ghosts_line(self, ghost_ids):
1993
1676
        """Create a line for the state file for parents information."""
1994
1677
        return '\0'.join([str(len(parent_ids))] + parent_ids)
1995
1678
 
1996
 
    def _get_entry_lines(self):
1997
 
        """Create lines for entries."""
1998
 
        return map(self._entry_to_line, self._iter_entries())
1999
 
 
2000
1679
    def _get_fields_to_entry(self):
2001
1680
        """Get a function which converts entry fields into a entry record.
2002
1681
 
2120
1799
            entry_index += 1
2121
1800
        return block_index, entry_index, True, False
2122
1801
 
2123
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
2124
 
                   include_deleted=False):
 
1802
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
2125
1803
        """Get the dirstate entry for path in tree tree_index.
2126
1804
 
2127
1805
        If either file_id or path is supplied, it is used as the key to lookup.
2143
1821
        self._read_dirblocks_if_needed()
2144
1822
        if path_utf8 is not None:
2145
1823
            if type(path_utf8) is not str:
2146
 
                raise errors.BzrError('path_utf8 is not a str: %s %r'
 
1824
                raise AssertionError('path_utf8 is not a str: %s %s'
2147
1825
                    % (type(path_utf8), path_utf8))
2148
1826
            # path lookups are faster
2149
1827
            dirname, basename = osutils.split(path_utf8)
2161
1839
                                          ' tree_index, file_id and path')
2162
1840
            return entry
2163
1841
        else:
2164
 
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1842
            possible_keys = self._get_id_index().get(fileid_utf8, None)
2165
1843
            if not possible_keys:
2166
1844
                return None, None
2167
1845
            for key in possible_keys:
2178
1856
                entry_index, present = self._find_entry_index(key, block)
2179
1857
                if present:
2180
1858
                    entry = self._dirblocks[block_index][1][entry_index]
2181
 
                    # TODO: We might want to assert that entry[0][2] ==
2182
 
                    #       fileid_utf8.
2183
1859
                    if entry[1][tree_index][0] in 'fdlt':
2184
1860
                        # this is the result we are looking for: the
2185
1861
                        # real home of this file_id in this tree.
2269
1945
            executable = False
2270
1946
        else:
2271
1947
            raise Exception("can't pack %s" % inv_entry)
2272
 
        return static_tuple.StaticTuple(minikind, fingerprint, size,
2273
 
                                        executable, tree_data)
 
1948
        return (minikind, fingerprint, size, executable, tree_data)
2274
1949
 
2275
1950
    def _iter_child_entries(self, tree_index, path_utf8):
2276
1951
        """Iterate over all the entries that are children of path_utf.
2325
2000
                yield entry
2326
2001
 
2327
2002
    def _get_id_index(self):
2328
 
        """Get an id index of self._dirblocks.
2329
 
 
2330
 
        This maps from file_id => [(directory, name, file_id)] entries where
2331
 
        that file_id appears in one of the trees.
2332
 
        """
 
2003
        """Get an id index of self._dirblocks."""
2333
2004
        if self._id_index is None:
2334
2005
            id_index = {}
2335
2006
            for key, tree_details in self._iter_entries():
2336
 
                self._add_to_id_index(id_index, key)
 
2007
                id_index.setdefault(key[2], set()).add(key)
2337
2008
            self._id_index = id_index
2338
2009
        return self._id_index
2339
2010
 
2340
 
    def _add_to_id_index(self, id_index, entry_key):
2341
 
        """Add this entry to the _id_index mapping."""
2342
 
        # This code used to use a set for every entry in the id_index. However,
2343
 
        # it is *rare* to have more than one entry. So a set is a large
2344
 
        # overkill. And even when we do, we won't ever have more than the
2345
 
        # number of parent trees. Which is still a small number (rarely >2). As
2346
 
        # such, we use a simple tuple, and do our own uniqueness checks. While
2347
 
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
2348
 
        # cause quadratic failure.
2349
 
        file_id = entry_key[2]
2350
 
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
2351
 
        if file_id not in id_index:
2352
 
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
2353
 
        else:
2354
 
            entry_keys = id_index[file_id]
2355
 
            if entry_key not in entry_keys:
2356
 
                id_index[file_id] = entry_keys + (entry_key,)
2357
 
 
2358
 
    def _remove_from_id_index(self, id_index, entry_key):
2359
 
        """Remove this entry from the _id_index mapping.
2360
 
 
2361
 
        It is an programming error to call this when the entry_key is not
2362
 
        already present.
2363
 
        """
2364
 
        file_id = entry_key[2]
2365
 
        entry_keys = list(id_index[file_id])
2366
 
        entry_keys.remove(entry_key)
2367
 
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
2368
 
 
2369
2011
    def _get_output_lines(self, lines):
2370
2012
        """Format lines for final output.
2371
2013
 
2391
2033
        """The number of parent entries in each record row."""
2392
2034
        return len(self._parents) - len(self._ghosts)
2393
2035
 
2394
 
    @classmethod
2395
 
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
 
2036
    @staticmethod
 
2037
    def on_file(path, sha1_provider=None):
2396
2038
        """Construct a DirState on the file at path "path".
2397
2039
 
2398
2040
        :param path: The path at which the dirstate file on disk should live.
2399
2041
        :param sha1_provider: an object meeting the SHA1Provider interface.
2400
2042
            If None, a DefaultSHA1Provider is used.
2401
 
        :param worth_saving_limit: when the exact number of hash changed
2402
 
            entries is known, only bother saving the dirstate if more than
2403
 
            this count of entries have changed. -1 means never save.
2404
2043
        :return: An unlocked DirState object, associated with the given path.
2405
2044
        """
2406
2045
        if sha1_provider is None:
2407
2046
            sha1_provider = DefaultSHA1Provider()
2408
 
        result = cls(path, sha1_provider,
2409
 
                     worth_saving_limit=worth_saving_limit)
 
2047
        result = DirState(path, sha1_provider)
2410
2048
        return result
2411
2049
 
2412
2050
    def _read_dirblocks_if_needed(self):
2504
2142
            trace.mutter('Not saving DirState because '
2505
2143
                    '_changes_aborted is set.')
2506
2144
            return
2507
 
        # TODO: Since we now distinguish IN_MEMORY_MODIFIED from
2508
 
        #       IN_MEMORY_HASH_MODIFIED, we should only fail quietly if we fail
2509
 
        #       to save an IN_MEMORY_HASH_MODIFIED, and fail *noisily* if we
2510
 
        #       fail to save IN_MEMORY_MODIFIED
2511
 
        if self._worth_saving():
 
2145
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
2146
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2147
 
2512
2148
            grabbed_write_lock = False
2513
2149
            if self._lock_state != 'w':
2514
2150
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2522
2158
                    # We couldn't grab a write lock, so we switch back to a read one
2523
2159
                    return
2524
2160
            try:
2525
 
                lines = self.get_lines()
2526
2161
                self._state_file.seek(0)
2527
 
                self._state_file.writelines(lines)
 
2162
                self._state_file.writelines(self.get_lines())
2528
2163
                self._state_file.truncate()
2529
2164
                self._state_file.flush()
2530
 
                self._mark_unmodified()
 
2165
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2166
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
2531
2167
            finally:
2532
2168
                if grabbed_write_lock:
2533
2169
                    self._lock_token = self._lock_token.restore_read_lock()
2536
2172
                    #       not changed contents. Since restore_read_lock may
2537
2173
                    #       not be an atomic operation.
2538
2174
 
2539
 
    def _worth_saving(self):
2540
 
        """Is it worth saving the dirstate or not?"""
2541
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED
2542
 
            or self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2543
 
            return True
2544
 
        if self._dirblock_state == DirState.IN_MEMORY_HASH_MODIFIED:
2545
 
            if self._worth_saving_limit == -1:
2546
 
                # We never save hash changes when the limit is -1
2547
 
                return False
2548
 
            # If we're using smart saving and only a small number of
2549
 
            # entries have changed their hash, don't bother saving. John has
2550
 
            # suggested using a heuristic here based on the size of the
2551
 
            # changed files and/or tree. For now, we go with a configurable
2552
 
            # number of changes, keeping the calculation time
2553
 
            # as low overhead as possible. (This also keeps all existing
2554
 
            # tests passing as the default is 0, i.e. always save.)
2555
 
            if len(self._known_hash_changes) >= self._worth_saving_limit:
2556
 
                return True
2557
 
        return False
2558
 
 
2559
2175
    def _set_data(self, parent_ids, dirblocks):
2560
2176
        """Set the full dirstate data in memory.
2561
2177
 
2569
2185
        """
2570
2186
        # our memory copy is now authoritative.
2571
2187
        self._dirblocks = dirblocks
2572
 
        self._mark_modified(header_modified=True)
 
2188
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2189
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2573
2190
        self._parents = list(parent_ids)
2574
2191
        self._id_index = None
2575
2192
        self._packed_stat_index = None
2595
2212
        self._make_absent(entry)
2596
2213
        self.update_minimal(('', '', new_id), 'd',
2597
2214
            path_utf8='', packed_stat=entry[1][0][4])
2598
 
        self._mark_modified()
2599
 
        # XXX: This was added by Ian, we need to make sure there
2600
 
        #      are tests for it, because it isn't in bzr.dev TRUNK
2601
 
        #      It looks like the only place it is called is in setting the root
2602
 
        #      id of the tree. So probably we never had an _id_index when we
2603
 
        #      don't even have a root yet.
 
2215
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2604
2216
        if self._id_index is not None:
2605
 
            self._add_to_id_index(self._id_index, entry[0])
 
2217
            self._id_index.setdefault(new_id, set()).add(entry[0])
2606
2218
 
2607
2219
    def set_parent_trees(self, trees, ghosts):
2608
2220
        """Set the parent trees for the dirstate.
2653
2265
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2654
2266
        # how many trees do we end up with
2655
2267
        parent_count = len(parent_trees)
2656
 
        st = static_tuple.StaticTuple
2657
2268
 
2658
2269
        # one: the current tree
2659
2270
        for entry in self._iter_entries():
2662
2273
                continue
2663
2274
            by_path[entry[0]] = [entry[1][0]] + \
2664
2275
                [DirState.NULL_PARENT_DETAILS] * parent_count
2665
 
            # TODO: Possibly inline this, since we know it isn't present yet
2666
 
            #       id_index[entry[0][2]] = (entry[0],)
2667
 
            self._add_to_id_index(id_index, entry[0])
 
2276
            id_index[entry[0][2]] = set([entry[0]])
2668
2277
 
2669
2278
        # now the parent trees:
2670
2279
        for tree_index, tree in enumerate(parent_trees):
2676
2285
            # the suffix is from tree_index+1:parent_count+1.
2677
2286
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2678
2287
            # now stitch in all the entries from this tree
2679
 
            last_dirname = None
2680
 
            for path, entry in tree.iter_entries_by_dir():
 
2288
            for path, entry in tree.inventory.iter_entries_by_dir():
2681
2289
                # here we process each trees details for each item in the tree.
2682
2290
                # we first update any existing entries for the id at other paths,
2683
2291
                # then we either create or update the entry for the id at the
2690
2298
                file_id = entry.file_id
2691
2299
                path_utf8 = path.encode('utf8')
2692
2300
                dirname, basename = osutils.split(path_utf8)
2693
 
                if dirname == last_dirname:
2694
 
                    # Try to re-use objects as much as possible
2695
 
                    dirname = last_dirname
2696
 
                else:
2697
 
                    last_dirname = dirname
2698
 
                new_entry_key = st(dirname, basename, file_id)
 
2301
                new_entry_key = (dirname, basename, file_id)
2699
2302
                # tree index consistency: All other paths for this id in this tree
2700
2303
                # index must point to the correct path.
2701
 
                entry_keys = id_index.get(file_id, ())
2702
 
                for entry_key in entry_keys:
 
2304
                for entry_key in id_index.setdefault(file_id, set()):
2703
2305
                    # TODO:PROFILING: It might be faster to just update
2704
2306
                    # rather than checking if we need to, and then overwrite
2705
2307
                    # the one we are located at.
2708
2310
                        # other trees, so put absent pointers there
2709
2311
                        # This is the vertical axis in the matrix, all pointing
2710
2312
                        # to the real path.
2711
 
                        by_path[entry_key][tree_index] = st('r', path_utf8, 0,
2712
 
                                                            False, '')
2713
 
                # by path consistency: Insert into an existing path record
2714
 
                # (trivial), or add a new one with relocation pointers for the
2715
 
                # other tree indexes.
2716
 
                if new_entry_key in entry_keys:
2717
 
                    # there is already an entry where this data belongs, just
2718
 
                    # insert it.
 
2313
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
2314
                # by path consistency: Insert into an existing path record (trivial), or
 
2315
                # add a new one with relocation pointers for the other tree indexes.
 
2316
                if new_entry_key in id_index[file_id]:
 
2317
                    # there is already an entry where this data belongs, just insert it.
2719
2318
                    by_path[new_entry_key][tree_index] = \
2720
2319
                        self._inv_entry_to_details(entry)
2721
2320
                else:
2725
2324
                    new_details = []
2726
2325
                    for lookup_index in xrange(tree_index):
2727
2326
                        # boundary case: this is the first occurence of file_id
2728
 
                        # so there are no id_indexes, possibly take this out of
 
2327
                        # so there are no id_indexs, possibly take this out of
2729
2328
                        # the loop?
2730
 
                        if not len(entry_keys):
 
2329
                        if not len(id_index[file_id]):
2731
2330
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2732
2331
                        else:
2733
2332
                            # grab any one entry, use it to find the right path.
2734
 
                            a_key = iter(entry_keys).next()
 
2333
                            # TODO: optimise this to reduce memory use in highly
 
2334
                            # fragmented situations by reusing the relocation
 
2335
                            # records.
 
2336
                            a_key = iter(id_index[file_id]).next()
2735
2337
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
2736
 
                                # its a pointer or missing statement, use it as
2737
 
                                # is.
 
2338
                                # its a pointer or missing statement, use it as is.
2738
2339
                                new_details.append(by_path[a_key][lookup_index])
2739
2340
                            else:
2740
2341
                                # we have the right key, make a pointer to it.
2741
2342
                                real_path = ('/'.join(a_key[0:2])).strip('/')
2742
 
                                new_details.append(st('r', real_path, 0, False,
2743
 
                                                      ''))
 
2343
                                new_details.append(('r', real_path, 0, False, ''))
2744
2344
                    new_details.append(self._inv_entry_to_details(entry))
2745
2345
                    new_details.extend(new_location_suffix)
2746
2346
                    by_path[new_entry_key] = new_details
2747
 
                    self._add_to_id_index(id_index, new_entry_key)
 
2347
                    id_index[file_id].add(new_entry_key)
2748
2348
        # --- end generation of full tree mappings
2749
2349
 
2750
2350
        # sort and output all the entries
2752
2352
        self._entries_to_current_state(new_entries)
2753
2353
        self._parents = [rev_id for rev_id, tree in trees]
2754
2354
        self._ghosts = list(ghosts)
2755
 
        self._mark_modified(header_modified=True)
 
2355
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2356
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2756
2357
        self._id_index = id_index
2757
2358
 
2758
2359
    def _sort_entries(self, entry_list):
2762
2363
        try to keep everything in sorted blocks all the time, but sometimes
2763
2364
        it's easier to sort after the fact.
2764
2365
        """
2765
 
        # When sorting, we usually have 10x more entries than directories. (69k
2766
 
        # total entries, 4k directories). So cache the results of splitting.
2767
 
        # Saving time and objects. Also, use StaticTuple to avoid putting all
2768
 
        # of these object into python's garbage collector.
2769
 
        split_dirs = {}
2770
 
        def _key(entry, _split_dirs=split_dirs, _st=static_tuple.StaticTuple):
 
2366
        def _key(entry):
2771
2367
            # sort by: directory parts, file name, file id
2772
 
            dirpath, fname, file_id = entry[0]
2773
 
            try:
2774
 
                split = _split_dirs[dirpath]
2775
 
            except KeyError:
2776
 
                split = _st.from_sequence(dirpath.split('/'))
2777
 
                _split_dirs[dirpath] = split
2778
 
            return _st(split, fname, file_id)
 
2368
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
2779
2369
        return sorted(entry_list, key=_key)
2780
2370
 
2781
2371
    def set_state_from_inventory(self, new_inv):
2789
2379
        if 'evil' in debug.debug_flags:
2790
2380
            trace.mutter_callsite(1,
2791
2381
                "set_state_from_inventory called; please mutate the tree instead")
2792
 
        tracing = 'dirstate' in debug.debug_flags
2793
 
        if tracing:
2794
 
            trace.mutter("set_state_from_inventory trace:")
2795
2382
        self._read_dirblocks_if_needed()
2796
2383
        # sketch:
2797
2384
        # Two iterators: current data and new data, both in dirblock order.
2806
2393
        new_iterator = new_inv.iter_entries_by_dir()
2807
2394
        # we will be modifying the dirstate, so we need a stable iterator. In
2808
2395
        # future we might write one, for now we just clone the state into a
2809
 
        # list using a copy so that we see every original item and don't have
2810
 
        # to adjust the position when items are inserted or deleted in the
2811
 
        # underlying dirstate.
 
2396
        # list - which is a shallow copy.
2812
2397
        old_iterator = iter(list(self._iter_entries()))
2813
2398
        # both must have roots so this is safe:
2814
2399
        current_new = new_iterator.next()
2848
2433
            # we make both end conditions explicit
2849
2434
            if not current_old:
2850
2435
                # old is finished: insert current_new into the state.
2851
 
                if tracing:
2852
 
                    trace.mutter("Appending from new '%s'.",
2853
 
                        new_path_utf8.decode('utf8'))
2854
2436
                self.update_minimal(new_entry_key, current_new_minikind,
2855
2437
                    executable=current_new[1].executable,
2856
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
2857
 
                    fullscan=True)
 
2438
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
2858
2439
                current_new = advance(new_iterator)
2859
2440
            elif not current_new:
2860
2441
                # new is finished
2861
 
                if tracing:
2862
 
                    trace.mutter("Truncating from old '%s/%s'.",
2863
 
                        current_old[0][0].decode('utf8'),
2864
 
                        current_old[0][1].decode('utf8'))
2865
2442
                self._make_absent(current_old)
2866
2443
                current_old = advance(old_iterator)
2867
2444
            elif new_entry_key == current_old[0]:
2874
2451
                # kind has changed.
2875
2452
                if (current_old[1][0][3] != current_new[1].executable or
2876
2453
                    current_old[1][0][0] != current_new_minikind):
2877
 
                    if tracing:
2878
 
                        trace.mutter("Updating in-place change '%s'.",
2879
 
                            new_path_utf8.decode('utf8'))
2880
2454
                    self.update_minimal(current_old[0], current_new_minikind,
2881
2455
                        executable=current_new[1].executable,
2882
 
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
2883
 
                        fullscan=True)
 
2456
                        path_utf8=new_path_utf8, fingerprint=fingerprint)
2884
2457
                # both sides are dealt with, move on
2885
2458
                current_old = advance(old_iterator)
2886
2459
                current_new = advance(new_iterator)
2889
2462
                      and new_entry_key[1:] < current_old[0][1:])):
2890
2463
                # new comes before:
2891
2464
                # add a entry for this and advance new
2892
 
                if tracing:
2893
 
                    trace.mutter("Inserting from new '%s'.",
2894
 
                        new_path_utf8.decode('utf8'))
2895
2465
                self.update_minimal(new_entry_key, current_new_minikind,
2896
2466
                    executable=current_new[1].executable,
2897
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
2898
 
                    fullscan=True)
 
2467
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
2899
2468
                current_new = advance(new_iterator)
2900
2469
            else:
2901
2470
                # we've advanced past the place where the old key would be,
2902
2471
                # without seeing it in the new list.  so it must be gone.
2903
 
                if tracing:
2904
 
                    trace.mutter("Deleting from old '%s/%s'.",
2905
 
                        current_old[0][0].decode('utf8'),
2906
 
                        current_old[0][1].decode('utf8'))
2907
2472
                self._make_absent(current_old)
2908
2473
                current_old = advance(old_iterator)
2909
 
        self._mark_modified()
 
2474
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2910
2475
        self._id_index = None
2911
2476
        self._packed_stat_index = None
2912
 
        if tracing:
2913
 
            trace.mutter("set_state_from_inventory complete.")
2914
 
 
2915
 
    def set_state_from_scratch(self, working_inv, parent_trees, parent_ghosts):
2916
 
        """Wipe the currently stored state and set it to something new.
2917
 
 
2918
 
        This is a hard-reset for the data we are working with.
2919
 
        """
2920
 
        # Technically, we really want a write lock, but until we write, we
2921
 
        # don't really need it.
2922
 
        self._requires_lock()
2923
 
        # root dir and root dir contents with no children. We have to have a
2924
 
        # root for set_state_from_inventory to work correctly.
2925
 
        empty_root = (('', '', inventory.ROOT_ID),
2926
 
                      [('d', '', 0, False, DirState.NULLSTAT)])
2927
 
        empty_tree_dirblocks = [('', [empty_root]), ('', [])]
2928
 
        self._set_data([], empty_tree_dirblocks)
2929
 
        self.set_state_from_inventory(working_inv)
2930
 
        self.set_parent_trees(parent_trees, parent_ghosts)
2931
2477
 
2932
2478
    def _make_absent(self, current_old):
2933
2479
        """Mark current_old - an entry - as absent for tree 0.
2959
2505
            block[1].pop(entry_index)
2960
2506
            # if we have an id_index in use, remove this key from it for this id.
2961
2507
            if self._id_index is not None:
2962
 
                self._remove_from_id_index(self._id_index, current_old[0])
 
2508
                self._id_index[current_old[0][2]].remove(current_old[0])
2963
2509
        # update all remaining keys for this id to record it as absent. The
2964
2510
        # existing details may either be the record we are marking as deleted
2965
2511
        # (if there were other trees with the id present at this path), or may
2978
2524
            if update_tree_details[0][0] == 'a': # absent
2979
2525
                raise AssertionError('bad row %r' % (update_tree_details,))
2980
2526
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2981
 
        self._mark_modified()
 
2527
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2982
2528
        return last_reference
2983
2529
 
2984
2530
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
2985
 
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
 
2531
                       packed_stat=None, size=0, path_utf8=None):
2986
2532
        """Update an entry to the state in tree 0.
2987
2533
 
2988
2534
        This will either create a new entry at 'key' or update an existing one.
2999
2545
        :param size: Size information for new entry
3000
2546
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
3001
2547
                extra computation.
3002
 
        :param fullscan: If True then a complete scan of the dirstate is being
3003
 
            done and checking for duplicate rows should not be done. This
3004
 
            should only be set by set_state_from_inventory and similar methods.
3005
2548
 
3006
2549
        If packed_stat and fingerprint are not given, they're invalidated in
3007
2550
        the entry.
3016
2559
        new_details = (minikind, fingerprint, size, executable, packed_stat)
3017
2560
        id_index = self._get_id_index()
3018
2561
        if not present:
3019
 
            # New record. Check there isn't a entry at this path already.
3020
 
            if not fullscan:
3021
 
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
3022
 
                while low_index < len(block):
3023
 
                    entry = block[low_index]
3024
 
                    if entry[0][0:2] == key[0:2]:
3025
 
                        if entry[1][0][0] not in 'ar':
3026
 
                            # This entry has the same path (but a different id) as
3027
 
                            # the new entry we're adding, and is present in ths
3028
 
                            # tree.
3029
 
                            self._raise_invalid(
3030
 
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
3031
 
                                "Attempt to add item at path already occupied by "
3032
 
                                "id %r" % entry[0][2])
3033
 
                        low_index += 1
3034
 
                    else:
3035
 
                        break
3036
2562
            # new entry, synthesis cross reference here,
3037
 
            existing_keys = id_index.get(key[2], ())
 
2563
            existing_keys = id_index.setdefault(key[2], set())
3038
2564
            if not existing_keys:
3039
2565
                # not currently in the state, simplest case
3040
2566
                new_entry = key, [new_details] + self._empty_parent_info()
3043
2569
                # grab one of them and use it to generate parent
3044
2570
                # relocation/absent entries.
3045
2571
                new_entry = key, [new_details]
3046
 
                # existing_keys can be changed as we iterate.
3047
 
                for other_key in tuple(existing_keys):
 
2572
                for other_key in existing_keys:
3048
2573
                    # change the record at other to be a pointer to this new
3049
2574
                    # record. The loop looks similar to the change to
3050
2575
                    # relocations when updating an existing record but its not:
3051
2576
                    # the test for existing kinds is different: this can be
3052
2577
                    # factored out to a helper though.
3053
 
                    other_block_index, present = self._find_block_index_from_key(
3054
 
                        other_key)
3055
 
                    if not present:
3056
 
                        raise AssertionError('could not find block for %s' % (
3057
 
                            other_key,))
3058
 
                    other_block = self._dirblocks[other_block_index][1]
3059
 
                    other_entry_index, present = self._find_entry_index(
3060
 
                        other_key, other_block)
3061
 
                    if not present:
3062
 
                        raise AssertionError(
3063
 
                            'update_minimal: could not find other entry for %s'
3064
 
                            % (other_key,))
 
2578
                    other_block_index, present = self._find_block_index_from_key(other_key)
 
2579
                    if not present:
 
2580
                        raise AssertionError('could not find block for %s' % (other_key,))
 
2581
                    other_entry_index, present = self._find_entry_index(other_key,
 
2582
                                            self._dirblocks[other_block_index][1])
 
2583
                    if not present:
 
2584
                        raise AssertionError('could not find entry for %s' % (other_key,))
3065
2585
                    if path_utf8 is None:
3066
2586
                        raise AssertionError('no path')
3067
 
                    # Turn this other location into a reference to the new
3068
 
                    # location. This also updates the aliased iterator
3069
 
                    # (current_old in set_state_from_inventory) so that the old
3070
 
                    # entry, if not already examined, is skipped over by that
3071
 
                    # loop.
3072
 
                    other_entry = other_block[other_entry_index]
3073
 
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
3074
 
                    if self._maybe_remove_row(other_block, other_entry_index,
3075
 
                                              id_index):
3076
 
                        # If the row holding this was removed, we need to
3077
 
                        # recompute where this entry goes
3078
 
                        entry_index, _ = self._find_entry_index(key, block)
 
2587
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
 
2588
                        ('r', path_utf8, 0, False, '')
3079
2589
 
3080
 
                # This loop:
3081
 
                # adds a tuple to the new details for each column
3082
 
                #  - either by copying an existing relocation pointer inside that column
3083
 
                #  - or by creating a new pointer to the right row inside that column
3084
2590
                num_present_parents = self._num_present_parents()
3085
 
                if num_present_parents:
3086
 
                    # TODO: This re-evaluates the existing_keys set, do we need
3087
 
                    #       to do that ourselves?
3088
 
                    other_key = list(existing_keys)[0]
3089
2591
                for lookup_index in xrange(1, num_present_parents + 1):
3090
2592
                    # grab any one entry, use it to find the right path.
3091
2593
                    # TODO: optimise this to reduce memory use in highly
3098
2600
                    update_entry_index, present = \
3099
2601
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
3100
2602
                    if not present:
3101
 
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
 
2603
                        raise AssertionError('could not find entry for %s' % (other_key,))
3102
2604
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
3103
2605
                    if update_details[0] in 'ar': # relocated, absent
3104
2606
                        # its a pointer or absent in lookup_index's tree, use
3109
2611
                        pointer_path = osutils.pathjoin(*other_key[0:2])
3110
2612
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
3111
2613
            block.insert(entry_index, new_entry)
3112
 
            self._add_to_id_index(id_index, key)
 
2614
            existing_keys.add(key)
3113
2615
        else:
3114
2616
            # Does the new state matter?
3115
2617
            block[entry_index][1][0] = new_details
3124
2626
            # converted to relocated.
3125
2627
            if path_utf8 is None:
3126
2628
                raise AssertionError('no path')
3127
 
            existing_keys = id_index.get(key[2], ())
3128
 
            if key not in existing_keys:
3129
 
                raise AssertionError('We found the entry in the blocks, but'
3130
 
                    ' the key is not in the id_index.'
3131
 
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
3132
 
            for entry_key in existing_keys:
 
2629
            for entry_key in id_index.setdefault(key[2], set()):
3133
2630
                # TODO:PROFILING: It might be faster to just update
3134
2631
                # rather than checking if we need to, and then overwrite
3135
2632
                # the one we are located at.
3153
2650
            if not present:
3154
2651
                self._dirblocks.insert(block_index, (subdir_key[0], []))
3155
2652
 
3156
 
        self._mark_modified()
3157
 
 
3158
 
    def _maybe_remove_row(self, block, index, id_index):
3159
 
        """Remove index if it is absent or relocated across the row.
3160
 
        
3161
 
        id_index is updated accordingly.
3162
 
        :return: True if we removed the row, False otherwise
3163
 
        """
3164
 
        present_in_row = False
3165
 
        entry = block[index]
3166
 
        for column in entry[1]:
3167
 
            if column[0] not in 'ar':
3168
 
                present_in_row = True
3169
 
                break
3170
 
        if not present_in_row:
3171
 
            block.pop(index)
3172
 
            self._remove_from_id_index(id_index, entry[0])
3173
 
            return True
3174
 
        return False
 
2653
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3175
2654
 
3176
2655
    def _validate(self):
3177
2656
        """Check that invariants on the dirblock are correct.
3312
2791
            if absent_positions == tree_count:
3313
2792
                raise AssertionError(
3314
2793
                    "entry %r has no data for any tree." % (entry,))
3315
 
        if self._id_index is not None:
3316
 
            for file_id, entry_keys in self._id_index.iteritems():
3317
 
                for entry_key in entry_keys:
3318
 
                    if entry_key[2] != file_id:
3319
 
                        raise AssertionError(
3320
 
                            'file_id %r did not match entry key %s'
3321
 
                            % (file_id, entry_key))
3322
 
                if len(entry_keys) != len(set(entry_keys)):
3323
 
                    raise AssertionError(
3324
 
                        'id_index contained non-unique data for %s'
3325
 
                        % (entry_keys,))
3326
2794
 
3327
2795
    def _wipe_state(self):
3328
2796
        """Forget all state information about the dirstate."""
3425
2893
    # If we have gotten this far, that means that we need to actually
3426
2894
    # process this entry.
3427
2895
    link_or_sha1 = None
3428
 
    worth_saving = True
3429
2896
    if minikind == 'f':
3430
2897
        executable = state._is_executable(stat_value.st_mode,
3431
2898
                                         saved_executable)
3447
2914
        else:
3448
2915
            entry[1][0] = ('f', '', stat_value.st_size,
3449
2916
                           executable, DirState.NULLSTAT)
3450
 
            worth_saving = False
3451
2917
    elif minikind == 'd':
3452
2918
        link_or_sha1 = None
3453
2919
        entry[1][0] = ('d', '', 0, False, packed_stat)
3459
2925
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3460
2926
            state._ensure_block(block_index, entry_index,
3461
2927
                               osutils.pathjoin(entry[0][0], entry[0][1]))
3462
 
        else:
3463
 
            worth_saving = False
3464
2928
    elif minikind == 'l':
3465
 
        if saved_minikind == 'l':
3466
 
            worth_saving = False
3467
2929
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3468
2930
        if state._cutoff_time is None:
3469
2931
            state._sha_cutoff_time()
3474
2936
        else:
3475
2937
            entry[1][0] = ('l', '', stat_value.st_size,
3476
2938
                           False, DirState.NULLSTAT)
3477
 
    if worth_saving:
3478
 
        state._mark_modified([entry])
 
2939
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
3479
2940
    return link_or_sha1
 
2941
update_entry = py_update_entry
3480
2942
 
3481
2943
 
3482
2944
class ProcessEntryPython(object):
3483
2945
 
3484
 
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
 
2946
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id", "uninteresting",
3485
2947
        "last_source_parent", "last_target_parent", "include_unchanged",
3486
 
        "partial", "use_filesystem_for_exec", "utf8_decode",
3487
 
        "searched_specific_files", "search_specific_files",
3488
 
        "searched_exact_paths", "search_specific_file_parents", "seen_ids",
3489
 
        "state", "source_index", "target_index", "want_unversioned", "tree"]
 
2948
        "use_filesystem_for_exec", "utf8_decode", "searched_specific_files",
 
2949
        "search_specific_files", "state", "source_index", "target_index",
 
2950
        "want_unversioned", "tree"]
3490
2951
 
3491
2952
    def __init__(self, include_unchanged, use_filesystem_for_exec,
3492
2953
        search_specific_files, state, source_index, target_index,
3493
2954
        want_unversioned, tree):
3494
2955
        self.old_dirname_to_file_id = {}
3495
2956
        self.new_dirname_to_file_id = {}
3496
 
        # Are we doing a partial iter_changes?
3497
 
        self.partial = search_specific_files != set([''])
 
2957
        # Just a sentry, so that _process_entry can say that this
 
2958
        # record is handled, but isn't interesting to process (unchanged)
 
2959
        self.uninteresting = object()
3498
2960
        # Using a list so that we can access the values and change them in
3499
2961
        # nested scope. Each one is [path, file_id, entry]
3500
2962
        self.last_source_parent = [None, None]
3503
2965
        self.use_filesystem_for_exec = use_filesystem_for_exec
3504
2966
        self.utf8_decode = cache_utf8._utf8_decode
3505
2967
        # for all search_indexs in each path at or under each element of
3506
 
        # search_specific_files, if the detail is relocated: add the id, and
3507
 
        # add the relocated path as one to search if its not searched already.
3508
 
        # If the detail is not relocated, add the id.
 
2968
        # search_specific_files, if the detail is relocated: add the id, and add the
 
2969
        # relocated path as one to search if its not searched already. If the
 
2970
        # detail is not relocated, add the id.
3509
2971
        self.searched_specific_files = set()
3510
 
        # When we search exact paths without expanding downwards, we record
3511
 
        # that here.
3512
 
        self.searched_exact_paths = set()
3513
2972
        self.search_specific_files = search_specific_files
3514
 
        # The parents up to the root of the paths we are searching.
3515
 
        # After all normal paths are returned, these specific items are returned.
3516
 
        self.search_specific_file_parents = set()
3517
 
        # The ids we've sent out in the delta.
3518
 
        self.seen_ids = set()
3519
2973
        self.state = state
3520
2974
        self.source_index = source_index
3521
2975
        self.target_index = target_index
3522
 
        if target_index != 0:
3523
 
            # A lot of code in here depends on target_index == 0
3524
 
            raise errors.BzrError('unsupported target index')
3525
2976
        self.want_unversioned = want_unversioned
3526
2977
        self.tree = tree
3527
2978
 
3529
2980
        """Compare an entry and real disk to generate delta information.
3530
2981
 
3531
2982
        :param path_info: top_relpath, basename, kind, lstat, abspath for
3532
 
            the path of entry. If None, then the path is considered absent in 
3533
 
            the target (Perhaps we should pass in a concrete entry for this ?)
 
2983
            the path of entry. If None, then the path is considered absent.
 
2984
            (Perhaps we should pass in a concrete entry for this ?)
3534
2985
            Basename is returned as a utf8 string because we expect this
3535
2986
            tuple will be ignored, and don't want to take the time to
3536
2987
            decode.
3537
 
        :return: (iter_changes_result, changed). If the entry has not been
3538
 
            handled then changed is None. Otherwise it is False if no content
3539
 
            or metadata changes have occurred, and True if any content or
3540
 
            metadata change has occurred. If self.include_unchanged is True then
3541
 
            if changed is not None, iter_changes_result will always be a result
3542
 
            tuple. Otherwise, iter_changes_result is None unless changed is
3543
 
            True.
 
2988
        :return: None if these don't match
 
2989
                 A tuple of information about the change, or
 
2990
                 the object 'uninteresting' if these match, but are
 
2991
                 basically identical.
3544
2992
        """
3545
2993
        if self.source_index is None:
3546
2994
            source_details = DirState.NULL_PARENT_DETAILS
3614
3062
                    if source_minikind != 'f':
3615
3063
                        content_change = True
3616
3064
                    else:
3617
 
                        # Check the sha. We can't just rely on the size as
3618
 
                        # content filtering may mean differ sizes actually
3619
 
                        # map to the same content
3620
 
                        if link_or_sha1 is None:
3621
 
                            # Stat cache miss:
3622
 
                            statvalue, link_or_sha1 = \
3623
 
                                self.state._sha1_provider.stat_and_sha1(
3624
 
                                path_info[4])
3625
 
                            self.state._observed_sha1(entry, link_or_sha1,
3626
 
                                statvalue)
3627
 
                        content_change = (link_or_sha1 != source_details[1])
 
3065
                        # If the size is the same, check the sha:
 
3066
                        if target_details[2] == source_details[2]:
 
3067
                            if link_or_sha1 is None:
 
3068
                                # Stat cache miss:
 
3069
                                statvalue, link_or_sha1 = \
 
3070
                                    self.state._sha1_provider.stat_and_sha1(
 
3071
                                    path_info[4])
 
3072
                                self.state._observed_sha1(entry, link_or_sha1,
 
3073
                                    statvalue)
 
3074
                            content_change = (link_or_sha1 != source_details[1])
 
3075
                        else:
 
3076
                            # Size changed, so must be different
 
3077
                            content_change = True
3628
3078
                    # Target details is updated at update_entry time
3629
3079
                    if self.use_filesystem_for_exec:
3630
3080
                        # We don't need S_ISREG here, because we are sure
3645
3095
                        content_change = False
3646
3096
                    target_exec = False
3647
3097
                else:
3648
 
                    if path is None:
3649
 
                        path = pathjoin(old_dirname, old_basename)
3650
 
                    raise errors.BadFileKindError(path, path_info[2])
 
3098
                    raise Exception, "unknown kind %s" % path_info[2]
3651
3099
            if source_minikind == 'd':
3652
3100
                if path is None:
3653
3101
                    old_path = path = pathjoin(old_dirname, old_basename)
3654
3102
                self.old_dirname_to_file_id[old_path] = file_id
3655
3103
            # parent id is the entry for the path in the target tree
3656
 
            if old_basename and old_dirname == self.last_source_parent[0]:
 
3104
            if old_dirname == self.last_source_parent[0]:
3657
3105
                source_parent_id = self.last_source_parent[1]
3658
3106
            else:
3659
3107
                try:
3669
3117
                    self.last_source_parent[0] = old_dirname
3670
3118
                    self.last_source_parent[1] = source_parent_id
3671
3119
            new_dirname = entry[0][0]
3672
 
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
 
3120
            if new_dirname == self.last_target_parent[0]:
3673
3121
                target_parent_id = self.last_target_parent[1]
3674
3122
            else:
3675
3123
                try:
3692
3140
                    self.last_target_parent[1] = target_parent_id
3693
3141
 
3694
3142
            source_exec = source_details[3]
3695
 
            changed = (content_change
 
3143
            if (self.include_unchanged
 
3144
                or content_change
3696
3145
                or source_parent_id != target_parent_id
3697
3146
                or old_basename != entry[0][1]
3698
3147
                or source_exec != target_exec
3699
 
                )
3700
 
            if not changed and not self.include_unchanged:
3701
 
                return None, False
3702
 
            else:
 
3148
                ):
3703
3149
                if old_path is None:
3704
3150
                    old_path = path = pathjoin(old_dirname, old_basename)
3705
3151
                    old_path_u = self.utf8_decode(old_path)[0]
3718
3164
                       (source_parent_id, target_parent_id),
3719
3165
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3720
3166
                       (source_kind, target_kind),
3721
 
                       (source_exec, target_exec)), changed
 
3167
                       (source_exec, target_exec))
 
3168
            else:
 
3169
                return self.uninteresting
3722
3170
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3723
3171
            # looks like a new file
3724
3172
            path = pathjoin(entry[0][0], entry[0][1])
3745
3193
                       (None, parent_id),
3746
3194
                       (None, self.utf8_decode(entry[0][1])[0]),
3747
3195
                       (None, path_info[2]),
3748
 
                       (None, target_exec)), True
 
3196
                       (None, target_exec))
3749
3197
            else:
3750
3198
                # Its a missing file, report it as such.
3751
3199
                return (entry[0][2],
3755
3203
                       (None, parent_id),
3756
3204
                       (None, self.utf8_decode(entry[0][1])[0]),
3757
3205
                       (None, None),
3758
 
                       (None, False)), True
 
3206
                       (None, False))
3759
3207
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3760
3208
            # unversioned, possibly, or possibly not deleted: we dont care.
3761
3209
            # if its still on disk, *and* theres no other entry at this
3773
3221
                   (parent_id, None),
3774
3222
                   (self.utf8_decode(entry[0][1])[0], None),
3775
3223
                   (DirState._minikind_to_kind[source_minikind], None),
3776
 
                   (source_details[3], None)), True
 
3224
                   (source_details[3], None))
3777
3225
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3778
3226
            # a rename; could be a true rename, or a rename inherited from
3779
3227
            # a renamed parent. TODO: handle this efficiently. Its not
3790
3238
            raise AssertionError("don't know how to compare "
3791
3239
                "source_minikind=%r, target_minikind=%r"
3792
3240
                % (source_minikind, target_minikind))
3793
 
        return None, None
 
3241
            ## import pdb;pdb.set_trace()
 
3242
        return None
3794
3243
 
3795
3244
    def __iter__(self):
3796
3245
        return self
3797
3246
 
3798
 
    def _gather_result_for_consistency(self, result):
3799
 
        """Check a result we will yield to make sure we are consistent later.
3800
 
        
3801
 
        This gathers result's parents into a set to output later.
3802
 
 
3803
 
        :param result: A result tuple.
3804
 
        """
3805
 
        if not self.partial or not result[0]:
3806
 
            return
3807
 
        self.seen_ids.add(result[0])
3808
 
        new_path = result[1][1]
3809
 
        if new_path:
3810
 
            # Not the root and not a delete: queue up the parents of the path.
3811
 
            self.search_specific_file_parents.update(
3812
 
                osutils.parent_directories(new_path.encode('utf8')))
3813
 
            # Add the root directory which parent_directories does not
3814
 
            # provide.
3815
 
            self.search_specific_file_parents.add('')
3816
 
 
3817
3247
    def iter_changes(self):
3818
3248
        """Iterate over the changes."""
3819
3249
        utf8_decode = cache_utf8._utf8_decode
3820
3250
        _cmp_by_dirs = cmp_by_dirs
3821
3251
        _process_entry = self._process_entry
 
3252
        uninteresting = self.uninteresting
3822
3253
        search_specific_files = self.search_specific_files
3823
3254
        searched_specific_files = self.searched_specific_files
3824
3255
        splitpath = osutils.splitpath
3894
3325
                continue
3895
3326
            path_handled = False
3896
3327
            for entry in root_entries:
3897
 
                result, changed = _process_entry(entry, root_dir_info)
3898
 
                if changed is not None:
 
3328
                result = _process_entry(entry, root_dir_info)
 
3329
                if result is not None:
3899
3330
                    path_handled = True
3900
 
                    if changed:
3901
 
                        self._gather_result_for_consistency(result)
3902
 
                    if changed or self.include_unchanged:
 
3331
                    if result is not uninteresting:
3903
3332
                        yield result
3904
3333
            if self.want_unversioned and not path_handled and root_dir_info:
3905
3334
                new_executable = bool(
4015
3444
                        for current_entry in current_block[1]:
4016
3445
                            # entry referring to file not present on disk.
4017
3446
                            # advance the entry only, after processing.
4018
 
                            result, changed = _process_entry(current_entry, None)
4019
 
                            if changed is not None:
4020
 
                                if changed:
4021
 
                                    self._gather_result_for_consistency(result)
4022
 
                                if changed or self.include_unchanged:
 
3447
                            result = _process_entry(current_entry, None)
 
3448
                            if result is not None:
 
3449
                                if result is not uninteresting:
4023
3450
                                    yield result
4024
3451
                        block_index +=1
4025
3452
                        if (block_index < len(self.state._dirblocks) and
4055
3482
                        pass
4056
3483
                    elif current_path_info is None:
4057
3484
                        # no path is fine: the per entry code will handle it.
4058
 
                        result, changed = _process_entry(current_entry, current_path_info)
4059
 
                        if changed is not None:
4060
 
                            if changed:
4061
 
                                self._gather_result_for_consistency(result)
4062
 
                            if changed or self.include_unchanged:
 
3485
                        result = _process_entry(current_entry, current_path_info)
 
3486
                        if result is not None:
 
3487
                            if result is not uninteresting:
4063
3488
                                yield result
4064
3489
                    elif (current_entry[0][1] != current_path_info[1]
4065
3490
                          or current_entry[1][self.target_index][0] in 'ar'):
4078
3503
                        else:
4079
3504
                            # entry referring to file not present on disk.
4080
3505
                            # advance the entry only, after processing.
4081
 
                            result, changed = _process_entry(current_entry, None)
4082
 
                            if changed is not None:
4083
 
                                if changed:
4084
 
                                    self._gather_result_for_consistency(result)
4085
 
                                if changed or self.include_unchanged:
 
3506
                            result = _process_entry(current_entry, None)
 
3507
                            if result is not None:
 
3508
                                if result is not uninteresting:
4086
3509
                                    yield result
4087
3510
                            advance_path = False
4088
3511
                    else:
4089
 
                        result, changed = _process_entry(current_entry, current_path_info)
4090
 
                        if changed is not None:
 
3512
                        result = _process_entry(current_entry, current_path_info)
 
3513
                        if result is not None:
4091
3514
                            path_handled = True
4092
 
                            if changed:
4093
 
                                self._gather_result_for_consistency(result)
4094
 
                            if changed or self.include_unchanged:
 
3515
                            if result is not uninteresting:
4095
3516
                                yield result
4096
3517
                    if advance_entry and current_entry is not None:
4097
3518
                        entry_index += 1
4156
3577
                        current_dir_info = dir_iterator.next()
4157
3578
                    except StopIteration:
4158
3579
                        current_dir_info = None
4159
 
        for result in self._iter_specific_file_parents():
4160
 
            yield result
4161
 
 
4162
 
    def _iter_specific_file_parents(self):
4163
 
        """Iter over the specific file parents."""
4164
 
        while self.search_specific_file_parents:
4165
 
            # Process the parent directories for the paths we were iterating.
4166
 
            # Even in extremely large trees this should be modest, so currently
4167
 
            # no attempt is made to optimise.
4168
 
            path_utf8 = self.search_specific_file_parents.pop()
4169
 
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
4170
 
                # We've examined this path.
4171
 
                continue
4172
 
            if path_utf8 in self.searched_exact_paths:
4173
 
                # We've examined this path.
4174
 
                continue
4175
 
            path_entries = self.state._entries_for_path(path_utf8)
4176
 
            # We need either one or two entries. If the path in
4177
 
            # self.target_index has moved (so the entry in source_index is in
4178
 
            # 'ar') then we need to also look for the entry for this path in
4179
 
            # self.source_index, to output the appropriate delete-or-rename.
4180
 
            selected_entries = []
4181
 
            found_item = False
4182
 
            for candidate_entry in path_entries:
4183
 
                # Find entries present in target at this path:
4184
 
                if candidate_entry[1][self.target_index][0] not in 'ar':
4185
 
                    found_item = True
4186
 
                    selected_entries.append(candidate_entry)
4187
 
                # Find entries present in source at this path:
4188
 
                elif (self.source_index is not None and
4189
 
                    candidate_entry[1][self.source_index][0] not in 'ar'):
4190
 
                    found_item = True
4191
 
                    if candidate_entry[1][self.target_index][0] == 'a':
4192
 
                        # Deleted, emit it here.
4193
 
                        selected_entries.append(candidate_entry)
4194
 
                    else:
4195
 
                        # renamed, emit it when we process the directory it
4196
 
                        # ended up at.
4197
 
                        self.search_specific_file_parents.add(
4198
 
                            candidate_entry[1][self.target_index][1])
4199
 
            if not found_item:
4200
 
                raise AssertionError(
4201
 
                    "Missing entry for specific path parent %r, %r" % (
4202
 
                    path_utf8, path_entries))
4203
 
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
4204
 
            for entry in selected_entries:
4205
 
                if entry[0][2] in self.seen_ids:
4206
 
                    continue
4207
 
                result, changed = self._process_entry(entry, path_info)
4208
 
                if changed is None:
4209
 
                    raise AssertionError(
4210
 
                        "Got entry<->path mismatch for specific path "
4211
 
                        "%r entry %r path_info %r " % (
4212
 
                        path_utf8, entry, path_info))
4213
 
                # Only include changes - we're outside the users requested
4214
 
                # expansion.
4215
 
                if changed:
4216
 
                    self._gather_result_for_consistency(result)
4217
 
                    if (result[6][0] == 'directory' and
4218
 
                        result[6][1] != 'directory'):
4219
 
                        # This stopped being a directory, the old children have
4220
 
                        # to be included.
4221
 
                        if entry[1][self.source_index][0] == 'r':
4222
 
                            # renamed, take the source path
4223
 
                            entry_path_utf8 = entry[1][self.source_index][1]
4224
 
                        else:
4225
 
                            entry_path_utf8 = path_utf8
4226
 
                        initial_key = (entry_path_utf8, '', '')
4227
 
                        block_index, _ = self.state._find_block_index_from_key(
4228
 
                            initial_key)
4229
 
                        if block_index == 0:
4230
 
                            # The children of the root are in block index 1.
4231
 
                            block_index +=1
4232
 
                        current_block = None
4233
 
                        if block_index < len(self.state._dirblocks):
4234
 
                            current_block = self.state._dirblocks[block_index]
4235
 
                            if not osutils.is_inside(
4236
 
                                entry_path_utf8, current_block[0]):
4237
 
                                # No entries for this directory at all.
4238
 
                                current_block = None
4239
 
                        if current_block is not None:
4240
 
                            for entry in current_block[1]:
4241
 
                                if entry[1][self.source_index][0] in 'ar':
4242
 
                                    # Not in the source tree, so doesn't have to be
4243
 
                                    # included.
4244
 
                                    continue
4245
 
                                # Path of the entry itself.
4246
 
 
4247
 
                                self.search_specific_file_parents.add(
4248
 
                                    osutils.pathjoin(*entry[0][:2]))
4249
 
                if changed or self.include_unchanged:
4250
 
                    yield result
4251
 
            self.searched_exact_paths.add(path_utf8)
4252
 
 
4253
 
    def _path_info(self, utf8_path, unicode_path):
4254
 
        """Generate path_info for unicode_path.
4255
 
 
4256
 
        :return: None if unicode_path does not exist, or a path_info tuple.
4257
 
        """
4258
 
        abspath = self.tree.abspath(unicode_path)
4259
 
        try:
4260
 
            stat = os.lstat(abspath)
4261
 
        except OSError, e:
4262
 
            if e.errno == errno.ENOENT:
4263
 
                # the path does not exist.
4264
 
                return None
4265
 
            else:
4266
 
                raise
4267
 
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
4268
 
        dir_info = (utf8_path, utf8_basename,
4269
 
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
4270
 
            abspath)
4271
 
        if dir_info[2] == 'directory':
4272
 
            if self.tree._directory_is_tree_reference(
4273
 
                unicode_path):
4274
 
                self.root_dir_info = self.root_dir_info[:2] + \
4275
 
                    ('tree-reference',) + self.root_dir_info[3:]
4276
 
        return dir_info
 
3580
_process_entry = ProcessEntryPython
4277
3581
 
4278
3582
 
4279
3583
# Try to load the compiled form if possible
4280
3584
try:
4281
 
    from bzrlib._dirstate_helpers_pyx import (
4282
 
        _read_dirblocks,
4283
 
        bisect_dirblock,
4284
 
        _bisect_path_left,
4285
 
        _bisect_path_right,
4286
 
        cmp_by_dirs,
 
3585
    from bzrlib._dirstate_helpers_c import (
 
3586
        _read_dirblocks_c as _read_dirblocks,
 
3587
        bisect_dirblock_c as bisect_dirblock,
 
3588
        _bisect_path_left_c as _bisect_path_left,
 
3589
        _bisect_path_right_c as _bisect_path_right,
 
3590
        cmp_by_dirs_c as cmp_by_dirs,
4287
3591
        ProcessEntryC as _process_entry,
4288
3592
        update_entry as update_entry,
4289
3593
        )
4290
 
except ImportError, e:
4291
 
    osutils.failed_to_load_extension(e)
 
3594
except ImportError:
4292
3595
    from bzrlib._dirstate_helpers_py import (
4293
 
        _read_dirblocks,
4294
 
        bisect_dirblock,
4295
 
        _bisect_path_left,
4296
 
        _bisect_path_right,
4297
 
        cmp_by_dirs,
 
3596
        _read_dirblocks_py as _read_dirblocks,
 
3597
        bisect_dirblock_py as bisect_dirblock,
 
3598
        _bisect_path_left_py as _bisect_path_left,
 
3599
        _bisect_path_right_py as _bisect_path_right,
 
3600
        cmp_by_dirs_py as cmp_by_dirs,
4298
3601
        )
4299
 
    # FIXME: It would be nice to be able to track moved lines so that the
4300
 
    # corresponding python code can be moved to the _dirstate_helpers_py
4301
 
    # module. I don't want to break the history for this important piece of
4302
 
    # code so I left the code here -- vila 20090622
4303
 
    update_entry = py_update_entry
4304
 
    _process_entry = ProcessEntryPython