~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

Move all features to bzrlib.tests.features in 2.5

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
21
21
are not - this is done for clarity of reading. All string data is in utf8.
22
22
 
23
 
MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
24
 
NL = "\n";
25
 
NULL = "\0";
26
 
WHOLE_NUMBER = {digit}, digit;
27
 
BOOLEAN = "y" | "n";
28
 
REVISION_ID = a non-empty utf8 string;
29
 
 
30
 
dirstate format = header line, full checksum, row count, parent details,
31
 
 ghost_details, entries;
32
 
header line = "#bazaar dirstate flat format 3", NL;
33
 
full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
34
 
row count = "num_entries: ", WHOLE_NUMBER, NL;
35
 
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
36
 
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
37
 
entries = {entry};
38
 
entry = entry_key, current_entry_details, {parent_entry_details};
39
 
entry_key = dirname,  basename, fileid;
40
 
current_entry_details = common_entry_details, working_entry_details;
41
 
parent_entry_details = common_entry_details, history_entry_details;
42
 
common_entry_details = MINIKIND, fingerprint, size, executable
43
 
working_entry_details = packed_stat
44
 
history_entry_details = REVISION_ID;
45
 
executable = BOOLEAN;
46
 
size = WHOLE_NUMBER;
47
 
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
48
 
 
49
 
Given this definition, the following is useful to know:
50
 
entry (aka row) - all the data for a given key.
51
 
entry[0]: The key (dirname, basename, fileid)
52
 
entry[0][0]: dirname
53
 
entry[0][1]: basename
54
 
entry[0][2]: fileid
55
 
entry[1]: The tree(s) data for this path and id combination.
56
 
entry[1][0]: The current tree
57
 
entry[1][1]: The second tree
58
 
 
59
 
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
60
 
entry[1][0][0]: minikind
61
 
entry[1][0][1]: fingerprint
62
 
entry[1][0][2]: size
63
 
entry[1][0][3]: executable
64
 
entry[1][0][4]: packed_stat
65
 
OR (for non tree-0)
66
 
entry[1][1][4]: revision_id
 
23
::
 
24
 
 
25
    MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
 
26
    NL = "\\n";
 
27
    NULL = "\\0";
 
28
    WHOLE_NUMBER = {digit}, digit;
 
29
    BOOLEAN = "y" | "n";
 
30
    REVISION_ID = a non-empty utf8 string;
 
31
    
 
32
    dirstate format = header line, full checksum, row count, parent details,
 
33
     ghost_details, entries;
 
34
    header line = "#bazaar dirstate flat format 3", NL;
 
35
    full checksum = "crc32: ", ["-"], WHOLE_NUMBER, NL;
 
36
    row count = "num_entries: ", WHOLE_NUMBER, NL;
 
37
    parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
 
38
    ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
 
39
    entries = {entry};
 
40
    entry = entry_key, current_entry_details, {parent_entry_details};
 
41
    entry_key = dirname,  basename, fileid;
 
42
    current_entry_details = common_entry_details, working_entry_details;
 
43
    parent_entry_details = common_entry_details, history_entry_details;
 
44
    common_entry_details = MINIKIND, fingerprint, size, executable
 
45
    working_entry_details = packed_stat
 
46
    history_entry_details = REVISION_ID;
 
47
    executable = BOOLEAN;
 
48
    size = WHOLE_NUMBER;
 
49
    fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
50
 
 
51
Given this definition, the following is useful to know::
 
52
 
 
53
    entry (aka row) - all the data for a given key.
 
54
    entry[0]: The key (dirname, basename, fileid)
 
55
    entry[0][0]: dirname
 
56
    entry[0][1]: basename
 
57
    entry[0][2]: fileid
 
58
    entry[1]: The tree(s) data for this path and id combination.
 
59
    entry[1][0]: The current tree
 
60
    entry[1][1]: The second tree
 
61
 
 
62
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate::
 
63
 
 
64
    entry[1][0][0]: minikind
 
65
    entry[1][0][1]: fingerprint
 
66
    entry[1][0][2]: size
 
67
    entry[1][0][3]: executable
 
68
    entry[1][0][4]: packed_stat
 
69
 
 
70
OR (for non tree-0)::
 
71
 
 
72
    entry[1][1][4]: revision_id
67
73
 
68
74
There may be multiple rows at the root, one per id present in the root, so the
69
 
in memory root row is now:
70
 
self._dirblocks[0] -> ('', [entry ...]),
71
 
and the entries in there are
72
 
entries[0][0]: ''
73
 
entries[0][1]: ''
74
 
entries[0][2]: file_id
75
 
entries[1][0]: The tree data for the current tree for this fileid at /
76
 
etc.
77
 
 
78
 
Kinds:
79
 
'r' is a relocated entry: This path is not present in this tree with this id,
80
 
    but the id can be found at another location. The fingerprint is used to
81
 
    point to the target location.
82
 
'a' is an absent entry: In that tree the id is not present at this path.
83
 
'd' is a directory entry: This path in this tree is a directory with the
84
 
    current file id. There is no fingerprint for directories.
85
 
'f' is a file entry: As for directory, but 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.
 
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.
92
103
 
93
104
Ordering:
94
105
 
95
 
The entries on disk and in memory are ordered according to the following keys:
 
106
The entries on disk and in memory are ordered according to the following keys::
96
107
 
97
108
    directory, as a list of components
98
109
    filename
99
110
    file-id
100
111
 
101
112
--- Format 1 had the following different definition: ---
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
 
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
108
122
 
109
123
PARENT ROW's are emitted for every parent that is not in the ghosts details
110
124
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
135
149
----
136
150
 
