~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: Robert Collins
  • Author(s): Vincent Ladeuil
  • Date: 2009-04-07 07:20:17 UTC
  • mto: This revision was merged to the branch mainline in revision 4262.
  • Revision ID: robertc@robertcollins.net-20090407072017-rxvtpahno3yfb52e
Add InterCHKRevisionTree

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
 
299
269
    def sha1(self, abspath):
300
 
        """Return the sha1 of a file given its absolute path.
301
 
 
302
 
        :param abspath:  May be a filesystem encoded absolute path
303
 
             or a unicode path.
304
 
        """
 
270
        """Return the sha1 of a file given its absolute path."""
305
271
        raise NotImplementedError(self.sha1)
306
272
 
307
273
    def stat_and_sha1(self, abspath):
308
274
        """Return the stat and sha1 of a file given its absolute path.
309
275
        
310
 
        :param abspath:  May be a filesystem encoded absolute path
311
 
             or a unicode path.
312
 
 
313
276
        Note: the stat should be the stat of the physical file
314
277
        while the sha may be the sha of its canonical content.
315
278
        """
383
346
    NOT_IN_MEMORY = 0
384
347
    IN_MEMORY_UNMODIFIED = 1
385
348
    IN_MEMORY_MODIFIED = 2
386
 
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
387
349
 
388
350
    # A pack_stat (the x's) that is just noise and will never match the output
389
351
    # of base64 encode.
390
352
    NULLSTAT = 'x' * 32
391
 
    NULL_PARENT_DETAILS = static_tuple.StaticTuple('a', '', 0, False, '')
 
353
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
392
354
 
393
355
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
394
356
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
395
357
 
396
 
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
 
358
    def __init__(self, path, sha1_provider):
397
359
        """Create a  DirState object.
398
360
 
399
361
        :param path: The path at which the dirstate file on disk should live.
400
362
        :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
363
        """
406
364
        # _header_state and _dirblock_state represent the current state
407
365
        # of the dirstate metadata and the per-row data respectiely.
444
402
        # during commit.
445
403
        self._last_block_index = None
446
404
        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
405
 
452
406
    def __repr__(self):
453
407
        return "%s(%r)" % \
454
408
            (self.__class__.__name__, self._filename)
455
409
 
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
410
    def add(self, path, file_id, kind, stat, fingerprint):
488
411
        """Add a path to be tracked.
489
412
 
615
538
        if kind == 'directory':
616
539
           # insert a new dirblock
617
540
           self._ensure_block(block_index, entry_index, utf8path)
618
 
        self._mark_modified()
 
541
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
619
542
        if self._id_index:
620
 
            self._add_to_id_index(self._id_index, entry_key)
 
543
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
621
544
 
622
545
    def _bisect(self, paths):
623
546
        """Bisect through the disk structure for specific rows.
1087
1010
 
1088
1011
        self._ghosts = []
1089
1012
        self._parents = [parents[0]]
1090
 
        self._mark_modified(header_modified=True)
 
1013
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1014
        self._header_state = DirState.IN_MEMORY_MODIFIED
1091
1015
 
1092
1016
    def _empty_parent_info(self):
1093
1017
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1222
1146
    def _fields_per_entry(self):
1223
1147
        """How many null separated fields should be in each entry row.
1224
1148
 
1225
 
        Each line now has an extra '\\n' field which is not used
 
1149
        Each line now has an extra '\n' field which is not used
1226
1150
        so we just skip over it
1227
 
 
1228
 
        entry size::
 
1151
        entry size:
1229
1152
            3 fields for the key
1230
1153
            + number of fields per tree_data (5) * tree count
1231
1154
            + newline
1344
1267
            raise
1345
1268
        return result
1346
1269
 
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
1270
    def update_by_delta(self, delta):
1356
1271
        """Apply an inventory delta to the dirstate for tree 0
1357
1272
 
1358
 
        This is the workhorse for apply_inventory_delta in dirstate based
1359
 
        trees.
1360
 
 
1361
1273
        :param delta: An inventory delta.  See Inventory.apply_delta for
1362
1274
            details.
1363
1275
        """
1364
1276
        self._read_dirblocks_if_needed()
1365
 
        encode = cache_utf8.encode
1366
1277
        insertions = {}
1367
1278
        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:
 
1279
        for old_path, new_path, file_id, inv_entry in sorted(delta, reverse=True):
1380
1280
            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")
 
1281
                raise AssertionError("repeated file id in delta %r" % (file_id,))
1383
1282
            if old_path is not None:
1384
1283
                old_path = old_path.encode('utf-8')
1385
1284
                removals[file_id] = old_path
1386
 
            else:
1387
 
                new_ids.add(file_id)
1388
1285
            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
1286
                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)
 
1287
                dirname, basename = osutils.split(new_path)
 
1288
                key = (dirname, basename, file_id)
1397
1289
                minikind = DirState._kind_to_minikind[inv_entry.kind]
1398
1290
                if minikind == 't':
1399
 
                    fingerprint = inv_entry.reference_revision or ''
 
1291
                    fingerprint = inv_entry.reference_revision
1400
1292
                else:
1401
1293
                    fingerprint = ''
1402
1294
                insertions[file_id] = (key, minikind, inv_entry.executable,
1411
1303
                    minikind = child[1][0][0]
1412
1304
                    fingerprint = child[1][0][4]
1413
1305
                    executable = child[1][0][3]
1414
 
                    old_child_path = osutils.pathjoin(child_dirname,
1415
 
                                                      child_basename)
 
1306
                    old_child_path = osutils.pathjoin(child[0][0],
 
1307
                                                      child[0][1])
1416
1308
                    removals[child[0][2]] = old_child_path
1417
1309
                    child_suffix = child_dirname[len(old_path):]
1418
1310
                    new_child_dirname = (new_path + child_suffix)
1419
1311
                    key = (new_child_dirname, child_basename, child[0][2])
1420
 
                    new_child_path = osutils.pathjoin(new_child_dirname,
1421
 
                                                      child_basename)
 
1312
                    new_child_path = os.path.join(new_child_dirname,
 
1313
                                                  child_basename)
1422
1314
                    insertions[child[0][2]] = (key, minikind, executable,
1423
1315
                                               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,))
 
1316
        self._apply_removals(removals.values())
 
1317
        self._apply_insertions(insertions.values())
1439
1318
 
1440
1319
    def _apply_removals(self, removals):
1441
 
        for file_id, path in sorted(removals, reverse=True,
1442
 
            key=operator.itemgetter(1)):
 
1320
        for path in sorted(removals, reverse=True):
1443
1321
            dirname, basename = osutils.split(path)
1444
1322
            block_i, entry_i, d_present, f_present = \
1445
1323
                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])
 
1324
            entry = self._dirblocks[block_i][1][entry_i]
1458
1325
            self._make_absent(entry)
1459
1326
            # See if we have a malformed delta: deleting a directory must not
1460
1327
            # leave crud behind. This increases the number of bisects needed
1468
1335
                # be due to it being in a parent tree, or a corrupt delta.
1469
1336
                for child_entry in self._dirblocks[block_i][1]:
1470
1337
                    if child_entry[1][0][0] not in ('r', 'a'):
1471
 
                        self._raise_invalid(path, entry[0][2],
 
1338
                        raise errors.InconsistentDelta(path, entry[0][2],
1472
1339
                            "The file id was deleted but its children were "
1473
1340
                            "not deleted.")
1474
1341
 
1475
1342
    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")
 
1343
        for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
 
1344
            self.update_minimal(key, minikind, executable, fingerprint,
 
1345
                                path_utf8=path_utf8)
1483
1346
 
1484
1347
    def update_basis_by_delta(self, delta, new_revid):
1485
1348
        """Update the parents of this tree after a commit.