137
151
Design priorities:
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
 
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
141
155
    is an example of this)
142
156
 
143
157
 
144
158
Locking:
 
159
 
145
160
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
146
161
 been modified, but will require that we flush/ignore cached stat-hit data
147
162
 because we won't want to restat all files on disk just because a lock was
148
163
 acquired, yet we cannot trust the data after the previous lock was released.
149
164
 
150
 
Memory representation:
 
165
Memory representation::
 
166
 
151
167
 vector of all directories, and vector of the childen ?
152
168
   i.e.
153
169
     root_entrie = (direntry for root, [parent_direntries_for_root]),
167
183
    - What's the risk of error here? Once we have the base format being processed
168
184
      we should have a net win regardless of optimality. So we are going to
169
185
      go with what seems reasonable.
 
186
 
170
187
open questions:
171
188
 
172
189
Maybe we should do a test profile of the core structure - 10K simulated
220
237
    inventory,
221
238
    lock,
222
239
    osutils,
 
240
    static_tuple,
223
241
    trace,
224
242
    )
225
243
 
264
282
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
265
283
 
266
284
 
 
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
 
267
296
class SHA1Provider(object):
268
297
    """An interface for getting sha1s of a file."""
269
298
 
354
383
    NOT_IN_MEMORY = 0
355
384
    IN_MEMORY_UNMODIFIED = 1
356
385
    IN_MEMORY_MODIFIED = 2
 
386
    IN_MEMORY_HASH_MODIFIED = 3 # Only hash-cache updates
357
387
 
358
388
    # A pack_stat (the x's) that is just noise and will never match the output
359
389
    # of base64 encode.
360
390
    NULLSTAT = 'x' * 32
361
 
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
391
    NULL_PARENT_DETAILS = static_tuple.StaticTuple('a', '', 0, False, '')
362
392
 
363
393
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
364
394
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
365
395
 
366
 
    def __init__(self, path, sha1_provider):
 
396
    def __init__(self, path, sha1_provider, worth_saving_limit=0):
367
397
        """Create a  DirState object.
368
398
 
369
399
        :param path: The path at which the dirstate file on disk should live.
370
400
        :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.
371
405
        """
372
406
        # _header_state and _dirblock_state represent the current state
373
407
        # of the dirstate metadata and the per-row data respectiely.
410
444
        # during commit.
411
445
        self._last_block_index = None
412
446
        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
413
451
 
414
452
    def __repr__(self):
415
453
        return "%s(%r)" % \
416
454
            (self.__class__.__name__, self._filename)
417
455
 
 
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
 
418
487
    def add(self, path, file_id, kind, stat, fingerprint):
419
488
        """Add a path to be tracked.
420
489
 
546
615
        if kind == 'directory':
547
616
           # insert a new dirblock
548
617
           self._ensure_block(block_index, entry_index, utf8path)
549
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
618
        self._mark_modified()
550
619
        if self._id_index:
551
 
            self._id_index.setdefault(entry_key[2], set()).add(entry_key)
 
620
            self._add_to_id_index(self._id_index, entry_key)
552
621
 
553
622
    def _bisect(self, paths):
554
623
        """Bisect through the disk structure for specific rows.
1018
1087
 
1019
1088
        self._ghosts = []
1020
1089
        self._parents = [parents[0]]
1021
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1022
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1090
        self._mark_modified(header_modified=True)
1023
1091
 
1024
1092
    def _empty_parent_info(self):
1025
1093
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
1154
1222
    def _fields_per_entry(self):
1155
1223
        """How many null separated fields should be in each entry row.
1156
1224
 
1157
 
        Each line now has an extra '\n' field which is not used
 
1225
        Each line now has an extra '\\n' field which is not used
1158
1226
        so we just skip over it
1159
 
        entry size:
 
1227
 
 
1228
        entry size::
1160
1229
            3 fields for the key
1161
1230
            + number of fields per tree_data (5) * tree count
1162
1231
            + newline
1275
1344
            raise
1276
1345
        return result
1277
1346
 
 
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
 
1278
1355
    def update_by_delta(self, delta):
1279
1356
        """Apply an inventory delta to the dirstate for tree 0
1280
1357
 
1298
1375
        new_ids = set()
1299
1376
        # This loop transforms the delta to single atomic operations that can
1300
1377
        # be executed and validated.
1301
 
        for old_path, new_path, file_id, inv_entry in sorted(
1302
 
            inventory._check_delta_unique_old_paths(
1303
 
            inventory._check_delta_unique_new_paths(
1304
 
            inventory._check_delta_ids_match_entry(
1305
 
            inventory._check_delta_ids_are_valid(
1306
 
            inventory._check_delta_new_path_entry_both_or_None(delta))))),
1307
 
            reverse=True):
 
1378
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
 
1379
        for old_path, new_path, file_id, inv_entry in delta:
1308
1380
            if (file_id in insertions) or (file_id in removals):