1492
1355
        Note that an exception during the operation of this method will leave
1493
1356
        the dirstate in a corrupt state where it should not be saved.
1494
1357
 
 
1358
        Finally, we expect all changes to be synchronising the basis tree with
 
1359
        the working tree.
 
1360
 
1495
1361
        :param new_revid: The new revision id for the trees parent.
1496
1362
        :param delta: An inventory delta (see apply_inventory_delta) describing
1497
1363
            the changes from the current left most parent revision to new_revid.
1509
1375
 
1510
1376
        self._parents[0] = new_revid
1511
1377
 
1512
 
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
 
1378
        delta = sorted(delta, reverse=True)
1513
1379
        adds = []
1514
1380
        changes = []
1515
1381
        deletes = []
1526
1392
        # At the same time, to reduce interface friction we convert the input
1527
1393
        # inventory entries to dirstate.
1528
1394
        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
1395
        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,
 
1396
            if old_path is None:
 
1397
                adds.append((None, encode(new_path), file_id,
1558
1398
                    inv_to_entry(inv_entry), True))
1559
 
                new_ids.add(file_id)
1560
1399
            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:
 
1400
                deletes.append((encode(old_path), None, file_id, None, True))
 
1401
            elif (old_path, new_path) != root_only:
1574
1402
                # Renames:
1575
1403
                # Because renames must preserve their children we must have
1576
1404
                # processed all relocations and removes before hand. The sort
1585
1413
                # for 'r' items on every pass.
1586
1414
                self._update_basis_apply_deletes(deletes)
1587
1415
                deletes = []
 
1416
                new_path_utf8 = encode(new_path)
1588
1417
                # 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))
 
1418
                adds.append((None, new_path_utf8, file_id,
 
1419
                    inv_to_entry(inv_entry), False))
1591
1420
                # Expunge deletes that we've seen so that deleted/renamed
1592
1421
                # children of a rename directory are handled correctly.
1593
 
                new_deletes = reversed(list(
1594
 
                    self._iter_child_entries(1, old_path_utf8)))
 
1422
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1423
                    encode(old_path))))
1595
1424
                # Remove the current contents of the tree at orig_path, and
1596
1425
                # reinsert at the correct new path.
1597
1426
                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
 
1427
                    if entry[0][0]:
 
1428
                        source_path = entry[0][0] + '/' + entry[0][1]
1601
1429
                    else:
1602
 
                        source_path = child_basename
 
1430
                        source_path = entry[0][1]
1603
1431
                    if new_path_utf8:
1604
1432
                        target_path = new_path_utf8 + source_path[len(old_path):]
1605
1433
                    else:
1606
1434
                        if old_path == '':
1607
1435
                            raise AssertionError("cannot rename directory to"
1608
 
                                                 " itself")
 
1436
                                " itself")
1609
1437
                        target_path = source_path[len(old_path) + 1:]