1309
 
                raise errors.InconsistentDelta(old_path or new_path, file_id,
 
1381
                self._raise_invalid(old_path or new_path, file_id,
1310
1382
                    "repeated file_id")
1311
1383
            if old_path is not None:
1312
1384
                old_path = old_path.encode('utf-8')
1315
1387
                new_ids.add(file_id)
1316
1388
            if new_path is not None:
1317
1389
                if inv_entry is None:
1318
 
                    raise errors.InconsistentDelta(new_path, file_id,
 
1390
                    self._raise_invalid(new_path, file_id,
1319
1391
                        "new_path with no entry")
1320
1392
                new_path = new_path.encode('utf-8')
1321
1393
                dirname_utf8, basename = osutils.split(new_path)
1362
1434
            # _get_entry raises BzrError when a request is inconsistent; we
1363
1435
            # want such errors to be shown as InconsistentDelta - and that 
1364
1436
            # fits the behaviour we trigger.
1365
 
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
 
1437
            raise errors.InconsistentDeltaDelta(delta,
 
1438
                "error from _get_entry. %s" % (e,))
1366
1439
 
1367
1440
    def _apply_removals(self, removals):
1368
1441
        for file_id, path in sorted(removals, reverse=True,
1373
1446
            try:
1374
1447
                entry = self._dirblocks[block_i][1][entry_i]
1375
1448
            except IndexError:
1376
 
                self._changes_aborted = True
1377
 
                raise errors.InconsistentDelta(path, file_id,
 
1449
                self._raise_invalid(path, file_id,
1378
1450
                    "Wrong path for old path.")
1379
1451
            if not f_present or entry[1][0][0] in 'ar':
1380
 
                self._changes_aborted = True
1381
 
                raise errors.InconsistentDelta(path, file_id,
 
1452
                self._raise_invalid(path, file_id,
1382
1453
                    "Wrong path for old path.")
1383
1454
            if file_id != entry[0][2]:
1384
 
                self._changes_aborted = True
1385
 
                raise errors.InconsistentDelta(path, file_id,
 
1455
                self._raise_invalid(path, file_id,
1386
1456
                    "Attempt to remove path has wrong id - found %r."
1387
1457
                    % entry[0][2])
1388
1458
            self._make_absent(entry)
1398
1468
                # be due to it being in a parent tree, or a corrupt delta.
1399
1469
                for child_entry in self._dirblocks[block_i][1]:
1400
1470
                    if child_entry[1][0][0] not in ('r', 'a'):
1401
 
                        self._changes_aborted = True
1402
 
                        raise errors.InconsistentDelta(path, entry[0][2],
 
1471
                        self._raise_invalid(path, entry[0][2],
1403
1472
                            "The file id was deleted but its children were "
1404
1473
                            "not deleted.")
1405
1474
 
1409
1478
                self.update_minimal(key, minikind, executable, fingerprint,
1410
1479
                                    path_utf8=path_utf8)
1411
1480
        except errors.NotVersionedError:
1412
 
            self._changes_aborted = True
1413
 
            raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
 
1481
            self._raise_invalid(path_utf8.decode('utf8'), key[2],
1414
1482
                "Missing parent")
1415
1483
 
1416
1484
    def update_basis_by_delta(self, delta, new_revid):
1424
1492
        Note that an exception during the operation of this method will leave
1425
1493
        the dirstate in a corrupt state where it should not be saved.
1426
1494
 
1427
 
        Finally, we expect all changes to be synchronising the basis tree with
1428
 
        the working tree.
1429
 
 
1430
1495
        :param new_revid: The new revision id for the trees parent.
1431
1496
        :param delta: An inventory delta (see apply_inventory_delta) describing
1432
1497
            the changes from the current left most parent revision to new_revid.
1444
1509
 
1445
1510
        self._parents[0] = new_revid
1446
1511
 
1447
 
        delta = sorted(delta, reverse=True)
 
1512
        delta = sorted(self._check_delta_is_valid(delta), reverse=True)
1448
1513
        adds = []
1449
1514
        changes = []
1450
1515
        deletes = []
1471
1536
        new_ids = set()
1472
1537
        for old_path, new_path, file_id, inv_entry in delta:
1473
1538
            if inv_entry is not None and file_id != inv_entry.file_id:
1474
 
                raise errors.InconsistentDelta(new_path, file_id,
 
1539
                self._raise_invalid(new_path, file_id,
1475
1540
                    "mismatched entry file_id %r" % inv_entry)
1476
 
            if new_path is not None:
 
1541
            if new_path is None:
 
1542
                new_path_utf8 = None
 
1543
            else:
1477
1544
                if inv_entry is None:
1478
 
                    raise errors.InconsistentDelta(new_path, file_id,
 
1545
                    self._raise_invalid(new_path, file_id,
1479
1546
                        "new_path with no entry")
1480
1547
                new_path_utf8 = encode(new_path)
1481
1548
                # note the parent for validation
1483
1550
                if basename_utf8:
1484
1551
                    parents.add((dirname_utf8, inv_entry.parent_id))
1485
1552
            if old_path is None:
1486
 
                adds.append((None, encode(new_path), file_id,
 
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,
1487
1558
                    inv_to_entry(inv_entry), True))
1488
1559
                new_ids.add(file_id)
1489
1560
            elif new_path is None:
1490
 
                deletes.append((encode(old_path), None, file_id, None, True))
1491
 
            elif (old_path, new_path) != root_only:
 
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:
1492
1574
                # Renames:
1493
1575
                # Because renames must preserve their children we must have
1494
1576
                # processed all relocations and removes before hand. The sort
1504
1586
                self._update_basis_apply_deletes(deletes)
1505
1587
                deletes = []
1506
1588
                # Split into an add/delete pair recursively.
1507
 
                adds.append((None, new_path_utf8, file_id,
1508
 
                    inv_to_entry(inv_entry), False))
 
1589
                adds.append((old_path_utf8, new_path_utf8, file_id,
 
1590
                             inv_to_entry(inv_entry), False))
1509
1591
                # Expunge deletes that we've seen so that deleted/renamed
1510
1592
                # children of a rename directory are handled correctly.
1511
 
                new_deletes = reversed(list(self._iter_child_entries(1,
1512
 
                    encode(old_path))))
 
1593
                new_deletes = reversed(list(
 
1594
                    self._iter_child_entries(1, old_path_utf8)))
1513
1595
                # Remove the current contents of the tree at orig_path, and
1514
1596
                # reinsert at the correct new path.
1515
1597
                for entry in new_deletes:
1516
 
                    if entry[0][0]:
1517
 
                        source_path = entry[0][0] + '/' + entry[0][1]
 
1598
                    child_dirname, child_basename, child_file_id = entry[0]
 
1599
                    if child_dirname:
 
1600
                        source_path = child_dirname + '/' + child_basename
1518
1601
                    else:
1519
 
                        source_path = entry[0][1]
 
1602
                        source_path = child_basename
1520
1603
                    if new_path_utf8:
1521
1604
                        target_path = new_path_utf8 + source_path[len(old_path):]
1522
1605
                    else:
1523
1606
                        if old_path == '':
1524
1607
                            raise AssertionError("cannot rename directory to"
1525
 
                                " itself")
 
1608
                                                 " itself")
1526
1609
                        target_path = source_path[len(old_path) + 1:]
1527
1610
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
1528
1611
                    deletes.append(
1529
1612
                        (source_path, target_path, entry[0][2], None, False))
1530
 
                deletes.append(
1531
 
                    (encode(old_path), new_path, file_id, None, False))
1532
 
            else:
1533
 
                # changes to just the root should not require remove/insertion
1534
 
                # of everything.
1535
 
                changes.append((encode(old_path), encode(new_path), file_id,
1536
 
                    inv_to_entry(inv_entry)))
 
1613
                deletes.append((old_path_utf8, new_path, file_id, None, False))
1537
1614
        self._check_delta_ids_absent(new_ids, delta, 1)
1538
1615
        try:
1539
1616
            # Finish expunging deletes/first half of renames.
1549
1626
            if 'integrity error' not in str(e):
1550
1627
                raise
1551
1628
            # _get_entry raises BzrError when a request is inconsistent; we
1552
 
            # want such errors to be shown as InconsistentDelta - and that 
1553
 
            # fits the behaviour we trigger. Partof this is driven by dirstate
1554
 
            # only supporting deltas that turn the basis into a closer fit to
1555
 
            # the active tree.
1556
 
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
 
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,))
1557
1633
 
1558
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1559
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1634
        self._mark_modified(header_modified=True)
1560
1635
        self._id_index = None
1561
1636
        return
1562
1637
 
1566
1641
            return
1567
1642
        id_index = self._get_id_index()
1568
1643
        for file_id in new_ids:
1569
 
            for key in id_index.get(file_id, []):
 
1644
            for key in id_index.get(file_id, ()):
1570
1645
                block_i, entry_i, d_present, f_present = \
1571
1646
                    self._get_block_entry_index(key[0], key[1], tree_index)
1572
1647
                if not f_present:
1576
1651
                if entry[0][2] != file_id:
1577
1652
                    # Different file_id, so not what we want.
1578
1653
                    continue
1579
 
                # NB: No changes made before this helper is called, so no need
1580
 
                # to set the _changes_aborted flag.
1581
 
                raise errors.InconsistentDelta(
1582
 
                    ("%s/%s" % key[0:2]).decode('utf8'), file_id,
 
1654
                self._raise_invalid(("%s/%s" % key[0:2]).decode('utf8'), file_id,
1583
1655
                    "This file_id is new in the delta but already present in "
1584
1656
                    "the target")
1585
1657
 
 
1658
    def _raise_invalid(self, path, file_id, reason):
 
1659
        self._changes_aborted = True
 
1660
        raise errors.InconsistentDelta(path, file_id, reason)
 
1661
 
1586
1662
    def _update_basis_apply_adds(self, adds):
1587
1663
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
1588
1664
 
1596
1672
        """
1597
1673
        # Adds are accumulated partly from renames, so can be in any input
1598
1674
        # order - sort it.
1599
 
        adds.sort()
 
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])
1600
1679
        # adds is now in lexographic order, which places all parents before
1601
1680
        # their children, so we can process it linearly.
1602
1681
        absent = 'ar'
 
1682
        st = static_tuple.StaticTuple
1603
1683
        for old_path, new_path, file_id, new_details, real_add in adds:
1604
 
            # the entry for this file_id must be in tree 0.
1605
 
            entry = self._get_entry(0, file_id, new_path)
1606
 
            if entry[0] is None or entry[0][2] != file_id:
1607
 
                self._changes_aborted = True
1608
 
                raise errors.InconsistentDelta(new_path, file_id,
1609
 
                    'working tree does not contain new entry')
1610
 
            if real_add and entry[1][1][0] not in absent:
1611
 
                self._changes_aborted = True
1612
 
                raise errors.InconsistentDelta(new_path, file_id,
1613
 
                    'The entry was considered to be a genuinely new record,'
1614
 
                    ' but there was already an old record for it.')
1615
 
            # We don't need to update the target of an 'r' because the handling
1616
 
            # of renames turns all 'r' situations into a delete at the original
1617
 
            # location.
1618
 
            entry[1][1] = new_details
 
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)
1619
1781
 
1620
1782
    def _update_basis_apply_changes(self, changes):
1621
1783
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
1626
1788
        absent = 'ar'
1627
1789
        for old_path, new_path, file_id, new_details in changes:
1628
1790
            # the entry for this file_id must be in tree 0.
1629
 
            entry = self._get_entry(0, file_id, new_path)
1630
 
            if entry[0] is None or entry[0][2] != file_id:
1631
 
                self._changes_aborted = True
1632
 
                raise errors.InconsistentDelta(new_path, file_id,
1633
 
                    'working tree does not contain new entry')
1634
 
            if (entry[1][0][0] in absent or
1635
 
                entry[1][1][0] in absent):
1636
 
                self._changes_aborted = True
1637
 
                raise errors.InconsistentDelta(new_path, file_id,
1638
 
                    'changed considered absent')
 
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')
1639
1795
            entry[1][1] = new_details
1640
1796
 
1641
1797
    def _update_basis_apply_deletes(self, deletes):
1653
1809
        null = DirState.NULL_PARENT_DETAILS
1654
1810
        for old_path, new_path, file_id, _, real_delete in deletes:
1655
1811
            if real_delete != (new_path is None):
1656
 
                self._changes_aborted = True
1657
 
                raise AssertionError("bad delete delta")
 
1812
                self._raise_invalid(old_path, file_id, "bad delete delta")
1658
1813
            # the entry for this file_id must be in tree 1.
1659
1814
            dirname, basename = osutils.split(old_path)
1660
1815
            block_index, entry_index, dir_present, file_present = \
1661
1816
                self._get_block_entry_index(dirname, basename, 1)
1662
1817
            if not file_present:
1663
 
                self._changes_aborted = True
1664
 
                raise errors.InconsistentDelta(old_path, file_id,
 
1818
                self._raise_invalid(old_path, file_id,
1665
1819
                    'basis tree does not contain removed entry')
1666
1820
            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]
1667
1823
            if entry[0][2] != file_id:
1668
 
                self._changes_aborted = True
1669
 
                raise errors.InconsistentDelta(old_path, file_id,
 
1824
                self._raise_invalid(old_path, file_id,
1670
1825
                    'mismatched file_id in tree 1')
1671
 
            if real_delete:
1672
 
                if entry[1][0][0] != 'a':
1673
 
                    self._changes_aborted = True
1674
 
                    raise errors.InconsistentDelta(old_path, file_id,
1675
 
                            'This was marked as a real delete, but the WT state'
1676
 
                            ' claims that it still exists and is versioned.')
 
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
1677
1846
                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]
1678
1859
            else:
1679
 
                if entry[1][0][0] == 'a':
1680
 
                    self._changes_aborted = True
1681
 
                    raise errors.InconsistentDelta(old_path, file_id,
1682
 
                        'The entry was considered a rename, but the source path'
1683
 
                        ' is marked as absent.')
1684
 
                    # For whatever reason, we were asked to rename an entry
1685
 
                    # that was originally marked as deleted. This could be
1686
 
                    # because we are renaming the parent directory, and the WT
1687
 
                    # current state has the file marked as deleted.
1688
 
                elif entry[1][0][0] == 'r':
1689
 
                    # implement the rename
1690
 
                    del self._dirblocks[block_index][1][entry_index]
1691
 
                else:
1692
 
                    # it is being resurrected here, so blank it out temporarily.
1693
 
                    self._dirblocks[block_index][1][entry_index][1][1] = null
 
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.")
1694
1873
 
1695
1874
    def _after_delta_check_parents(self, parents, index):
1696
1875
        """Check that parents required by the delta are all intact.
1705
1884
            # has the right file id.
1706
1885
            entry = self._get_entry(index, file_id, dirname_utf8)
1707
1886
            if entry[1] is None:
1708
 
                self._changes_aborted = True
1709
 
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1887
                self._raise_invalid(dirname_utf8.decode('utf8'),
1710
1888
                    file_id, "This parent is not present.")
1711
1889
            # Parents of things must be directories
1712
1890
            if entry[1][index][0] != 'd':
1713
 
                self._changes_aborted = True
1714
 
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1891
                self._raise_invalid(dirname_utf8.decode('utf8'),
1715
1892
                    file_id, "This parent is not a directory.")
1716
1893
 
1717
1894
    def _observed_sha1(self, entry, sha1, stat_value,
1733
1910
                self._sha_cutoff_time()
1734
1911
            if (stat_value.st_mtime < self._cutoff_time
1735
1912
                and stat_value.st_ctime < self._cutoff_time):
1736
 
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
1737
 
                    packed_stat)
1738
 
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1913
                entry[1][0] = ('f', sha1, stat_value.st_size, entry[1][0][3],
 
1914
                               packed_stat)
 
1915
                self._mark_modified([entry])
1739
1916
 
1740
1917
    def _sha_cutoff_time(self):
1741
1918
        """Return cutoff time.
1799
1976
        """Serialise the entire dirstate to a sequence of lines."""
1800
1977
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
1801
1978
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
1802
 
            # read whats on disk.
 
1979
            # read what's on disk.
1803
1980
            self._state_file.seek(0)
1804
1981
            return self._state_file.readlines()
1805
1982
        lines = []
1806
1983
        lines.append(self._get_parents_line(self.get_parent_ids()))
1807
1984
        lines.append(self._get_ghosts_line(self._ghosts))
1808
 
        # append the root line which is special cased
1809
 
        lines.extend(map(self._entry_to_line, self._iter_entries()))
 
1985
        lines.extend(self._get_entry_lines())
1810
1986
        return self._get_output_lines(lines)
1811
1987
 
1812
1988
    def _get_ghosts_line(self, ghost_ids):
1817
1993
        """Create a line for the state file for parents information."""
1818
1994
        return '\0'.join([str(len(parent_ids))] + parent_ids)
1819
1995
 
 
1996
    def _get_entry_lines(self):
 
1997
        """Create lines for entries."""
 
1998
        return map(self._entry_to_line, self._iter_entries())
 
1999
 
1820
2000
    def _get_fields_to_entry(self):
1821
2001
        """Get a function which converts entry fields into a entry record.
1822
2002
 
1940
2120
            entry_index += 1
1941
2121
        return block_index, entry_index, True, False
1942
2122
 
1943
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
 
2123
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None,
 
2124
                   include_deleted=False):
1944
2125
        """Get the dirstate entry for path in tree tree_index.
1945
2126
 
1946
2127
        If either file_id or path is supplied, it is used as the key to lookup.
1980
2161
                                          ' tree_index, file_id and path')
1981
2162
            return entry
1982
2163
        else:
1983
 
            possible_keys = self._get_id_index().get(fileid_utf8, None)
 
2164
            possible_keys = self._get_id_index().get(fileid_utf8, ())
1984
2165
            if not possible_keys:
1985
2166
                return None, None
1986
2167
            for key in possible_keys:
2088
2269
            executable = False
2089
2270
        else:
2090
2271
            raise Exception("can't pack %s" % inv_entry)
2091
 
        return (minikind, fingerprint, size, executable, tree_data)
 
2272
        return static_tuple.StaticTuple(minikind, fingerprint, size,
 
2273
                                        executable, tree_data)
2092
2274
 
2093
2275
    def _iter_child_entries(self, tree_index, path_utf8):
2094
2276
        """Iterate over all the entries that are children of path_utf.
2143
2325
                yield entry
2144
2326
 
2145
2327
    def _get_id_index(self):
2146
 
        """Get an id index of self._dirblocks."""
 
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
        """
2147
2333
        if self._id_index is None:
2148
2334
            id_index = {}
2149
2335
            for key, tree_details in self._iter_entries():
2150
 
                id_index.setdefault(key[2], set()).add(key)
 
2336
                self._add_to_id_index(id_index, key)
2151
2337
            self._id_index = id_index
2152
2338
        return self._id_index
2153
2339
 
 
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
 
2154
2369
    def _get_output_lines(self, lines):
2155
2370
        """Format lines for final output.
2156
2371
 
2176
2391
        """The number of parent entries in each record row."""
2177
2392
        return len(self._parents) - len(self._ghosts)
2178
2393
 
2179
 
    @staticmethod
2180
 
    def on_file(path, sha1_provider=None):
 
2394
    @classmethod
 
2395
    def on_file(cls, path, sha1_provider=None, worth_saving_limit=0):
2181
2396
        """Construct a DirState on the file at path "path".
2182
2397
 
2183
2398
        :param path: The path at which the dirstate file on disk should live.
2184
2399
        :param sha1_provider: an object meeting the SHA1Provider interface.
2185
2400
            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.
2186
2404
        :return: An unlocked DirState object, associated with the given path.
2187
2405
        """
2188
2406
        if sha1_provider is None:
2189
2407
            sha1_provider = DefaultSHA1Provider()
2190
 
        result = DirState(path, sha1_provider)
 
2408
        result = cls(path, sha1_provider,
 
2409
                     worth_saving_limit=worth_saving_limit)
2191
2410
        return result
2192
2411
 
2193
2412
    def _read_dirblocks_if_needed(self):
2285
2504
            trace.mutter('Not saving DirState because '
2286
2505
                    '_changes_aborted is set.')
2287
2506
            return
2288
 
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
2289
 
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
2290
 
 
 
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():
2291
2512
            grabbed_write_lock = False
2292
2513
            if self._lock_state != 'w':
2293
2514
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
2301
2522
                    # We couldn't grab a write lock, so we switch back to a read one
2302
2523
                    return
2303
2524
            try:
 
2525
                lines = self.get_lines()
2304
2526
                self._state_file.seek(0)
2305
 
                self._state_file.writelines(self.get_lines())
 
2527
                self._state_file.writelines(lines)
2306
2528
                self._state_file.truncate()
2307
2529
                self._state_file.flush()
2308
 
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
2309
 
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
2530
                self._mark_unmodified()
2310
2531
            finally:
2311
2532
                if grabbed_write_lock:
2312
2533
                    self._lock_token = self._lock_token.restore_read_lock()
2315
2536
                    #       not changed contents. Since restore_read_lock may
2316
2537
                    #       not be an atomic operation.
2317
2538
 
 
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
 
2318
2559
    def _set_data(self, parent_ids, dirblocks):
2319
2560
        """Set the full dirstate data in memory.
2320
2561
 
2328
2569
        """
2329
2570
        # our memory copy is now authoritative.
2330
2571
        self._dirblocks = dirblocks
2331
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
2332
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2572
        self._mark_modified(header_modified=True)
2333
2573
        self._parents = list(parent_ids)
2334
2574
        self._id_index = None
2335
2575
        self._packed_stat_index = None
2355
2595
        self._make_absent(entry)
2356
2596
        self.update_minimal(('', '', new_id), 'd',
2357
2597
            path_utf8='', packed_stat=entry[1][0][4])
2358
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
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.
 
2604
        if self._id_index is not None:
 
2605
            self._add_to_id_index(self._id_index, entry[0])
2359
2606
 
2360
2607
    def set_parent_trees(self, trees, ghosts):
2361
2608
        """Set the parent trees for the dirstate.
2406
2653
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
2407
2654
        # how many trees do we end up with
2408
2655
        parent_count = len(parent_trees)
 
2656
        st = static_tuple.StaticTuple
2409
2657
 
2410
2658
        # one: the current tree
2411
2659
        for entry in self._iter_entries():
2414
2662
                continue
2415
2663
            by_path[entry[0]] = [entry[1][0]] + \
2416
2664
                [DirState.NULL_PARENT_DETAILS] * parent_count
2417
 
            id_index[entry[0][2]] = set([entry[0]])
 
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])
2418
2668
 
2419
2669
        # now the parent trees:
2420
2670
        for tree_index, tree in enumerate(parent_trees):
2426
2676
            # the suffix is from tree_index+1:parent_count+1.
2427
2677
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
2428
2678
            # now stitch in all the entries from this tree
2429
 
            for path, entry in tree.inventory.iter_entries_by_dir():
 
2679
            last_dirname = None
 
2680
            for path, entry in tree.iter_entries_by_dir():
2430
2681
                # here we process each trees details for each item in the tree.
2431
2682
                # we first update any existing entries for the id at other paths,
2432
2683
                # then we either create or update the entry for the id at the
2439
2690
                file_id = entry.file_id
2440
2691
                path_utf8 = path.encode('utf8')
2441
2692
                dirname, basename = osutils.split(path_utf8)
2442
 
                new_entry_key = (dirname, basename, file_id)
 
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)
2443
2699
                # tree index consistency: All other paths for this id in this tree
2444
2700
                # index must point to the correct path.
2445
 
                for entry_key in id_index.setdefault(file_id, set()):
 
2701
                entry_keys = id_index.get(file_id, ())
 
2702
                for entry_key in entry_keys:
2446
2703
                    # TODO:PROFILING: It might be faster to just update
2447
2704
                    # rather than checking if we need to, and then overwrite
2448
2705
                    # the one we are located at.
2451
2708
                        # other trees, so put absent pointers there
2452
2709
                        # This is the vertical axis in the matrix, all pointing
2453
2710
                        # to the real path.
2454
 
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
2455
 
                # by path consistency: Insert into an existing path record (trivial), or
2456
 
                # add a new one with relocation pointers for the other tree indexes.
2457
 
                if new_entry_key in id_index[file_id]:
2458
 
                    # there is already an entry where this data belongs, just insert it.
 
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.
2459
2719
                    by_path[new_entry_key][tree_index] = \
2460
2720
                        self._inv_entry_to_details(entry)
2461
2721
                else:
2465
2725
                    new_details = []
2466
2726
                    for lookup_index in xrange(tree_index):
2467
2727
                        # boundary case: this is the first occurence of file_id
2468
 
                        # so there are no id_indexs, possibly take this out of
 
2728
                        # so there are no id_indexes, possibly take this out of
2469
2729
                        # the loop?
2470
 
                        if not len(id_index[file_id]):
 
2730
                        if not len(entry_keys):
2471
2731
                            new_details.append(DirState.NULL_PARENT_DETAILS)
2472
2732
                        else:
2473
2733
                            # grab any one entry, use it to find the right path.
2474
 
                            # TODO: optimise this to reduce memory use in highly
2475
 
                            # fragmented situations by reusing the relocation
2476
 
                            # records.
2477
 
                            a_key = iter(id_index[file_id]).next()
 
2734
                            a_key = iter(entry_keys).next()
2478
2735
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
2479
 
                                # its a pointer or missing statement, use it as is.
 
2736
                                # its a pointer or missing statement, use it as
 
2737
                                # is.
2480
2738
                                new_details.append(by_path[a_key][lookup_index])
2481
2739
                            else:
2482
2740
                                # we have the right key, make a pointer to it.
2483
2741
                                real_path = ('/'.join(a_key[0:2])).strip('/')
2484
 
                                new_details.append(('r', real_path, 0, False, ''))
 
2742
                                new_details.append(st('r', real_path, 0, False,
 
2743
                                                      ''))
2485
2744
                    new_details.append(self._inv_entry_to_details(entry))
2486
2745
                    new_details.extend(new_location_suffix)
2487
2746
                    by_path[new_entry_key] = new_details
2488
 
                    id_index[file_id].add(new_entry_key)
 
2747
                    self._add_to_id_index(id_index, new_entry_key)
2489
2748
        # --- end generation of full tree mappings
2490
2749
 
2491
2750
        # sort and output all the entries
2493
2752
        self._entries_to_current_state(new_entries)
2494
2753
        self._parents = [rev_id for rev_id, tree in trees]
2495
2754
        self._ghosts = list(ghosts)
2496
 
        self._header_state = DirState.IN_MEMORY_MODIFIED
2497
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2755
        self._mark_modified(header_modified=True)
2498
2756
        self._id_index = id_index
2499
2757
 
2500
2758
    def _sort_entries(self, entry_list):
2504
2762
        try to keep everything in sorted blocks all the time, but sometimes
2505
2763
        it's easier to sort after the fact.
2506
2764
        """
2507
 
        def _key(entry):
 
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):
2508
2771
            # sort by: directory parts, file name, file id
2509
 
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
 
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)
2510
2779
        return sorted(entry_list, key=_key)
2511
2780
 
2512
2781
    def set_state_from_inventory(self, new_inv):
2637
2906
                        current_old[0][1].decode('utf8'))
2638
2907
                self._make_absent(current_old)
2639
2908
                current_old = advance(old_iterator)
2640
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2909
        self._mark_modified()
2641
2910
        self._id_index = None
2642
2911
        self._packed_stat_index = None
2643
2912
        if tracing:
2644
2913
            trace.mutter("set_state_from_inventory complete.")
2645
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
 
2646
2932
    def _make_absent(self, current_old):
2647
2933
        """Mark current_old - an entry - as absent for tree 0.
2648
2934
 
2673
2959
            block[1].pop(entry_index)
2674
2960
            # if we have an id_index in use, remove this key from it for this id.
2675
2961
            if self._id_index is not None:
2676
 
                self._id_index[current_old[0][2]].remove(current_old[0])
 
2962
                self._remove_from_id_index(self._id_index, current_old[0])
2677
2963
        # update all remaining keys for this id to record it as absent. The
2678
2964
        # existing details may either be the record we are marking as deleted
2679
2965
        # (if there were other trees with the id present at this path), or may
2692
2978
            if update_tree_details[0][0] == 'a': # absent
2693
2979
                raise AssertionError('bad row %r' % (update_tree_details,))
2694
2980
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
2695
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2981
        self._mark_modified()
2696
2982
        return last_reference
2697
2983
 
2698
2984
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
2740
3026
                            # This entry has the same path (but a different id) as
2741
3027
                            # the new entry we're adding, and is present in ths
2742
3028
                            # tree.
2743
 
                            raise errors.InconsistentDelta(
 
3029
                            self._raise_invalid(
2744
3030
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
2745
3031
                                "Attempt to add item at path already occupied by "
2746
3032
                                "id %r" % entry[0][2])
2748
3034
                    else:
2749
3035
                        break
2750
3036
            # new entry, synthesis cross reference here,
2751
 
            existing_keys = id_index.setdefault(key[2], set())
 
3037
            existing_keys = id_index.get(key[2], ())
2752
3038
            if not existing_keys:
2753
3039
                # not currently in the state, simplest case
2754
3040
                new_entry = key, [new_details] + self._empty_parent_info()
2785
3071
                    # loop.
2786
3072
                    other_entry = other_block[other_entry_index]
2787
3073
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
2788
 
                    self._maybe_remove_row(other_block, other_entry_index,
2789
 
                        id_index)
 
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)
2790
3079
 
2791
3080
                # This loop:
2792
3081
                # adds a tuple to the new details for each column
2794
3083
                #  - or by creating a new pointer to the right row inside that column
2795
3084
                num_present_parents = self._num_present_parents()
2796
3085
                if num_present_parents:
 
3086
                    # TODO: This re-evaluates the existing_keys set, do we need
 
3087
                    #       to do that ourselves?
2797
3088
                    other_key = list(existing_keys)[0]
2798
3089
                for lookup_index in xrange(1, num_present_parents + 1):
2799
3090
                    # grab any one entry, use it to find the right path.
2818
3109
                        pointer_path = osutils.pathjoin(*other_key[0:2])
2819
3110
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
2820
3111
            block.insert(entry_index, new_entry)
2821
 
            existing_keys.add(key)
 
3112
            self._add_to_id_index(id_index, key)
2822
3113
        else:
2823
3114
            # Does the new state matter?
2824
3115
            block[entry_index][1][0] = new_details
2833
3124
            # converted to relocated.
2834
3125
            if path_utf8 is None:
2835
3126
                raise AssertionError('no path')
2836
 
            for entry_key in id_index.setdefault(key[2], set()):
 
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:
2837
3133
                # TODO:PROFILING: It might be faster to just update
2838
3134
                # rather than checking if we need to, and then overwrite
2839
3135
                # the one we are located at.
2857
3153
            if not present:
2858
3154
                self._dirblocks.insert(block_index, (subdir_key[0], []))
2859
3155
 
2860
 
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3156
        self._mark_modified()
2861
3157
 
2862
3158
    def _maybe_remove_row(self, block, index, id_index):
2863
3159
        """Remove index if it is absent or relocated across the row.
2864
3160
        
2865
3161
        id_index is updated accordingly.
 
3162
        :return: True if we removed the row, False otherwise
2866
3163
        """
2867
3164
        present_in_row = False
2868
3165
        entry = block[index]
2872
3169
                break
2873
3170
        if not present_in_row:
2874
3171
            block.pop(index)
2875
 
            id_index[entry[0][2]].remove(entry[0])
 
3172
            self._remove_from_id_index(id_index, entry[0])
 
3173
            return True
 
3174
        return False
2876
3175
 
2877
3176
    def _validate(self):
2878
3177
        """Check that invariants on the dirblock are correct.
3020
3319
                        raise AssertionError(
3021
3320
                            'file_id %r did not match entry key %s'
3022
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,))
3023
3326
 
3024
3327
    def _wipe_state(self):
3025
3328
        """Forget all state information about the dirstate."""
3122
3425
    # If we have gotten this far, that means that we need to actually
3123
3426
    # process this entry.
3124
3427
    link_or_sha1 = None
 
3428
    worth_saving = True
3125
3429
    if minikind == 'f':
3126
3430
        executable = state._is_executable(stat_value.st_mode,
3127
3431
                                         saved_executable)
3143
3447
        else:
3144
3448
            entry[1][0] = ('f', '', stat_value.st_size,
3145
3449
                           executable, DirState.NULLSTAT)
 
3450
            worth_saving = False
3146
3451
    elif minikind == 'd':
3147
3452
        link_or_sha1 = None
3148
3453
        entry[1][0] = ('d', '', 0, False, packed_stat)
3154
3459
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
3155
3460
            state._ensure_block(block_index, entry_index,
3156
3461
                               osutils.pathjoin(entry[0][0], entry[0][1]))
 
3462
        else:
 
3463
            worth_saving = False
3157
3464
    elif minikind == 'l':
 
3465
        if saved_minikind == 'l':
 
3466
            worth_saving = False
3158
3467
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
3159
3468
        if state._cutoff_time is None:
3160
3469
            state._sha_cutoff_time()
3165
3474
        else:
3166
3475
            entry[1][0] = ('l', '', stat_value.st_size,
3167
3476
                           False, DirState.NULLSTAT)
3168
 
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3477
    if worth_saving:
 
3478
        state._mark_modified([entry])
3169
3479
    return link_or_sha1
3170
3480
 
3171
3481
 
3480
3790
            raise AssertionError("don't know how to compare "
3481
3791
                "source_minikind=%r, target_minikind=%r"
3482
3792
                % (source_minikind, target_minikind))
3483
 
            ## import pdb;pdb.set_trace()
3484
3793
        return None, None
3485
3794
 
3486
3795
    def __iter__(self):