1610
1438
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1611
1439
                    deletes.append(
1612
1440
                        (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)
 
1441
                deletes.append(
 
1442
                    (encode(old_path), new_path, file_id, None, False))
 
1443
            else:
 
1444
                # changes to just the root should not require remove/insertion
 
1445
                # of everything.
 
1446
                changes.append((encode(old_path), encode(new_path), file_id,
 
1447
                    inv_to_entry(inv_entry)))
 
1448
 
 
1449
        # Finish expunging deletes/first half of renames.
 
1450
        self._update_basis_apply_deletes(deletes)
 
1451
        # Reinstate second half of renames and new paths.
 
1452
        self._update_basis_apply_adds(adds)
 
1453
        # Apply in-situ changes.
 
1454
        self._update_basis_apply_changes(changes)
 
1455
 
 
1456
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1457
        self._header_state = DirState.IN_MEMORY_MODIFIED
1635
1458
        self._id_index = None
1636
1459
        return
1637
1460
 
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
1461
    def _update_basis_apply_adds(self, adds):
1663
1462
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1664
1463
 
1672
1471
        """
1673
1472
        # Adds are accumulated partly from renames, so can be in any input
1674
1473
        # 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])
 
1474
        adds.sort()
1679
1475
        # adds is now in lexographic order, which places all parents before
1680
1476
        # their children, so we can process it linearly.
1681
1477
        absent = 'ar'
1682
 
        st = static_tuple.StaticTuple
1683
1478
        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)
 
1479
            # the entry for this file_id must be in tree 0.
 
1480
            entry = self._get_entry(0, file_id, new_path)
 
1481
            if entry[0] is None or entry[0][2] != file_id:
 
1482
                self._changes_aborted = True
 
1483
                raise errors.InconsistentDelta(new_path, file_id,
 
1484
                    'working tree does not contain new entry')
 
1485
            if real_add and entry[1][1][0] not in absent:
 
1486
                self._changes_aborted = True
 
1487
                raise errors.InconsistentDelta(new_path, file_id,
 
1488
                    'The entry was considered to be a genuinely new record,'
 
1489
                    ' but there was already an old record for it.')
 
1490
            # We don't need to update the target of an 'r' because the handling
 
1491
            # of renames turns all 'r' situations into a delete at the original
 
1492
            # location.
 
1493
            entry[1][1] = new_details
1781
1494
 
1782
1495
    def _update_basis_apply_changes(self, changes):
1783
1496
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1788
1501
        absent = 'ar'
1789
1502
        for old_path, new_path, file_id, new_details in changes:
1790
1503
            # 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')
 
1504
            entry = self._get_entry(0, file_id, new_path)
 
1505
            if entry[0] is None or entry[0][2] != file_id:
 
1506
                self._changes_aborted = True
 
1507
                raise errors.InconsistentDelta(new_path, file_id,
 
1508
                    'working tree does not contain new entry')
 
1509
            if (entry[1][0][0] in absent or
 
1510
                entry[1][1][0] in absent):
 
1511
                self._changes_aborted = True
 
1512
                raise errors.InconsistentDelta(new_path, file_id,
 
1513
                    'changed considered absent')
1795
1514
            entry[1][1] = new_details
1796
1515
 
1797
1516
    def _update_basis_apply_deletes(self, deletes):
1809
1528
        null = DirState.NULL_PARENT_DETAILS
1810
1529
        for old_path, new_path, file_id, _, real_delete in deletes:
1811
1530
            if real_delete != (new_path is None):
1812
 
                self._raise_invalid(old_path, file_id, "bad delete delta")
 
1531
                raise AssertionError("bad delete delta")
1813
1532
            # the entry for this file_id must be in tree 1.
1814
1533
            dirname, basename = osutils.split(old_path)
1815
1534
            block_index, entry_index, dir_present, file_present = \
1816
1535
                self._get_block_entry_index(dirname, basename, 1)
1817
1536
            if not file_present:
1818
 
                self._raise_invalid(old_path, file_id,
 
1537
                self._changes_aborted = True
 
1538
                raise errors.InconsistentDelta(old_path, file_id,
1819
1539
                    'basis tree does not contain removed entry')
1820
1540
            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
1541
            if entry[0][2] != file_id:
1824
 
                self._raise_invalid(old_path, file_id,
 
1542
                self._changes_aborted = True
 
1543
                raise errors.InconsistentDelta(old_path, file_id,
1825
1544
                    '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
 
1545
            if real_delete:
 
1546
                if entry[1][0][0] != 'a':
 
1547
                    self._changes_aborted = True
 
1548
                    raise errors.InconsistentDelta(old_path, file_id,
 
1549
                            'This was marked as a real delete, but the WT state'
 
1550
                            ' claims that it still exists and is versioned.')
1846
1551
                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
1552
            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.")
 
1553
                if entry[1][0][0] == 'a':
 
1554
                    self._changes_aborted = True
 
1555
                    raise errors.InconsistentDelta(old_path, file_id,
 
1556
                        'The entry was considered a rename, but the source path'
 
1557
                        ' is marked as absent.')
 
1558
                    # For whatever reason, we were asked to rename an entry
 
1559
                    # that was originally marked as deleted. This could be
 
1560
                    # because we are renaming the parent directory, and the WT
 
1561
                    # current state has the file marked as deleted.
 
1562
                elif entry[1][0][0] == 'r':
 
1563
                    # implement the rename
 
1564
                    del self._dirblocks[block_index][1][entry_index]
 
1565
                else:
 
1566
                    # it is being resurrected here, so blank it out temporarily.
 
1567
                    self._dirblocks[block_index][1][entry_index][1][1] = null
1893
1568
 
1894
1569
    def _observed_sha1(self, entry, sha1, stat_value,
1895
1570
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
1910
1585
                self._sha_cutoff_time()
1911
1586
            if (stat_value.st_mtime < self._cutoff_time
1912
1587
                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])
 
1588
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
 
1589
                    packed_stat)
 
1590
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1916
1591
 
1917
1592
    def _sha_cutoff_time(self):
1918
1593
        """Return cutoff time.
1976
1651
        """Serialise the entire dirstate to a sequence of lines."""
1977
1652
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1978
1653
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1979
 
            # read what's on disk.
 
1654
            # read whats on disk.
1980
1655
            self._state_file.seek(0)
1981
1656
            return self._state_file.readlines()
1982
1657
        lines = []
1983
1658
        lines.append(self._get_parents_line(self.get_parent_ids()))
1984
1659
        lines.append(self._get_ghosts_line(self._ghosts))
1985
 
        lines.extend(self._get_entry_lines())
 
1660
        # append the root line which is special cased
 
1661
        lines.extend(map(self._entry_to_line, self._iter_entries()))
1986
1662
        return self._get_output_lines(lines)
1987
1663
 
1988
1664
    def _get_ghosts_line(self, ghost_ids):
1993
1669
        """Create a line for the state file for parents information."""
1994
1670
        return '\0'.join([str(len(parent_ids))] + parent_ids)
1995
1671
 
1996
 
    def _get_entry_lines(self):
1997
 
        """Create lines for entries."""
1998
 
        return map(self._entry_to_line, self._iter_entries())
1999
 
 
2000
1672
    def _get_fields_to_entry(self):
2001
1673
        """Get a function which converts entry fields into a entry record.
2002
1674
 
2120
1792
            entry_index += 1
2121
1793
        return block_index, entry_index, True, False
2122
1794
 
2123
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
2124
 
                   include_deleted=False):
 
1795
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
2125
1796
        """Get the dirstate entry for path in tree tree_index.
2126
1797
 
2127
1798
        If either file_id or path is supplied, it is used as the key to lookup.
2143
1814
        self._read_dirblocks_if_needed()
2144
1815
        if path_utf8 is not None:
2145
1816
            if type(path_utf8) is not str:
2146
 
                raise errors.BzrError('path_utf8 is not a str: %s %r'
 
1817
                raise AssertionError('path_utf8 is not a str: %s %s'
2147
1818
                    % (type(path_utf8), path_utf8))
2148
1819
            # path lookups are faster
2149
1820
            dirname, basename = osutils.split(path_utf8)
2161
1832
                                          ' tree_index, file_id and path')
2162
1833
            return entry
2163
1834
        else:
2164
 
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1835
            possible_keys = self._get_id_index().get(fileid_utf8, None)
2165
1836
            if not possible_keys:
2166
1837
                return None, None
2167
1838
            for key in possible_keys:
2178
1849
                entry_index, present = self._find_entry_index(key, block)
2179
1850
                if present:
2180
1851
                    entry = self._dirblocks[block_index][1][entry_index]
2181
 
                    # TODO: We might want to assert that entry[0][2] ==
2182
 
                    #       fileid_utf8.
2183
1852
                    if entry[1][tree_index][0] in 'fdlt':
2184
1853
                        # this is the result we are looking for: the
2185
1854
                        # real home of this file_id in this tree.
2269
1938
            executable = False
2270
1939
        else:
2271
1940
            raise Exception("can't pack %s" % inv_entry)
2272
 
        return static_tuple.StaticTuple(minikind, fingerprint, size,
2273
 
                                        executable, tree_data)
 
1941
        return (minikind, fingerprint, size, executable, tree_data)
2274
1942
 
2275
1943
    def _iter_child_entries(self, tree_index, path_utf8):
2276
1944
        """Iterate over all the entries that are children of path_utf.
2325
1993
                yield entry
2326
1994
 
2327
1995
    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
 
        """
 
1996
        """Get an id index of self._dirblocks."""
2333
1997
        if self._id_index is None:
2334
1998
            id_index = {}
2335
1999
            for key, tree_details in self._iter_entries():
2336
 
                self._add_to_id_index(id_index, key)
 
2000
                id_index.setdefault(key[2], set()).add(key)
2337
2001
            self._id_index = id_index
2338
2002
        return self._id_index
2339
2003
 
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
2004
    def _get_output_lines(self, lines):
2370
2005
        """Format lines for final output.
2371
2006
 
2391
2026
        """The number of parent entries in each record row."""
2392
2027
        return len(self._parents) - len(self._ghosts)
2393
2028
 
2394
 
    @classmethod
2395
 
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
 
2029
    @staticmethod
 
2030
    def on_file(path, sha1_provider=None):
2396
2031
        """Construct a DirState on the file at path "path".
2397
2032
 
2398
2033
        :param path: The path at which the dirstate file on disk should live.
2399
2034
        :param sha1_provider: an object meeting the SHA1Provider interface.
2400
2035
            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
2036
        :return: An unlocked DirState object, associated with the given path.
2405
2037
        """
2406
2038
        if sha1_provider is None:
2407
2039
            sha1_provider = DefaultSHA1Provider()
2408
 
        result = cls(path, sha1_provider,
2409
 
                     worth_saving_limit=worth_saving_limit)
 
2040
        result = DirState(path, sha1_provider)
2410
2041
        return result
2411
2042
 
2412
2043
    def _read_dirblocks_if_needed(self):
2504
2135
            trace.mutter('Not saving DirState because '
2505
2136
                    '_changes_aborted is set.')
2506
2137
            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():
 
2138
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
2139
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
2140
 
2512
2141
            grabbed_write_lock = False
2513
2142
            if self._lock_state != 'w':
2514
2143
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2522
2151
                    # We couldn't grab a write lock, so we switch back to a read one
2523
2152
                    return
2524
2153
            try:
2525
 
                lines = self.get_lines()
2526
2154
                self._state_file.seek(0)
2527
 
                self._state_file.writelines(lines)
 
2155
                self._state_file.writelines(self.get_lines())
2528
2156
                self._state_file.truncate()
2529
2157
                self._state_file.flush()
2530
 
                self._mark_unmodified()
 
2158
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2159
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
2531
2160
            finally:
2532
2161
                if grabbed_write_lock:
2533
2162
                    self._lock_token = self._lock_token.restore_read_lock()
2536
2165
                    #       not changed contents. Since restore_read_lock may
2537
2166
                    #       not be an atomic operation.
2538
2167
 
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
2168
    def _set_data(self, parent_ids, dirblocks):
2560
2169
        """Set the full dirstate data in memory.
2561
2170
 
2569
2178
        """
2570
2179
        # our memory copy is now authoritative.
2571
2180
        self._dirblocks = dirblocks
2572
 
        self._mark_modified(header_modified=True)
 
2181
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2182
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2573
2183
        self._parents = list(parent_ids)
2574
2184
        self._id_index = None
2575
2185
        self._packed_stat_index = None
2595
2205
        self._make_absent(entry)
2596
2206
        self.update_minimal(('', '', new_id), 'd',
2597
2207
            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.
 
2208
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2604
2209
        if self._id_index is not None:
2605
 
            self._add_to_id_index(self._id_index, entry[0])
 
2210
            self._id_index.setdefault(new_id, set()).add(entry[0])
2606
2211
 
2607
2212
    def set_parent_trees(self, trees, ghosts):
2608
2213
        """Set the parent trees for the dirstate.
2653
2258
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2654
2259
        # how many trees do we end up with
2655
2260
        parent_count = len(parent_trees)
2656
 
        st = static_tuple.StaticTuple
2657
2261
 
2658
2262
        # one: the current tree
2659
2263
        for entry in self._iter_entries():
2662
2266
                continue
2663
2267
            by_path[entry[0]] = [entry[1][0]] + \
2664
2268
                [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])
 
2269
            id_index[entry[0][2]] = set([entry[0]])
2668
2270
 
2669
2271
        # now the parent trees:
2670
2272
        for tree_index, tree in enumerate(parent_trees):
2676
2278
            # the suffix is from tree_index+1:parent_count+1.
2677
2279
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2678
2280
            # now stitch in all the entries from this tree
2679
 
            last_dirname = None
2680
 
            for path, entry in tree.iter_entries_by_dir():
 
2281
            for path, entry in tree.inventory.iter_entries_by_dir():
2681
2282
                # here we process each trees details for each item in the tree.
2682
2283
                # we first update any existing entries for the id at other paths,
2683
2284
                # then we either create or update the entry for the id at the
2690
2291
                file_id = entry.file_id
2691
2292
                path_utf8 = path.encode('utf8')
2692
2293
                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)
 
2294
                new_entry_key = (dirname, basename, file_id)
2699
2295
                # tree index consistency: All other paths for this id in this tree
2700
2296
                # index must point to the correct path.
2701
 
                entry_keys = id_index.get(file_id, ())
2702
 
                for entry_key in entry_keys:
 
2297
                for entry_key in id_index.setdefault(file_id, set()):
2703
2298
                    # TODO:PROFILING: It might be faster to just update
2704
2299
                    # rather than checking if we need to, and then overwrite
2705
2300
                    # the one we are located at.
2708
2303
                        # other trees, so put absent pointers there
2709
2304
                        # This is the vertical axis in the matrix, all pointing
2710
2305
                        # 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.
 
2306
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
2307
                # by path consistency: Insert into an existing path record (trivial), or
 
2308
                # add a new one with relocation pointers for the other tree indexes.
 
2309
                if new_entry_key in id_index[file_id]:
 
2310
                    # there is already an entry where this data belongs, just insert it.
2719
2311
                    by_path[new_entry_key][tree_index] = \
2720
2312
                        self._inv_entry_to_details(entry)
2721
2313
                else:
2725
2317
                    new_details = []
2726
2318
                    for lookup_index in xrange(tree_index):
2727
2319
                        # boundary case: this is the first occurence of file_id
2728
 
                        # so there are no id_indexes, possibly take this out of
 
2320
                        # so there are no id_indexs, possibly take this out of
2729
2321
                        # the loop?
2730
 
                        if not len(entry_keys):
 
2322
                        if not len(id_index[file_id]):
2731
2323
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2732
2324
                        else:
2733
2325
                            # grab any one entry, use it to find the right path.
2734
 
                            a_key = iter(entry_keys).next()
 
2326
                            # TODO: optimise this to reduce memory use in highly
 
2327
                            # fragmented situations by reusing the relocation
 
2328
                            # records.
 
2329
                            a_key = iter(id_index[file_id]).next()
2735
2330
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
2736
 
                                # its a pointer or missing statement, use it as
2737
 
                                # is.
 
2331
                                # its a pointer or missing statement, use it as is.
2738
2332
                                new_details.append(by_path[a_key][lookup_index])
2739
2333
                            else:
2740
2334
                                # we have the right key, make a pointer to it.
2741
2335
                                real_path = ('/'.join(a_key[0:2])).strip('/')
2742
 
                                new_details.append(st('r', real_path, 0, False,
2743
 
                                                      ''))
 
2336
                                new_details.append(('r', real_path, 0, False, ''))
2744
2337
                    new_details.append(self._inv_entry_to_details(entry))
2745
2338
                    new_details.extend(new_location_suffix)
2746
2339
                    by_path[new_entry_key] = new_details
2747
 
                    self._add_to_id_index(id_index, new_entry_key)
 
2340
                    id_index[file_id].add(new_entry_key)
2748
2341
        # --- end generation of full tree mappings
2749
2342
 
2750
2343
        # sort and output all the entries
2752
2345
        self._entries_to_current_state(new_entries)
2753
2346
        self._parents = [rev_id for rev_id, tree in trees]
2754
2347
        self._ghosts = list(ghosts)
2755
 
        self._mark_modified(header_modified=True)
 
2348
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
2349
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2756
2350
        self._id_index = id_index
2757
2351
 
2758
2352
    def _sort_entries(self, entry_list):
2762
2356
        try to keep everything in sorted blocks all the time, but sometimes
2763
2357
        it's easier to sort after the fact.
2764
2358
        """
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):
 
2359
        def _key(entry):
2771
2360
            # 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)
 
2361
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
2779
2362
        return sorted(entry_list, key=_key)
2780
2363
 
2781
2364
    def set_state_from_inventory(self, new_inv):
2789
2372
        if 'evil' in debug.debug_flags:
2790
2373
            trace.mutter_callsite(1,
2791
2374
                "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
2375
        self._read_dirblocks_if_needed()
2796
2376
        # sketch:
2797
2377
        # Two iterators: current data and new data, both in dirblock order.
2806
2386
        new_iterator = new_inv.iter_entries_by_dir()
2807
2387
        # we will be modifying the dirstate, so we need a stable iterator. In
2808
2388
        # 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.
 
2389
        # list - which is a shallow copy.
2812
2390
        old_iterator = iter(list(self._iter_entries()))
2813
2391
        # both must have roots so this is safe:
2814
2392
        current_new = new_iterator.next()
2848
2426
            # we make both end conditions explicit
2849
2427
            if not current_old:
2850
2428
                # 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
2429
                self.update_minimal(new_entry_key, current_new_minikind,
2855
2430
                    executable=current_new[1].executable,
2856
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
2857
 
                    fullscan=True)
 
2431
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
2858
2432
                current_new = advance(new_iterator)
2859
2433
            elif not current_new:
2860
2434
                # 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
2435
                self._make_absent(current_old)
2866
2436
                current_old = advance(old_iterator)
2867
2437
            elif new_entry_key == current_old[0]:
2874
2444
                # kind has changed.
2875
2445
                if (current_old[1][0][3] != current_new[1].executable or
2876
2446
                    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
2447
                    self.update_minimal(current_old[0], current_new_minikind,
2881
2448
                        executable=current_new[1].executable,
2882
 
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
2883
 
                        fullscan=True)
 
2449
                        path_utf8=new_path_utf8, fingerprint=fingerprint)
2884
2450
                # both sides are dealt with, move on
2885
2451
                current_old = advance(old_iterator)
2886
2452
                current_new = advance(new_iterator)
2889
2455
                      and new_entry_key[1:] < current_old[0][1:])):
2890
2456
                # new comes before:
2891
2457
                # 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
2458
                self.update_minimal(new_entry_key, current_new_minikind,
2896
2459
                    executable=current_new[1].executable,
2897
 
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
2898
 
                    fullscan=True)
 
2460
                    path_utf8=new_path_utf8, fingerprint=fingerprint)
2899
2461
                current_new = advance(new_iterator)
2900
2462
            else:
2901
2463
                # we've advanced past the place where the old key would be,
2902
2464
                # 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
2465
                self._make_absent(current_old)
2908
2466
                current_old = advance(old_iterator)
2909
 
        self._mark_modified()
 
2467
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2910
2468
        self._id_index = None
2911
2469
        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
2470
 
2932
2471
    def _make_absent(self, current_old):
2933
2472
        """Mark current_old - an entry - as absent for tree 0.
2959
2498
            block[1].pop(entry_index)
2960
2499
            # if we have an id_index in use, remove this key from it for this id.
2961
2500
            if self._id_index is not None:
2962
 
                self._remove_from_id_index(self._id_index, current_old[0])
 
2501
                self._id_index[current_old[0][2]].remove(current_old[0])
2963
2502
        # update all remaining keys for this id to record it as absent. The
2964
2503
        # existing details may either be the record we are marking as deleted
2965
2504
        # (if there were other trees with the id present at this path), or may
2978
2517
            if update_tree_details[0][0] == 'a': # absent
2979
2518
                raise AssertionError('bad row %r' % (update_tree_details,))
2980
2519
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2981
 
        self._mark_modified()
 
2520
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
2982
2521
        return last_reference
2983
2522
 
2984
2523
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
2985
 
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
 
2524
                       packed_stat=None, size=0, path_utf8=None):
2986
2525
        """Update an entry to the state in tree 0.
2987
2526
 
2988
2527
        This will either create a new entry at 'key' or update an existing one.
2999
2538
        :param size: Size information for new entry
3000
2539
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
3001
2540
                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
2541
 
3006
2542
        If packed_stat and fingerprint are not given, they're invalidated in
3007
2543
        the entry.
3016
2552
        new_details = (minikind, fingerprint, size, executable, packed_stat)
3017
2553
        id_index = self._get_id_index()
3018
2554
        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
2555
            # new entry, synthesis cross reference here,
3037
 
            existing_keys = id_index.get(key[2], ())
 
2556
            existing_keys = id_index.setdefault(key[2], set())
3038
2557
            if not existing_keys:
3039
2558
                # not currently in the state, simplest case
3040
2559
                new_entry = key, [new_details] + self._empty_parent_info()
3043
2562
                # grab one of them and use it to generate parent
3044
2563
                # relocation/absent entries.
3045
2564
                new_entry = key, [new_details]
3046
 
                # existing_keys can be changed as we iterate.
3047
 
                for other_key in tuple(existing_keys):
 
2565
                for other_key in existing_keys:
3048
2566
                    # change the record at other to be a pointer to this new
3049
2567
                    # record. The loop looks similar to the change to
3050
2568
                    # relocations when updating an existing record but its not:
3051
2569
                    # the test for existing kinds is different: this can be
3052
2570
                    # 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,))
 
2571
                    other_block_index, present = self._find_block_index_from_key(other_key)
 
2572
                    if not present:
 
2573
                        raise AssertionError('could not find block for %s' % (other_key,))
 
2574
                    other_entry_index, present = self._find_entry_index(other_key,
 
2575
                                            self._dirblocks[other_block_index][1])
 
2576
                    if not present:
 
2577
                        raise AssertionError('could not find entry for %s' % (other_key,))
3065
2578
                    if path_utf8 is None:
3066
2579
                        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)
 
2580
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
 
2581
                        ('r', path_utf8, 0, False, '')
3079
2582
 
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
2583
                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
2584
                for lookup_index in xrange(1, num_present_parents + 1):
3090
2585
                    # grab any one entry, use it to find the right path.
3091
2586
                    # TODO: optimise this to reduce memory use in highly
3098
2593
                    update_entry_index, present = \
3099
2594
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
3100
2595
                    if not present:
3101
 
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
 
2596
                        raise AssertionError('could not find entry for %s' % (other_key,))
3102
2597
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
3103
2598
                    if update_details[0] in 'ar': # relocated, absent
3104
2599
                        # its a pointer or absent in lookup_index's tree, use
3109
2604
                        pointer_path = osutils.pathjoin(*other_key[0:2])
3110
2605
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
3111
2606
            block.insert(entry_index, new_entry)
3112
 
            self._add_to_id_index(id_index, key)
 
2607
            existing_keys.add(key)
3113
2608
        else:
3114
2609
            # Does the new state matter?
3115
2610
            block[entry_index][1][0] = new_details
3124
2619
            # converted to relocated.
3125
2620
            if path_utf8 is None:
3126
2621
                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:
 
2622
            for entry_key in id_index.setdefault(key[2], set()):
3133
2623
                # TODO:PROFILING: It might be faster to just update
3134
2624
                # rather than checking if we need to, and then overwrite
3135
2625
                # the one we are located at.
3153
2643
            if not present:
3154
2644
                self._dirblocks.insert(block_index, (subdir_key[0], []))
3155
2645
 
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
 
2646
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
3175
2647
 
3176
2648
    def _validate(self):
3177
2649
        """Check that invariants on the dirblock are correct.
3312
2784
            if absent_positions == tree_count:
3313
2785
                raise AssertionError(
3314
2786
                    "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
2787
 
3327
2788
    def _wipe_state(self):
3328
2789
        """Forget all state information about the dirstate."""
3425
2886
    # If we have gotten this far, that means that we need to actually
3426
2887
    # process this entry.
3427
2888
    link_or_sha1 = None
3428
 
    worth_saving = True
3429
2889
    if minikind == 'f':
3430
2890
        executable = state._is_executable(stat_value.st_mode,
3431
2891
                                         saved_executable)
3447
2907
        else:
3448
2908
            entry[1][0] = ('f', '', stat_value.st_size,
3449
2909
                           executable, DirState.NULLSTAT)
3450
 
            worth_saving = False
3451
2910
    elif minikind == 'd':
3452
2911
        link_or_sha1 = None
3453
2912
        entry[1][0] = ('d', '', 0, False, packed_stat)
3459
2918
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3460
2919
            state._ensure_block(block_index, entry_index,
3461
2920
                               osutils.pathjoin(entry[0][0], entry[0][1]))
3462
 
        else:
3463
 
            worth_saving = False
3464
2921
    elif minikind == 'l':
3465
 
        if saved_minikind == 'l':
3466
 
            worth_saving = False
3467
2922
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3468
2923
        if state._cutoff_time is None:
3469
2924
            state._sha_cutoff_time()
3474
2929
        else:
3475
2930
            entry[1][0] = ('l', '', stat_value.st_size,
3476
2931
                           False, DirState.NULLSTAT)
3477
 
    if worth_saving:
3478
 
        state._mark_modified([entry])
 
2932
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
3479
2933
    return link_or_sha1
 
2934
update_entry = py_update_entry
3480
2935
 
3481
2936
 
3482
2937
class ProcessEntryPython(object):
3483
2938
 
3484
 
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
 
2939
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id", "uninteresting",
3485
2940
        "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"]
 
2941
        "use_filesystem_for_exec", "utf8_decode", "searched_specific_files",
 
2942
        "search_specific_files", "state", "source_index", "target_index",
 
2943
        "want_unversioned", "tree"]
3490
2944
 
3491
2945
    def __init__(self, include_unchanged, use_filesystem_for_exec,
3492
2946
        search_specific_files, state, source_index, target_index,
3493
2947
        want_unversioned, tree):
3494
2948
        self.old_dirname_to_file_id = {}
3495
2949
        self.new_dirname_to_file_id = {}
3496
 
        # Are we doing a partial iter_changes?
3497
 
        self.partial = search_specific_files != set([''])
 
2950
        # Just a sentry, so that _process_entry can say that this
 
2951
        # record is handled, but isn't interesting to process (unchanged)
 
2952
        self.uninteresting = object()
3498
2953
        # Using a list so that we can access the values and change them in
3499
2954
        # nested scope. Each one is [path, file_id, entry]
3500
2955
        self.last_source_parent = [None, None]
3503
2958
        self.use_filesystem_for_exec = use_filesystem_for_exec
3504
2959
        self.utf8_decode = cache_utf8._utf8_decode
3505
2960
        # 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.
 
2961
        # search_specific_files, if the detail is relocated: add the id, and add the
 
2962
        # relocated path as one to search if its not searched already. If the
 
2963
        # detail is not relocated, add the id.
3509
2964
        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
2965
        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
2966
        self.state = state
3520
2967
        self.source_index = source_index
3521
2968
        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
2969
        self.want_unversioned = want_unversioned
3526
2970
        self.tree = tree
3527
2971
 
3529
2973
        """Compare an entry and real disk to generate delta information.
3530
2974
 
3531
2975
        :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 ?)
 
2976
            the path of entry. If None, then the path is considered absent.
 
2977
            (Perhaps we should pass in a concrete entry for this ?)
3534
2978
            Basename is returned as a utf8 string because we expect this
3535
2979
            tuple will be ignored, and don't want to take the time to
3536
2980
            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.
 
2981
        :return: None if these don't match
 
2982
                 A tuple of information about the change, or
 
2983
                 the object 'uninteresting' if these match, but are
 
2984
                 basically identical.
3544
2985
        """
3545
2986
        if self.source_index is None:
3546
2987
            source_details = DirState.NULL_PARENT_DETAILS
3614
3055
                    if source_minikind != 'f':
3615
3056
                        content_change = True
3616
3057
                    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])
 
3058
                        # If the size is the same, check the sha:
 
3059
                        if target_details[2] == source_details[2]:
 
3060
                            if link_or_sha1 is None:
 
3061
                                # Stat cache miss:
 
3062
                                statvalue, link_or_sha1 = \
 
3063
                                    self.state._sha1_provider.stat_and_sha1(
 
3064
                                    path_info[4])
 
3065
                                self.state._observed_sha1(entry, link_or_sha1,
 
3066
                                    statvalue)
 
3067
                            content_change = (link_or_sha1 != source_details[1])
 
3068
                        else:
 
3069
                            # Size changed, so must be different
 
3070
                            content_change = True
3628
3071
                    # Target details is updated at update_entry time
3629
3072
                    if self.use_filesystem_for_exec:
3630
3073
                        # We don't need S_ISREG here, because we are sure
3645
3088
                        content_change = False
3646
3089
                    target_exec = False
3647
3090
                else:
3648
 
                    if path is None:
3649
 
                        path = pathjoin(old_dirname, old_basename)
3650
 
                    raise errors.BadFileKindError(path, path_info[2])
 
3091
                    raise Exception, "unknown kind %s" % path_info[2]
3651
3092
            if source_minikind == 'd':
3652
3093
                if path is None:
3653
3094
                    old_path = path = pathjoin(old_dirname, old_basename)
3654
3095
                self.old_dirname_to_file_id[old_path] = file_id
3655
3096
            # parent id is the entry for the path in the target tree
3656
 
            if old_basename and old_dirname == self.last_source_parent[0]:
 
3097
            if old_dirname == self.last_source_parent[0]:
3657
3098
                source_parent_id = self.last_source_parent[1]
3658
3099
            else:
3659
3100
                try:
3669
3110
                    self.last_source_parent[0] = old_dirname
3670
3111
                    self.last_source_parent[1] = source_parent_id
3671
3112
            new_dirname = entry[0][0]
3672
 
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
 
3113
            if new_dirname == self.last_target_parent[0]:
3673
3114
                target_parent_id = self.last_target_parent[1]
3674
3115
            else:
3675
3116
                try:
3692
3133
                    self.last_target_parent[1] = target_parent_id
3693
3134
 
3694
3135
            source_exec = source_details[3]
3695
 
            changed = (content_change
 
3136
            if (self.include_unchanged
 
3137
                or content_change
3696
3138
                or source_parent_id != target_parent_id
3697
3139
                or old_basename != entry[0][1]
3698
3140
                or source_exec != target_exec
3699
 
                )
3700
 
            if not changed and not self.include_unchanged:
3701
 
                return None, False
3702
 
            else:
 
3141
                ):
3703
3142
                if old_path is None:
3704
3143
                    old_path = path = pathjoin(old_dirname, old_basename)
3705
3144
                    old_path_u = self.utf8_decode(old_path)[0]
3718
3157
                       (source_parent_id, target_parent_id),
3719
3158
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
3720
3159
                       (source_kind, target_kind),
3721
 
                       (source_exec, target_exec)), changed
 
3160
                       (source_exec, target_exec))
 
3161
            else:
 
3162
                return self.uninteresting
3722
3163
        elif source_minikind in 'a' and target_minikind in 'fdlt':
3723
3164
            # looks like a new file
3724
3165
            path = pathjoin(entry[0][0], entry[0][1])
3745
3186
                       (None, parent_id),
3746
3187
                       (None, self.utf8_decode(entry[0][1])[0]),
3747
3188
                       (None, path_info[2]),
3748
 
                       (None, target_exec)), True
 
3189
                       (None, target_exec))
3749
3190
            else:
3750
3191
                # Its a missing file, report it as such.
3751
3192
                return (entry[0][2],
3755
3196
                       (None, parent_id),
3756
3197
                       (None, self.utf8_decode(entry[0][1])[0]),
3757
3198
                       (None, None),
3758
 
                       (None, False)), True
 
3199
                       (None, False))
3759
3200
        elif source_minikind in 'fdlt' and target_minikind in 'a':
3760
3201
            # unversioned, possibly, or possibly not deleted: we dont care.
3761
3202
            # if its still on disk, *and* theres no other entry at this
3773
3214
                   (parent_id, None),
3774
3215
                   (self.utf8_decode(entry[0][1])[0], None),
3775
3216
                   (DirState._minikind_to_kind[source_minikind], None),
3776
 
                   (source_details[3], None)), True
 
3217
                   (source_details[3], None))
3777
3218
        elif source_minikind in 'fdlt' and target_minikind in 'r':
3778
3219
            # a rename; could be a true rename, or a rename inherited from
3779
3220
            # a renamed parent. TODO: handle this efficiently. Its not
3790
3231
            raise AssertionError("don't know how to compare "
3791
3232
                "source_minikind=%r, target_minikind=%r"
3792
3233
                % (source_minikind, target_minikind))
3793
 
        return None, None
 
3234
            ## import pdb;pdb.set_trace()
 
3235
        return None
3794
3236
 
3795
3237
    def __iter__(self):
3796
3238
        return self
3797
3239
 
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
3240
    def iter_changes(self):
3818
3241
        """Iterate over the changes."""
3819
3242
        utf8_decode = cache_utf8._utf8_decode
3820
3243
        _cmp_by_dirs = cmp_by_dirs
3821
3244
        _process_entry = self._process_entry
 
3245
        uninteresting = self.uninteresting
3822
3246
        search_specific_files = self.search_specific_files
3823
3247
        searched_specific_files = self.searched_specific_files
3824
3248
        splitpath = osutils.splitpath
3894
3318
                continue
3895
3319
            path_handled = False
3896
3320
            for entry in root_entries:
3897
 
                result, changed = _process_entry(entry, root_dir_info)
3898
 
                if changed is not None:
 
3321
                result = _process_entry(entry, root_dir_info)
 
3322
                if result is not None:
3899
3323
                    path_handled = True
3900
 
                    if changed:
3901
 
                        self._gather_result_for_consistency(result)
3902
 
                    if changed or self.include_unchanged:
 
3324
                    if result is not uninteresting:
3903
3325
                        yield result
3904
3326
            if self.want_unversioned and not path_handled and root_dir_info:
3905
3327
                new_executable = bool(
4015
3437
                        for current_entry in current_block[1]:
4016
3438
                            # entry referring to file not present on disk.
4017
3439
                            # 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:
 
3440
                            result = _process_entry(current_entry, None)
 
3441
                            if result is not None:
 
3442
                                if result is not uninteresting:
4023
3443
                                    yield result
4024
3444
                        block_index +=1
4025
3445
                        if (block_index < len(self.state._dirblocks) and
4055
3475
                        pass
4056
3476
                    elif current_path_info is None:
4057
3477
                        # 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:
 
3478
                        result = _process_entry(current_entry, current_path_info)
 
3479
                        if result is not None:
 
3480
                            if result is not uninteresting:
4063
3481
                                yield result
4064
3482
                    elif (current_entry[0][1] != current_path_info[1]
4065
3483
                          or current_entry[1][self.target_index][0] in 'ar'):
4078
3496
                        else:
4079
3497
                            # entry referring to file not present on disk.
4080
3498
                            # 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:
 
3499
                            result = _process_entry(current_entry, None)
 
3500
                            if result is not None:
 
3501
                                if result is not uninteresting:
4086
3502
                                    yield result
4087
3503
                            advance_path = False
4088
3504
                    else:
4089
 
                        result, changed = _process_entry(current_entry, current_path_info)
4090
 
                        if changed is not None:
 
3505
                        result = _process_entry(current_entry, current_path_info)
 
3506
                        if result is not None:
4091
3507
                            path_handled = True
4092
 
                            if changed:
4093
 
                                self._gather_result_for_consistency(result)
4094
 
                            if changed or self.include_unchanged:
 
3508
                            if result is not uninteresting:
4095
3509
                                yield result
4096
3510
                    if advance_entry and current_entry is not None:
4097
3511
                        entry_index += 1
4156
3570
                        current_dir_info = dir_iterator.next()
4157
3571
                    except StopIteration:
4158
3572
                        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
 
3573
_process_entry = ProcessEntryPython
4277
3574
 
4278
3575
 
4279
3576
# Try to load the compiled form if possible
4280
3577
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,
 
3578
    from bzrlib._dirstate_helpers_c import (
 
3579
        _read_dirblocks_c as _read_dirblocks,
 
3580
        bisect_dirblock_c as bisect_dirblock,
 
3581
        _bisect_path_left_c as _bisect_path_left,
 
3582
        _bisect_path_right_c as _bisect_path_right,
 
3583
        cmp_by_dirs_c as cmp_by_dirs,
4287
3584
        ProcessEntryC as _process_entry,
4288
3585
        update_entry as update_entry,
4289
3586
        )
4290
 
except ImportError, e:
4291
 
    osutils.failed_to_load_extension(e)
 
3587
except ImportError:
4292
3588
    from bzrlib._dirstate_helpers_py import (
4293
 
        _read_dirblocks,
4294
 
        bisect_dirblock,
4295
 
        _bisect_path_left,
4296
 
        _bisect_path_right,
4297
 
        cmp_by_dirs,
 
3589
        _read_dirblocks_py as _read_dirblocks,
 
3590
        bisect_dirblock_py as bisect_dirblock,
 
3591
        _bisect_path_left_py as _bisect_path_left,
 
3592
        _bisect_path_right_py as _bisect_path_right,
 
3593
        cmp_by_dirs_py as cmp_by_dirs,
4298
3594
        )
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