~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

Add bzrlib.pyutils, which has get_named_object, a wrapper around __import__.

This is used to replace various ad hoc implementations of the same logic,
notably the version used in registry's _LazyObjectGetter which had a bug when
getting a module without also getting a member.  And of course, this new
function has unit tests, unlike the replaced code.

This also adds a KnownHooksRegistry subclass to provide a more natural home for
some other logic.

I'm not thrilled about the name of the new module or the new functions, but it's
hard to think of good names for such generic functionality.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""DirState objects record the state of a directory and its bzr metadata.
18
18
 
20
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
21
21
are not - this is done for clarity of reading. All string data is in utf8.
22
22
 
23
 
MINIKIND = "f" | "d" | "l" | "a" | "r";
 
23
MINIKIND = "f" | "d" | "l" | "a" | "r" | "t";
24
24
NL = "\n";
25
25
NULL = "\0";
26
26
WHOLE_NUMBER = {digit}, digit;
29
29
 
30
30
dirstate format = header line, full checksum, row count, parent details,
31
31
 ghost_details, entries;
32
 
header line = "#bazaar dirstate flat format 2", NL;
33
 
full checksum = "adler32: ", ["-"], WHOLE_NUMBER, NL;
34
 
row count = "num_entries: ", digit, NL;
 
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
35
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
36
36
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
37
37
entries = {entry};
57
57
entry[1][1]: The second tree
58
58
 
59
59
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
60
 
entry[1][0][0]: kind
 
60
entry[1][0][0]: minikind
61
61
entry[1][0][1]: fingerprint
62
62
entry[1][0][2]: size
63
63
entry[1][0][3]: executable
65
65
OR (for non tree-0)
66
66
entry[1][1][4]: revision_id
67
67
 
68
 
There may be multiple rows at the root, one per id present in the root, so the in memory root row is now:
69
 
_root_entries[0][0]: ''
70
 
_root_entries[0][1]: ''
71
 
_root_entries[0][2]: file_id
72
 
_root_entries[1][0]: The tree data for the current tree for this fileid at /
 
68
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 /
73
76
etc.
74
77
 
75
78
Kinds:
79
82
'a' is an absent entry: In that tree the id is not present at this path.
80
83
'd' is a directory entry: This path in this tree is a directory with the
81
84
    current file id. There is no fingerprint for directories.
82
 
'f' is a file entry: As for directory, but its a file. The fingerprint is a
83
 
    sha1 value.
 
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.
84
88
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
85
89
    link target.
86
 
 
 
90
't' is a reference to a nested subtree; the fingerprint is the referenced
 
91
    revision.
 
92
 
 
93
Ordering:
 
94
 
 
95
The entries on disk and in memory are ordered according to the following keys:
 
96
 
 
97
    directory, as a list of components
 
98
    filename
 
99
    file-id
87
100
 
88
101
--- Format 1 had the following different definition: ---
89
102
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
90
 
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target, 
 
103
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target,
91
104
    {PARENT ROW}
92
105
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
93
106
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
106
119
where we need id->path mapping; we also usually read the whole file, so
107
120
I'm going to skip that for the moment, as we have the ability to locate
108
121
via bisect any path in any tree, and if we lookup things by path, we can
109
 
accumulate a id->path mapping as we go, which will tend to match what we
 
122
accumulate an id->path mapping as we go, which will tend to match what we
110
123
looked for.
111
124
 
112
125
I plan to implement this asap, so please speak up now to alter/tweak the
118
131
operations for the less common but still occurs a lot status/diff/commit
119
132
on specific files). Operations on specific files involve a scan for all
120
133
the children of a path, *in every involved tree*, which the current
121
 
format did not accommodate. 
 
134
format did not accommodate.
122
135
----
123
136
 
124
137
Design priorities:
131
144
Locking:
132
145
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
133
146
 been modified, but will require that we flush/ignore cached stat-hit data
134
 
 because we wont want to restat all files on disk just because a lock was
 
147
 because we won't want to restat all files on disk just because a lock was
135
148
 acquired, yet we cannot trust the data after the previous lock was released.
136
149
 
137
150
Memory representation:
138
151
 vector of all directories, and vector of the childen ?
139
 
   i.e. 
140
 
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
 
152
   i.e.
 
153
     root_entrie = (direntry for root, [parent_direntries_for_root]),
141
154
     dirblocks = [
142
155
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
143
156
     ('dir', ['achild', 'cchild', 'echild'])
146
159
    - in-order for serialisation - this is 'dirblock' grouping.
147
160
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
148
161
      insert 10K elements from scratch does not generates O(N^2) memoves of a
149
 
      single vector, rather each individual, which tends to be limited to a 
150
 
      manageable number. Will scale badly on trees with 10K entries in a 
 
162
      single vector, rather each individual, which tends to be limited to a
 
163
      manageable number. Will scale badly on trees with 10K entries in a
151
164
      single directory. compare with Inventory.InventoryDirectory which has
152
165
      a dictionary for the children. No bisect capability, can only probe for
153
 
      exact matches, or grab all elements and sorta.
154
 
    - Whats the risk of error here? Once we have the base format being processed
155
 
      we should have a net win regardless of optimality. So we are going to 
156
 
      go with what seems reasonably.
 
166
      exact matches, or grab all elements and sort.
 
167
    - What's the risk of error here? Once we have the base format being processed
 
168
      we should have a net win regardless of optimality. So we are going to
 
169
      go with what seems reasonable.
157
170
open questions:
158
171
 
159
 
maybe we should do a test profile of these core structure - 10K simulated searches/lookups/etc?
 
172
Maybe we should do a test profile of the core structure - 10K simulated
 
173
searches/lookups/etc?
160
174
 
161
175
Objects for each row?
162
176
The lifetime of Dirstate objects is current per lock, but see above for
173
187
the file on disk, and then immediately discard, the overhead of object creation
174
188
becomes a significant cost.
175
189
 
176
 
Figures: Creating a tuple from from 3 elements was profiled at 0.0625
 
190
Figures: Creating a tuple from 3 elements was profiled at 0.0625
177
191
microseconds, whereas creating a object which is subclassed from tuple was
178
192
0.500 microseconds, and creating an object with 3 elements and slots was 3
179
193
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
187
201
 
188
202
"""
189
203
 
190
 
 
191
 
import base64
192
204
import bisect
193
 
import cStringIO
 
205
import binascii
 
206
import errno
 
207
import operator
194
208
import os
195
 
import sha
 
209
from stat import S_IEXEC
 
210
import stat
196
211
import struct
 
212
import sys
 
213
import time
197
214
import zlib
198
215
 
199
216
from bzrlib import (
 
217
    cache_utf8,
 
218
    debug,
200
219
    errors,
 
220
    inventory,
 
221
    lock,
 
222
    osutils,
 
223
    static_tuple,
201
224
    trace,
202
225
    )
203
 
import bzrlib.inventory
204
 
from bzrlib import osutils
205
 
from bzrlib.osutils import (
206
 
    pathjoin,
207
 
    sha_file,
208
 
    sha_string,
209
 
    walkdirs,
210
 
    )
 
226
 
 
227
 
 
228
# This is the Windows equivalent of ENOTDIR
 
229
# It is defined in pywin32.winerror, but we don't want a strong dependency for
 
230
# just an error code.
 
231
ERROR_PATH_NOT_FOUND = 3
 
232
ERROR_DIRECTORY = 267
 
233
 
 
234
 
 
235
if not getattr(struct, '_compile', None):
 
236
    # Cannot pre-compile the dirstate pack_stat
 
237
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=struct.pack):
 
238
        """Convert stat values into a packed representation."""
 
239
        return _encode(_pack('>LLLLLL', st.st_size, int(st.st_mtime),
 
240
            int(st.st_ctime), st.st_dev, st.st_ino & 0xFFFFFFFF,
 
241
            st.st_mode))[:-1]
 
242
else:
 
243
    # compile the struct compiler we need, so as to only do it once
 
244
    from _struct import Struct
 
245
    _compiled_pack = Struct('>LLLLLL').pack
 
246
    def pack_stat(st, _encode=binascii.b2a_base64, _pack=_compiled_pack):
 
247
        """Convert stat values into a packed representation."""
 
248
        # jam 20060614 it isn't really worth removing more entries if we
 
249
        # are going to leave it in packed form.
 
250
        # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
 
251
        # With all entries, filesize is 5.9M and read time is maybe 280ms
 
252
        # well within the noise margin
 
253
 
 
254
        # base64 encoding always adds a final newline, so strip it off
 
255
        # The current version
 
256
        return _encode(_pack(st.st_size, int(st.st_mtime), int(st.st_ctime),
 
257
            st.st_dev, st.st_ino & 0xFFFFFFFF, st.st_mode))[:-1]
 
258
        # This is 0.060s / 1.520s faster by not encoding as much information
 
259
        # return _encode(_pack('>LL', int(st.st_mtime), st.st_mode))[:-1]
 
260
        # This is not strictly faster than _encode(_pack())[:-1]
 
261
        # return '%X.%X.%X.%X.%X.%X' % (
 
262
        #      st.st_size, int(st.st_mtime), int(st.st_ctime),
 
263
        #      st.st_dev, st.st_ino, st.st_mode)
 
264
        # Similar to the _encode(_pack('>LL'))
 
265
        # return '%X.%X' % (int(st.st_mtime), st.st_mode)
 
266
 
 
267
 
 
268
class SHA1Provider(object):
 
269
    """An interface for getting sha1s of a file."""
 
270
 
 
271
    def sha1(self, abspath):
 
272
        """Return the sha1 of a file given its absolute path.
 
273
 
 
274
        :param abspath:  May be a filesystem encoded absolute path
 
275
             or a unicode path.
 
276
        """
 
277
        raise NotImplementedError(self.sha1)
 
278
 
 
279
    def stat_and_sha1(self, abspath):
 
280
        """Return the stat and sha1 of a file given its absolute path.
 
281
        
 
282
        :param abspath:  May be a filesystem encoded absolute path
 
283
             or a unicode path.
 
284
 
 
285
        Note: the stat should be the stat of the physical file
 
286
        while the sha may be the sha of its canonical content.
 
287
        """
 
288
        raise NotImplementedError(self.stat_and_sha1)
 
289
 
 
290
 
 
291
class DefaultSHA1Provider(SHA1Provider):
 
292
    """A SHA1Provider that reads directly from the filesystem."""
 
293
 
 
294
    def sha1(self, abspath):
 
295
        """Return the sha1 of a file given its absolute path."""
 
296
        return osutils.sha_file_by_name(abspath)
 
297
 
 
298
    def stat_and_sha1(self, abspath):
 
299
        """Return the stat and sha1 of a file given its absolute path."""
 
300
        file_obj = file(abspath, 'rb')
 
301
        try:
 
302
            statvalue = os.fstat(file_obj.fileno())
 
303
            sha1 = osutils.sha_file(file_obj)
 
304
        finally:
 
305
            file_obj.close()
 
306
        return statvalue, sha1
211
307
 
212
308
 
213
309
class DirState(object):
215
311
 
216
312
    A dirstate is a specialised data structure for managing local working
217
313
    tree state information. Its not yet well defined whether it is platform
218
 
    specific, and if it is how we detect/parameterise that.
 
314
    specific, and if it is how we detect/parameterize that.
 
315
 
 
316
    Dirstates use the usual lock_write, lock_read and unlock mechanisms.
 
317
    Unlike most bzr disk formats, DirStates must be locked for reading, using
 
318
    lock_read.  (This is an os file lock internally.)  This is necessary
 
319
    because the file can be rewritten in place.
 
320
 
 
321
    DirStates must be explicitly written with save() to commit changes; just
 
322
    unlocking them does not write the changes to disk.
219
323
    """
220
324
 
221
 
    _kind_to_minikind = {'absent':'a', 'file':'f', 'directory':'d', 'relocated':'r', 'symlink':'l'}
222
 
    _minikind_to_kind = {'a':'absent', 'f':'file', 'd':'directory', 'l':'symlink', 'r':'relocated'}
 
325
    _kind_to_minikind = {
 
326
            'absent': 'a',
 
327
            'file': 'f',
 
328
            'directory': 'd',
 
329
            'relocated': 'r',
 
330
            'symlink': 'l',
 
331
            'tree-reference': 't',
 
332
        }
 
333
    _minikind_to_kind = {
 
334
            'a': 'absent',
 
335
            'f': 'file',
 
336
            'd': 'directory',
 
337
            'l':'symlink',
 
338
            'r': 'relocated',
 
339
            't': 'tree-reference',
 
340
        }
 
341
    _stat_to_minikind = {
 
342
        stat.S_IFDIR:'d',
 
343
        stat.S_IFREG:'f',
 
344
        stat.S_IFLNK:'l',
 
345
    }
223
346
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
224
347
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
225
348
     # it is faster.
226
349
 
 
350
    # TODO: jam 20070221 Figure out what to do if we have a record that exceeds
 
351
    #       the BISECT_PAGE_SIZE. For now, we just have to make it large enough
 
352
    #       that we are sure a single record will always fit.
 
353
    BISECT_PAGE_SIZE = 4096
 
354
 
227
355
    NOT_IN_MEMORY = 0
228
356
    IN_MEMORY_UNMODIFIED = 1
229
357
    IN_MEMORY_MODIFIED = 2
231
359
    # A pack_stat (the x's) that is just noise and will never match the output
232
360
    # of base64 encode.
233
361
    NULLSTAT = 'x' * 32
234
 
    NULL_PARENT_DETAILS = ('absent', '', 0, False, '')
235
 
 
236
 
    def __init__(self):
 
362
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
363
 
 
364
    HEADER_FORMAT_2 = '#bazaar dirstate flat format 2\n'
 
365
    HEADER_FORMAT_3 = '#bazaar dirstate flat format 3\n'
 
366
 
 
367
    def __init__(self, path, sha1_provider):
237
368
        """Create a  DirState object.
238
369
 
239
 
        Attributes of note:
240
 
 
241
 
        :attr _root_entrie: The root row of the directory/file information,
242
 
            - contains the path to / - '', ''
243
 
            - kind of 'directory',
244
 
            - the file id of the root in utf8
245
 
            - size of 0
246
 
            - a packed state
247
 
            - and no sha information.
 
370
        :param path: The path at which the dirstate file on disk should live.
 
371
        :param sha1_provider: an object meeting the SHA1Provider interface.
248
372
        """
249
373
        # _header_state and _dirblock_state represent the current state
250
374
        # of the dirstate metadata and the per-row data respectiely.
252
376
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
253
377
        #   is the same as is on disk
254
378
        # IN_MEMORY_MODIFIED indicates that we have a modified version
255
 
        #   of what is on disk. 
 
379
        #   of what is on disk.
256
380
        # In future we will add more granularity, for instance _dirblock_state
257
381
        # will probably support partially-in-memory as a separate variable,
258
382
        # allowing for partially-in-memory unmodified and partially-in-memory
259
383
        # modified states.
260
384
        self._header_state = DirState.NOT_IN_MEMORY
261
385
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
386
        # If true, an error has been detected while updating the dirstate, and
 
387
        # for safety we're not going to commit to disk.
 
388
        self._changes_aborted = False
262
389
        self._dirblocks = []
263
390
        self._ghosts = []
264
391
        self._parents = []
265
 
        self._root_entries = None
266
 
        self._state_file=None
267
 
 
268
 
    def add(self, path, file_id, kind, stat, link_or_sha1):
 
392
        self._state_file = None
 
393
        self._filename = path
 
394
        self._lock_token = None
 
395
        self._lock_state = None
 
396
        self._id_index = None
 
397
        # a map from packed_stat to sha's.
 
398
        self._packed_stat_index = None
 
399
        self._end_of_header = None
 
400
        self._cutoff_time = None
 
401
        self._split_path_cache = {}
 
402
        self._bisect_page_size = DirState.BISECT_PAGE_SIZE
 
403
        self._sha1_provider = sha1_provider
 
404
        if 'hashcache' in debug.debug_flags:
 
405
            self._sha1_file = self._sha1_file_and_mutter
 
406
        else:
 
407
            self._sha1_file = self._sha1_provider.sha1
 
408
        # These two attributes provide a simple cache for lookups into the
 
409
        # dirstate in-memory vectors. By probing respectively for the last
 
410
        # block, and for the next entry, we save nearly 2 bisections per path
 
411
        # during commit.
 
412
        self._last_block_index = None
 
413
        self._last_entry_index = None
 
414
 
 
415
    def __repr__(self):
 
416
        return "%s(%r)" % \
 
417
            (self.__class__.__name__, self._filename)
 
418
 
 
419
    def add(self, path, file_id, kind, stat, fingerprint):
269
420
        """Add a path to be tracked.
270
421
 
271
422
        :param path: The path within the dirstate - '' is the root, 'foo' is the
272
 
            path foo within the root, 'foo/bar' is the path bar within foo 
 
423
            path foo within the root, 'foo/bar' is the path bar within foo
273
424
            within the root.
274
425
        :param file_id: The file id of the path being added.
275
 
        :param kind: The kind of the path.
276
 
        :param stat: The output of os.lstate for the path.
277
 
        :param link_or_sha1: The sha value of the file, or the target of a
278
 
            symlink. '' for directories.
 
426
        :param kind: The kind of the path, as a string like 'file',
 
427
            'directory', etc.
 
428
        :param stat: The output of os.lstat for the path.
 
429
        :param fingerprint: The sha value of the file's canonical form (i.e.
 
430
            after any read filters have been applied),
 
431
            or the target of a symlink,
 
432
            or the referenced revision id for tree-references,
 
433
            or '' for directories.
279
434
        """
280
435
        # adding a file:
281
 
        # find the block its in. 
 
436
        # find the block its in.
282
437
        # find the location in the block.
283
438
        # check its not there
284
439
        # add it.
285
 
        #------- copied from bzrlib.inventory.make_entry
 
440
        #------- copied from inventory.ensure_normalized_name - keep synced.
286
441
        # --- normalized_filename wants a unicode basename only, so get one.
287
 
        dirname, basename = os.path.split(path)
 
442
        dirname, basename = osutils.split(path)
288
443
        # we dont import normalized_filename directly because we want to be
289
444
        # able to change the implementation at runtime for tests.
290
445
        norm_name, can_access = osutils.normalized_filename(basename)
293
448
                basename = norm_name
294
449
            else:
295
450
                raise errors.InvalidNormalization(path)
296
 
        # now that we've normalised, we need the correct utf8 path and 
 
451
        # you should never have files called . or ..; just add the directory
 
452
        # in the parent, or according to the special treatment for the root
 
453
        if basename == '.' or basename == '..':
 
454
            raise errors.InvalidEntryName(path)
 
455
        # now that we've normalised, we need the correct utf8 path and
297
456
        # dirname and basename elements. This single encode and split should be
298
457
        # faster than three separate encodes.
299
458
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
300
 
        dirname, basename = os.path.split(utf8path)
301
 
        self._read_dirblocks_if_needed()
302
 
        block_index = self._find_dirblock_index(dirname)
303
 
        if block_index < 0:
304
 
            # some parent path has not been added - its an error to add this
305
 
            # child
306
 
            raise errors.NotVersionedError(path, str(self))
 
459
        dirname, basename = osutils.split(utf8path)
 
460
        # uses __class__ for speed; the check is needed for safety
 
461
        if file_id.__class__ is not str:
 
462
            raise AssertionError(
 
463
                "must be a utf8 file_id not %s" % (type(file_id), ))
 
464
        # Make sure the file_id does not exist in this tree
 
465
        rename_from = None
 
466
        file_id_entry = self._get_entry(0, fileid_utf8=file_id, include_deleted=True)
 
467
        if file_id_entry != (None, None):
 
468
            if file_id_entry[1][0][0] == 'a':
 
469
                if file_id_entry[0] != (dirname, basename, file_id):
 
470
                    # set the old name's current operation to rename
 
471
                    self.update_minimal(file_id_entry[0],
 
472
                        'r',
 
473
                        path_utf8='',
 
474
                        packed_stat='',
 
475
                        fingerprint=utf8path
 
476
                    )
 
477
                    rename_from = file_id_entry[0][0:2]
 
478
            else:
 
479
                path = osutils.pathjoin(file_id_entry[0][0], file_id_entry[0][1])
 
480
                kind = DirState._minikind_to_kind[file_id_entry[1][0][0]]
 
481
                info = '%s:%s' % (kind, path)
 
482
                raise errors.DuplicateFileId(file_id, info)
 
483
        first_key = (dirname, basename, '')
 
484
        block_index, present = self._find_block_index_from_key(first_key)
 
485
        if present:
 
486
            # check the path is not in the tree
 
487
            block = self._dirblocks[block_index][1]
 
488
            entry_index, _ = self._find_entry_index(first_key, block)
 
489
            while (entry_index < len(block) and
 
490
                block[entry_index][0][0:2] == first_key[0:2]):
 
491
                if block[entry_index][1][0][0] not in 'ar':
 
492
                    # this path is in the dirstate in the current tree.
 
493
                    raise Exception, "adding already added path!"
 
494
                entry_index += 1
 
495
        else:
 
496
            # The block where we want to put the file is not present. But it
 
497
            # might be because the directory was empty, or not loaded yet. Look
 
498
            # for a parent entry, if not found, raise NotVersionedError
 
499
            parent_dir, parent_base = osutils.split(dirname)
 
500
            parent_block_idx, parent_entry_idx, _, parent_present = \
 
501
                self._get_block_entry_index(parent_dir, parent_base, 0)
 
502
            if not parent_present:
 
503
                raise errors.NotVersionedError(path, str(self))
 
504
            self._ensure_block(parent_block_idx, parent_entry_idx, dirname)
307
505
        block = self._dirblocks[block_index][1]
 
506
        entry_key = (dirname, basename, file_id)
308
507
        if stat is None:
309
508
            size = 0
310
509
            packed_stat = DirState.NULLSTAT
312
511
            size = stat.st_size
313
512
            packed_stat = pack_stat(stat)
314
513
        parent_info = self._empty_parent_info()
315
 
        entry_key = (dirname, basename, file_id.encode('utf8'))
 
514
        minikind = DirState._kind_to_minikind[kind]
 
515
        if rename_from is not None:
 
516
            if rename_from[0]:
 
517
                old_path_utf8 = '%s/%s' % rename_from
 
518
            else:
 
519
                old_path_utf8 = rename_from[1]
 
520
            parent_info[0] = ('r', old_path_utf8, 0, False, '')
316
521
        if kind == 'file':
317
522
            entry_data = entry_key, [
318
 
                (kind, link_or_sha1, size, False, packed_stat),
 
523
                (minikind, fingerprint, size, False, packed_stat),
319
524
                ] + parent_info
320
525
        elif kind == 'directory':
321
526
            entry_data = entry_key, [
322
 
                (kind, '', 0, False, packed_stat),
 
527
                (minikind, '', 0, False, packed_stat),
323
528
                ] + parent_info
324
529
        elif kind == 'symlink':
325
530
            entry_data = entry_key, [
326
 
                (kind, link_or_sha1, size, False, packed_stat),
 
531
                (minikind, fingerprint, size, False, packed_stat),
 
532
                ] + parent_info
 
533
        elif kind == 'tree-reference':
 
534
            entry_data = entry_key, [
 
535
                (minikind, fingerprint, 0, False, packed_stat),
327
536
                ] + parent_info
328
537
        else:
329
538
            raise errors.BzrError('unknown kind %r' % kind)
330
 
        entry_index = bisect.bisect_left(block, entry_data)
331
 
        if len(block) > entry_index:
332
 
            assert block[entry_index][0][1] != basename, \
333
 
                "basename %r already added" % basename
334
 
        block.insert(entry_index, entry_data)
 
539
        entry_index, present = self._find_entry_index(entry_key, block)
 
540
        if not present:
 
541
            block.insert(entry_index, entry_data)
 
542
        else:
 
543
            if block[entry_index][1][0][0] != 'a':
 
544
                raise AssertionError(" %r(%r) already added" % (basename, file_id))
 
545
            block[entry_index][1][0] = entry_data[1][0]
335
546
 
336
547
        if kind == 'directory':
337
548
           # insert a new dirblock
338
549
           self._ensure_block(block_index, entry_index, utf8path)
339
550
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
340
 
 
341
 
    def add_deleted(self, fileid_utf8, parents):
342
 
        """Add fileid_utf8 with parents as deleted."""
 
551
        if self._id_index:
 
552
            self._add_to_id_index(self._id_index, entry_key)
 
553
 
 
554
    def _bisect(self, paths):
 
555
        """Bisect through the disk structure for specific rows.
 
556
 
 
557
        :param paths: A list of paths to find
 
558
        :return: A dict mapping path => entries for found entries. Missing
 
559
                 entries will not be in the map.
 
560
                 The list is not sorted, and entries will be populated
 
561
                 based on when they were read.
 
562
        """
 
563
        self._requires_lock()
 
564
        # We need the file pointer to be right after the initial header block
 
565
        self._read_header_if_needed()
 
566
        # If _dirblock_state was in memory, we should just return info from
 
567
        # there, this function is only meant to handle when we want to read
 
568
        # part of the disk.
 
569
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
 
570
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
 
571
 
 
572
        # The disk representation is generally info + '\0\n\0' at the end. But
 
573
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
 
574
        # Because it means we can sync on the '\n'
 
575
        state_file = self._state_file
 
576
        file_size = os.fstat(state_file.fileno()).st_size
 
577
        # We end up with 2 extra fields, we should have a trailing '\n' to
 
578
        # ensure that we read the whole record, and we should have a precursur
 
579
        # '' which ensures that we start after the previous '\n'
 
580
        entry_field_count = self._fields_per_entry() + 1
 
581
 
 
582
        low = self._end_of_header
 
583
        high = file_size - 1 # Ignore the final '\0'
 
584
        # Map from (dir, name) => entry
 
585
        found = {}
 
586
 
 
587
        # Avoid infinite seeking
 
588
        max_count = 30*len(paths)
 
589
        count = 0
 
590
        # pending is a list of places to look.
 
591
        # each entry is a tuple of low, high, dir_names
 
592
        #   low -> the first byte offset to read (inclusive)
 
593
        #   high -> the last byte offset (inclusive)
 
594
        #   dir_names -> The list of (dir, name) pairs that should be found in
 
595
        #                the [low, high] range
 
596
        pending = [(low, high, paths)]
 
597
 
 
598
        page_size = self._bisect_page_size
 
599
 
 
600
        fields_to_entry = self._get_fields_to_entry()
 
601
 
 
602
        while pending:
 
603
            low, high, cur_files = pending.pop()
 
604
 
 
605
            if not cur_files or low >= high:
 
606
                # Nothing to find
 
607
                continue
 
608
 
 
609
            count += 1
 
610
            if count > max_count:
 
611
                raise errors.BzrError('Too many seeks, most likely a bug.')
 
612
 
 
613
            mid = max(low, (low+high-page_size)/2)
 
614
 
 
615
            state_file.seek(mid)
 
616
            # limit the read size, so we don't end up reading data that we have
 
617
            # already read.
 
618
            read_size = min(page_size, (high-mid)+1)
 
619
            block = state_file.read(read_size)
 
620
 
 
621
            start = mid
 
622
            entries = block.split('\n')
 
623
 
 
624
            if len(entries) < 2:
 
625
                # We didn't find a '\n', so we cannot have found any records.
 
626
                # So put this range back and try again. But we know we have to
 
627
                # increase the page size, because a single read did not contain
 
628
                # a record break (so records must be larger than page_size)
 
629
                page_size *= 2
 
630
                pending.append((low, high, cur_files))
 
631
                continue
 
632
 
 
633
            # Check the first and last entries, in case they are partial, or if
 
634
            # we don't care about the rest of this page
 
635
            first_entry_num = 0
 
636
            first_fields = entries[0].split('\0')
 
637
            if len(first_fields) < entry_field_count:
 
638
                # We didn't get the complete first entry
 
639
                # so move start, and grab the next, which
 
640
                # should be a full entry
 
641
                start += len(entries[0])+1
 
642
                first_fields = entries[1].split('\0')
 
643
                first_entry_num = 1
 
644
 
 
645
            if len(first_fields) <= 2:
 
646
                # We didn't even get a filename here... what do we do?
 
647
                # Try a large page size and repeat this query
 
648
                page_size *= 2
 
649
                pending.append((low, high, cur_files))
 
650
                continue
 
651
            else:
 
652
                # Find what entries we are looking for, which occur before and
 
653
                # after this first record.
 
654
                after = start
 
655
                if first_fields[1]:
 
656
                    first_path = first_fields[1] + '/' + first_fields[2]
 
657
                else:
 
658
                    first_path = first_fields[2]
 
659
                first_loc = _bisect_path_left(cur_files, first_path)
 
660
 
 
661
                # These exist before the current location
 
662
                pre = cur_files[:first_loc]
 
663
                # These occur after the current location, which may be in the
 
664
                # data we read, or might be after the last entry
 
665
                post = cur_files[first_loc:]
 
666
 
 
667
            if post and len(first_fields) >= entry_field_count:
 
668
                # We have files after the first entry
 
669
 
 
670
                # Parse the last entry
 
671
                last_entry_num = len(entries)-1
 
672
                last_fields = entries[last_entry_num].split('\0')
 
673
                if len(last_fields) < entry_field_count:
 
674
                    # The very last hunk was not complete,
 
675
                    # read the previous hunk
 
676
                    after = mid + len(block) - len(entries[-1])
 
677
                    last_entry_num -= 1
 
678
                    last_fields = entries[last_entry_num].split('\0')
 
679
                else:
 
680
                    after = mid + len(block)
 
681
 
 
682
                if last_fields[1]:
 
683
                    last_path = last_fields[1] + '/' + last_fields[2]
 
684
                else:
 
685
                    last_path = last_fields[2]
 
686
                last_loc = _bisect_path_right(post, last_path)
 
687
 
 
688
                middle_files = post[:last_loc]
 
689
                post = post[last_loc:]
 
690
 
 
691
                if middle_files:
 
692
                    # We have files that should occur in this block
 
693
                    # (>= first, <= last)
 
694
                    # Either we will find them here, or we can mark them as
 
695
                    # missing.
 
696
 
 
697
                    if middle_files[0] == first_path:
 
698
                        # We might need to go before this location
 
699
                        pre.append(first_path)
 
700
                    if middle_files[-1] == last_path:
 
701
                        post.insert(0, last_path)
 
702
 
 
703
                    # Find out what paths we have
 
704
                    paths = {first_path:[first_fields]}
 
705
                    # last_path might == first_path so we need to be
 
706
                    # careful if we should append rather than overwrite
 
707
                    if last_entry_num != first_entry_num:
 
708
                        paths.setdefault(last_path, []).append(last_fields)
 
709
                    for num in xrange(first_entry_num+1, last_entry_num):
 
710
                        # TODO: jam 20070223 We are already splitting here, so
 
711
                        #       shouldn't we just split the whole thing rather
 
712
                        #       than doing the split again in add_one_record?
 
713
                        fields = entries[num].split('\0')
 
714
                        if fields[1]:
 
715
                            path = fields[1] + '/' + fields[2]
 
716
                        else:
 
717
                            path = fields[2]
 
718
                        paths.setdefault(path, []).append(fields)
 
719
 
 
720
                    for path in middle_files:
 
721
                        for fields in paths.get(path, []):
 
722
                            # offset by 1 because of the opening '\0'
 
723
                            # consider changing fields_to_entry to avoid the
 
724
                            # extra list slice
 
725
                            entry = fields_to_entry(fields[1:])
 
726
                            found.setdefault(path, []).append(entry)
 
727
 
 
728
            # Now we have split up everything into pre, middle, and post, and
 
729
            # we have handled everything that fell in 'middle'.
 
730
            # We add 'post' first, so that we prefer to seek towards the
 
731
            # beginning, so that we will tend to go as early as we need, and
 
732
            # then only seek forward after that.
 
733
            if post:
 
734
                pending.append((after, high, post))
 
735
            if pre:
 
736
                pending.append((low, start-1, pre))
 
737
 
 
738
        # Consider that we may want to return the directory entries in sorted
 
739
        # order. For now, we just return them in whatever order we found them,
 
740
        # and leave it up to the caller if they care if it is ordered or not.
 
741
        return found
 
742
 
 
743
    def _bisect_dirblocks(self, dir_list):
 
744
        """Bisect through the disk structure to find entries in given dirs.
 
745
 
 
746
        _bisect_dirblocks is meant to find the contents of directories, which
 
747
        differs from _bisect, which only finds individual entries.
 
748
 
 
749
        :param dir_list: A sorted list of directory names ['', 'dir', 'foo'].
 
750
        :return: A map from dir => entries_for_dir
 
751
        """
 
752
        # TODO: jam 20070223 A lot of the bisecting logic could be shared
 
753
        #       between this and _bisect. It would require parameterizing the
 
754
        #       inner loop with a function, though. We should evaluate the
 
755
        #       performance difference.
 
756
        self._requires_lock()
 
757
        # We need the file pointer to be right after the initial header block
 
758
        self._read_header_if_needed()
 
759
        # If _dirblock_state was in memory, we should just return info from
 
760
        # there, this function is only meant to handle when we want to read
 
761
        # part of the disk.
 
762
        if self._dirblock_state != DirState.NOT_IN_MEMORY:
 
763
            raise AssertionError("bad dirblock state %r" % self._dirblock_state)
 
764
        # The disk representation is generally info + '\0\n\0' at the end. But
 
765
        # for bisecting, it is easier to treat this as '\0' + info + '\0\n'
 
766
        # Because it means we can sync on the '\n'
 
767
        state_file = self._state_file
 
768
        file_size = os.fstat(state_file.fileno()).st_size
 
769
        # We end up with 2 extra fields, we should have a trailing '\n' to
 
770
        # ensure that we read the whole record, and we should have a precursur
 
771
        # '' which ensures that we start after the previous '\n'
 
772
        entry_field_count = self._fields_per_entry() + 1
 
773
 
 
774
        low = self._end_of_header
 
775
        high = file_size - 1 # Ignore the final '\0'
 
776
        # Map from dir => entry
 
777
        found = {}
 
778
 
 
779
        # Avoid infinite seeking
 
780
        max_count = 30*len(dir_list)
 
781
        count = 0
 
782
        # pending is a list of places to look.
 
783
        # each entry is a tuple of low, high, dir_names
 
784
        #   low -> the first byte offset to read (inclusive)
 
785
        #   high -> the last byte offset (inclusive)
 
786
        #   dirs -> The list of directories that should be found in
 
787
        #                the [low, high] range
 
788
        pending = [(low, high, dir_list)]
 
789
 
 
790
        page_size = self._bisect_page_size
 
791
 
 
792
        fields_to_entry = self._get_fields_to_entry()
 
793
 
 
794
        while pending:
 
795
            low, high, cur_dirs = pending.pop()
 
796
 
 
797
            if not cur_dirs or low >= high:
 
798
                # Nothing to find
 
799
                continue
 
800
 
 
801
            count += 1
 
802
            if count > max_count:
 
803
                raise errors.BzrError('Too many seeks, most likely a bug.')
 
804
 
 
805
            mid = max(low, (low+high-page_size)/2)
 
806
 
 
807
            state_file.seek(mid)
 
808
            # limit the read size, so we don't end up reading data that we have
 
809
            # already read.
 
810
            read_size = min(page_size, (high-mid)+1)
 
811
            block = state_file.read(read_size)
 
812
 
 
813
            start = mid
 
814
            entries = block.split('\n')
 
815
 
 
816
            if len(entries) < 2:
 
817
                # We didn't find a '\n', so we cannot have found any records.
 
818
                # So put this range back and try again. But we know we have to
 
819
                # increase the page size, because a single read did not contain
 
820
                # a record break (so records must be larger than page_size)
 
821
                page_size *= 2
 
822
                pending.append((low, high, cur_dirs))
 
823
                continue
 
824
 
 
825
            # Check the first and last entries, in case they are partial, or if
 
826
            # we don't care about the rest of this page
 
827
            first_entry_num = 0
 
828
            first_fields = entries[0].split('\0')
 
829
            if len(first_fields) < entry_field_count:
 
830
                # We didn't get the complete first entry
 
831
                # so move start, and grab the next, which
 
832
                # should be a full entry
 
833
                start += len(entries[0])+1
 
834
                first_fields = entries[1].split('\0')
 
835
                first_entry_num = 1
 
836
 
 
837
            if len(first_fields) <= 1:
 
838
                # We didn't even get a dirname here... what do we do?
 
839
                # Try a large page size and repeat this query
 
840
                page_size *= 2
 
841
                pending.append((low, high, cur_dirs))
 
842
                continue
 
843
            else:
 
844
                # Find what entries we are looking for, which occur before and
 
845
                # after this first record.
 
846
                after = start
 
847
                first_dir = first_fields[1]
 
848
                first_loc = bisect.bisect_left(cur_dirs, first_dir)
 
849
 
 
850
                # These exist before the current location
 
851
                pre = cur_dirs[:first_loc]
 
852
                # These occur after the current location, which may be in the
 
853
                # data we read, or might be after the last entry
 
854
                post = cur_dirs[first_loc:]
 
855
 
 
856
            if post and len(first_fields) >= entry_field_count:
 
857
                # We have records to look at after the first entry
 
858
 
 
859
                # Parse the last entry
 
860
                last_entry_num = len(entries)-1
 
861
                last_fields = entries[last_entry_num].split('\0')
 
862
                if len(last_fields) < entry_field_count:
 
863
                    # The very last hunk was not complete,
 
864
                    # read the previous hunk
 
865
                    after = mid + len(block) - len(entries[-1])
 
866
                    last_entry_num -= 1
 
867
                    last_fields = entries[last_entry_num].split('\0')
 
868
                else:
 
869
                    after = mid + len(block)
 
870
 
 
871
                last_dir = last_fields[1]
 
872
                last_loc = bisect.bisect_right(post, last_dir)
 
873
 
 
874
                middle_files = post[:last_loc]
 
875
                post = post[last_loc:]
 
876
 
 
877
                if middle_files:
 
878
                    # We have files that should occur in this block
 
879
                    # (>= first, <= last)
 
880
                    # Either we will find them here, or we can mark them as
 
881
                    # missing.
 
882
 
 
883
                    if middle_files[0] == first_dir:
 
884
                        # We might need to go before this location
 
885
                        pre.append(first_dir)
 
886
                    if middle_files[-1] == last_dir:
 
887
                        post.insert(0, last_dir)
 
888
 
 
889
                    # Find out what paths we have
 
890
                    paths = {first_dir:[first_fields]}
 
891
                    # last_dir might == first_dir so we need to be
 
892
                    # careful if we should append rather than overwrite
 
893
                    if last_entry_num != first_entry_num:
 
894
                        paths.setdefault(last_dir, []).append(last_fields)
 
895
                    for num in xrange(first_entry_num+1, last_entry_num):
 
896
                        # TODO: jam 20070223 We are already splitting here, so
 
897
                        #       shouldn't we just split the whole thing rather
 
898
                        #       than doing the split again in add_one_record?
 
899
                        fields = entries[num].split('\0')
 
900
                        paths.setdefault(fields[1], []).append(fields)
 
901
 
 
902
                    for cur_dir in middle_files:
 
903
                        for fields in paths.get(cur_dir, []):
 
904
                            # offset by 1 because of the opening '\0'
 
905
                            # consider changing fields_to_entry to avoid the
 
906
                            # extra list slice
 
907
                            entry = fields_to_entry(fields[1:])
 
908
                            found.setdefault(cur_dir, []).append(entry)
 
909
 
 
910
            # Now we have split up everything into pre, middle, and post, and
 
911
            # we have handled everything that fell in 'middle'.
 
912
            # We add 'post' first, so that we prefer to seek towards the
 
913
            # beginning, so that we will tend to go as early as we need, and
 
914
            # then only seek forward after that.
 
915
            if post:
 
916
                pending.append((after, high, post))
 
917
            if pre:
 
918
                pending.append((low, start-1, pre))
 
919
 
 
920
        return found
 
921
 
 
922
    def _bisect_recursive(self, paths):
 
923
        """Bisect for entries for all paths and their children.
 
924
 
 
925
        This will use bisect to find all records for the supplied paths. It
 
926
        will then continue to bisect for any records which are marked as
 
927
        directories. (and renames?)
 
928
 
 
929
        :param paths: A sorted list of (dir, name) pairs
 
930
             eg: [('', 'a'), ('', 'f'), ('a/b', 'c')]
 
931
        :return: A dictionary mapping (dir, name, file_id) => [tree_info]
 
932
        """
 
933
        # Map from (dir, name, file_id) => [tree_info]
 
934
        found = {}
 
935
 
 
936
        found_dir_names = set()
 
937
 
 
938
        # Directories that have been read
 
939
        processed_dirs = set()
 
940
        # Get the ball rolling with the first bisect for all entries.
 
941
        newly_found = self._bisect(paths)
 
942
 
 
943
        while newly_found:
 
944
            # Directories that need to be read
 
945
            pending_dirs = set()
 
946
            paths_to_search = set()
 
947
            for entry_list in newly_found.itervalues():
 
948
                for dir_name_id, trees_info in entry_list:
 
949
                    found[dir_name_id] = trees_info
 
950
                    found_dir_names.add(dir_name_id[:2])
 
951
                    is_dir = False
 
952
                    for tree_info in trees_info:
 
953
                        minikind = tree_info[0]
 
954
                        if minikind == 'd':
 
955
                            if is_dir:
 
956
                                # We already processed this one as a directory,
 
957
                                # we don't need to do the extra work again.
 
958
                                continue
 
959
                            subdir, name, file_id = dir_name_id
 
960
                            path = osutils.pathjoin(subdir, name)
 
961
                            is_dir = True
 
962
                            if path not in processed_dirs:
 
963
                                pending_dirs.add(path)
 
964
                        elif minikind == 'r':
 
965
                            # Rename, we need to directly search the target
 
966
                            # which is contained in the fingerprint column
 
967
                            dir_name = osutils.split(tree_info[1])
 
968
                            if dir_name[0] in pending_dirs:
 
969
                                # This entry will be found in the dir search
 
970
                                continue
 
971
                            if dir_name not in found_dir_names:
 
972
                                paths_to_search.add(tree_info[1])
 
973
            # Now we have a list of paths to look for directly, and
 
974
            # directory blocks that need to be read.
 
975
            # newly_found is mixing the keys between (dir, name) and path
 
976
            # entries, but that is okay, because we only really care about the
 
977
            # targets.
 
978
            newly_found = self._bisect(sorted(paths_to_search))
 
979
            newly_found.update(self._bisect_dirblocks(sorted(pending_dirs)))
 
980
            processed_dirs.update(pending_dirs)
 
981
        return found
 
982
 
 
983
    def _discard_merge_parents(self):
 
984
        """Discard any parents trees beyond the first.
 
985
 
 
986
        Note that if this fails the dirstate is corrupted.
 
987
 
 
988
        After this function returns the dirstate contains 2 trees, neither of
 
989
        which are ghosted.
 
990
        """
 
991
        self._read_header_if_needed()
 
992
        parents = self.get_parent_ids()
 
993
        if len(parents) < 1:
 
994
            return
 
995
        # only require all dirblocks if we are doing a full-pass removal.
343
996
        self._read_dirblocks_if_needed()
344
 
        new_row = self._make_deleted_row(fileid_utf8, parents)
345
 
        block_index = self._find_dirblock_index(new_row[0][0])
346
 
        if block_index < 0:
347
 
            # no deleted block yet.
348
 
            bisect.insort_left(self._dirblocks, (new_row[0][0], []))
349
 
            block_index = self._find_dirblock_index(new_row[0][0])
350
 
        block = self._dirblocks[block_index][1]
351
 
        row_index = bisect.insort_left(block, new_row)
 
997
        dead_patterns = set([('a', 'r'), ('a', 'a'), ('r', 'r'), ('r', 'a')])
 
998
        def iter_entries_removable():
 
999
            for block in self._dirblocks:
 
1000
                deleted_positions = []
 
1001
                for pos, entry in enumerate(block[1]):
 
1002
                    yield entry
 
1003
                    if (entry[1][0][0], entry[1][1][0]) in dead_patterns:
 
1004
                        deleted_positions.append(pos)
 
1005
                if deleted_positions:
 
1006
                    if len(deleted_positions) == len(block[1]):
 
1007
                        del block[1][:]
 
1008
                    else:
 
1009
                        for pos in reversed(deleted_positions):
 
1010
                            del block[1][pos]
 
1011
        # if the first parent is a ghost:
 
1012
        if parents[0] in self.get_ghosts():
 
1013
            empty_parent = [DirState.NULL_PARENT_DETAILS]
 
1014
            for entry in iter_entries_removable():
 
1015
                entry[1][1:] = empty_parent
 
1016
        else:
 
1017
            for entry in iter_entries_removable():
 
1018
                del entry[1][2:]
 
1019
 
 
1020
        self._ghosts = []
 
1021
        self._parents = [parents[0]]
352
1022
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1023
        self._header_state = DirState.IN_MEMORY_MODIFIED
353
1024
 
354
1025
    def _empty_parent_info(self):
355
1026
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
356
1027
                                                    len(self._ghosts))
357
1028
 
358
1029
    def _ensure_block(self, parent_block_index, parent_row_index, dirname):
359
 
        """Enssure a block for dirname exists.
360
 
        
 
1030
        """Ensure a block for dirname exists.
 
1031
 
361
1032
        This function exists to let callers which know that there is a
362
1033
        directory dirname ensure that the block for it exists. This block can
363
1034
        fail to exist because of demand loading, or because a directory had no
375
1046
        :param dirname: The utf8 dirname to ensure there is a block for.
376
1047
        :return: The index for the block.
377
1048
        """
 
1049
        if dirname == '' and parent_row_index == 0 and parent_block_index == 0:
 
1050
            # This is the signature of the root row, and the
 
1051
            # contents-of-root row is always index 1
 
1052
            return 1
378
1053
        # the basename of the directory must be the end of its full name.
379
1054
        if not (parent_block_index == -1 and
380
1055
            parent_block_index == -1 and dirname == ''):
381
 
            assert dirname.endswith(
382
 
                self._dirblocks[parent_block_index][1][parent_row_index][0][1])
383
 
        ## In future, when doing partial parsing, this should load and 
384
 
        # populate the entire block.
385
 
        index = bisect.bisect_left(self._dirblocks, (dirname, []))
386
 
        if (index == len(self._dirblocks) or
387
 
            self._dirblocks[index][0] != dirname):
388
 
            self._dirblocks.insert(index, (dirname, []))
389
 
        return index
 
1056
            if not dirname.endswith(
 
1057
                    self._dirblocks[parent_block_index][1][parent_row_index][0][1]):
 
1058
                raise AssertionError("bad dirname %r" % dirname)
 
1059
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
 
1060
        if not present:
 
1061
            ## In future, when doing partial parsing, this should load and
 
1062
            # populate the entire block.
 
1063
            self._dirblocks.insert(block_index, (dirname, []))
 
1064
        return block_index
390
1065
 
391
1066
    def _entries_to_current_state(self, new_entries):
392
 
        """Load new_entries into self._root_entries and self.dirblocks.
 
1067
        """Load new_entries into self.dirblocks.
393
1068
 
394
1069
        Process new_entries into the current state object, making them the active
395
 
        state.
 
1070
        state.  The entries are grouped together by directory to form dirblocks.
396
1071
 
397
1072
        :param new_entries: A sorted list of entries. This function does not sort
398
1073
            to prevent unneeded overhead when callers have a sorted list already.
399
1074
        :return: Nothing.
400
1075
        """
401
 
        assert new_entries[0][0][0:2] == ('', ''), \
402
 
            "Missing root row %r" % new_entries[0][0]
403
 
        self._root_entries = []
404
 
        self._dirblocks = [('', [])]
405
 
        current_block = self._root_entries
 
1076
        if new_entries[0][0][0:2] != ('', ''):
 
1077
            raise AssertionError(
 
1078
                "Missing root row %r" % (new_entries[0][0],))
 
1079
        # The two blocks here are deliberate: the root block and the
 
1080
        # contents-of-root block.
 
1081
        self._dirblocks = [('', []), ('', [])]
 
1082
        current_block = self._dirblocks[0][1]
406
1083
        current_dirname = ''
407
1084
        root_key = ('', '')
 
1085
        append_entry = current_block.append
408
1086
        for entry in new_entries:
409
1087
            if entry[0][0] != current_dirname:
410
 
                # new block
 
1088
                # new block - different dirname
411
1089
                current_block = []
412
 
                self._dirblocks.append((entry[0][0], current_block))
413
 
            elif entry[0][0:2] != root_key:
414
 
                # this is not a root entry for a tree
415
 
                current_block = self._dirblocks[-1][1]
 
1090
                current_dirname = entry[0][0]
 
1091
                self._dirblocks.append((current_dirname, current_block))
 
1092
                append_entry = current_block.append
416
1093
            # append the entry to the current block
417
 
            current_block.append(entry)
418
 
    
 
1094
            append_entry(entry)
 
1095
        self._split_root_dirblock_into_contents()
 
1096
 
 
1097
    def _split_root_dirblock_into_contents(self):
 
1098
        """Split the root dirblocks into root and contents-of-root.
 
1099
 
 
1100
        After parsing by path, we end up with root entries and contents-of-root
 
1101
        entries in the same block. This loop splits them out again.
 
1102
        """
 
1103
        # The above loop leaves the "root block" entries mixed with the
 
1104
        # "contents-of-root block". But we don't want an if check on
 
1105
        # all entries, so instead we just fix it up here.
 
1106
        if self._dirblocks[1] != ('', []):
 
1107
            raise ValueError("bad dirblock start %r" % (self._dirblocks[1],))
 
1108
        root_block = []
 
1109
        contents_of_root_block = []
 
1110
        for entry in self._dirblocks[0][1]:
 
1111
            if not entry[0][1]: # This is a root entry
 
1112
                root_block.append(entry)
 
1113
            else:
 
1114
                contents_of_root_block.append(entry)
 
1115
        self._dirblocks[0] = ('', root_block)
 
1116
        self._dirblocks[1] = ('', contents_of_root_block)
 
1117
 
 
1118
    def _entries_for_path(self, path):
 
1119
        """Return a list with all the entries that match path for all ids."""
 
1120
        dirname, basename = os.path.split(path)
 
1121
        key = (dirname, basename, '')
 
1122
        block_index, present = self._find_block_index_from_key(key)
 
1123
        if not present:
 
1124
            # the block which should contain path is absent.
 
1125
            return []
 
1126
        result = []
 
1127
        block = self._dirblocks[block_index][1]
 
1128
        entry_index, _ = self._find_entry_index(key, block)
 
1129
        # we may need to look at multiple entries at this path: walk while the specific_files match.
 
1130
        while (entry_index < len(block) and
 
1131
            block[entry_index][0][0:2] == key[0:2]):
 
1132
            result.append(block[entry_index])
 
1133
            entry_index += 1
 
1134
        return result
 
1135
 
419
1136
    def _entry_to_line(self, entry):
420
1137
        """Serialize entry to a NULL delimited line ready for _get_output_lines.
421
 
        
 
1138
 
422
1139
        :param entry: An entry_tuple as defined in the module docstring.
423
1140
        """
424
1141
        entire_entry = list(entry[0])
425
1142
        for tree_number, tree_data in enumerate(entry[1]):
426
 
            # (kind, fingerprint, size, executable, tree_specific_string)
 
1143
            # (minikind, fingerprint, size, executable, tree_specific_string)
427
1144
            entire_entry.extend(tree_data)
428
1145
            # 3 for the key, 5 for the fields per tree.
429
1146
            tree_offset = 3 + tree_number * 5
430
 
            # kind
431
 
            entire_entry[tree_offset + 0] = DirState._kind_to_minikind[tree_data[0]]
 
1147
            # minikind
 
1148
            entire_entry[tree_offset + 0] = tree_data[0]
432
1149
            # size
433
1150
            entire_entry[tree_offset + 2] = str(tree_data[2])
434
1151
            # executable
435
1152
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
436
1153
        return '\0'.join(entire_entry)
437
1154
 
 
1155
    def _fields_per_entry(self):
 
1156
        """How many null separated fields should be in each entry row.
 
1157
 
 
1158
        Each line now has an extra '\n' field which is not used
 
1159
        so we just skip over it
 
1160
        entry size:
 
1161
            3 fields for the key
 
1162
            + number of fields per tree_data (5) * tree count
 
1163
            + newline
 
1164
         """
 
1165
        tree_count = 1 + self._num_present_parents()
 
1166
        return 3 + 5 * tree_count + 1
 
1167
 
438
1168
    def _find_block(self, key, add_if_missing=False):
439
1169
        """Return the block that key should be present in.
440
1170
 
441
1171
        :param key: A dirstate entry key.
442
1172
        :return: The block tuple.
443
1173
        """
444
 
        if key[0:2] == ('', ''):
445
 
            return self._root_entries
446
 
        else:
447
 
            block_index, present = self._find_block_index_from_key(key)
448
 
            if not present:
449
 
                if add_if_missing:
450
 
                    self._dirblocks.insert(block_index, (key[0], []))
451
 
                else:
452
 
                    # some parent path has not been added - its an error to add this
453
 
                    # child
 
1174
        block_index, present = self._find_block_index_from_key(key)
 
1175
        if not present:
 
1176
            if not add_if_missing:
 
1177
                # check to see if key is versioned itself - we might want to
 
1178
                # add it anyway, because dirs with no entries dont get a
 
1179
                # dirblock at parse time.
 
1180
                # This is an uncommon branch to take: most dirs have children,
 
1181
                # and most code works with versioned paths.
 
1182
                parent_base, parent_name = osutils.split(key[0])
 
1183
                if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
 
1184
                    # some parent path has not been added - its an error to add
 
1185
                    # this child
454
1186
                    raise errors.NotVersionedError(key[0:2], str(self))
455
 
            return self._dirblocks[block_index]
 
1187
            self._dirblocks.insert(block_index, (key[0], []))
 
1188
        return self._dirblocks[block_index]
456
1189
 
457
1190
    def _find_block_index_from_key(self, key):
458
1191
        """Find the dirblock index for a key.
459
1192
 
460
1193
        :return: The block index, True if the block for the key is present.
461
1194
        """
462
 
        block_index = bisect.bisect_left(self._dirblocks, (key[0], []))
 
1195
        if key[0:2] == ('', ''):
 
1196
            return 0, True
 
1197
        try:
 
1198
            if (self._last_block_index is not None and
 
1199
                self._dirblocks[self._last_block_index][0] == key[0]):
 
1200
                return self._last_block_index, True
 
1201
        except IndexError:
 
1202
            pass
 
1203
        block_index = bisect_dirblock(self._dirblocks, key[0], 1,
 
1204
                                      cache=self._split_path_cache)
 
1205
        # _right returns one-past-where-key is so we have to subtract
 
1206
        # one to use it. we use _right here because there are two
 
1207
        # '' blocks - the root, and the contents of root
 
1208
        # we always have a minimum of 2 in self._dirblocks: root and
 
1209
        # root-contents, and for '', we get 2 back, so this is
 
1210
        # simple and correct:
463
1211
        present = (block_index < len(self._dirblocks) and
464
1212
            self._dirblocks[block_index][0] == key[0])
 
1213
        self._last_block_index = block_index
 
1214
        # Reset the entry index cache to the beginning of the block.
 
1215
        self._last_entry_index = -1
465
1216
        return block_index, present
466
1217
 
467
 
    def _find_dirblock_index(self, dirname):
468
 
        """Find the dirblock index for dirname.
469
 
 
470
 
        :return: -1 if the dirname is not present, or the index in
471
 
            self._dirblocks for it otherwise.
472
 
        """
473
 
        block_index = bisect.bisect_left(self._dirblocks, (dirname, []))
474
 
        if (block_index == len(self._dirblocks) or
475
 
            self._dirblocks[block_index][0] != dirname):
476
 
            return -1
477
 
        return block_index
478
 
 
479
1218
    def _find_entry_index(self, key, block):
480
1219
        """Find the entry index for a key in a block.
481
1220
 
482
1221
        :return: The entry index, True if the entry for the key is present.
483
1222
        """
 
1223
        len_block = len(block)
 
1224
        try:
 
1225
            if self._last_entry_index is not None:
 
1226
                # mini-bisect here.
 
1227
                entry_index = self._last_entry_index + 1
 
1228
                # A hit is when the key is after the last slot, and before or
 
1229
                # equal to the next slot.
 
1230
                if ((entry_index > 0 and block[entry_index - 1][0] < key) and
 
1231
                    key <= block[entry_index][0]):
 
1232
                    self._last_entry_index = entry_index
 
1233
                    present = (block[entry_index][0] == key)
 
1234
                    return entry_index, present
 
1235
        except IndexError:
 
1236
            pass
484
1237
        entry_index = bisect.bisect_left(block, (key, []))
485
 
        present = (entry_index < len(block) and
 
1238
        present = (entry_index < len_block and
486
1239
            block[entry_index][0] == key)
 
1240
        self._last_entry_index = entry_index
487
1241
        return entry_index, present
488
1242
 
489
1243
    @staticmethod
490
 
    def from_tree(tree, dir_state_filename):
 
1244
    def from_tree(tree, dir_state_filename, sha1_provider=None):
491
1245
        """Create a dirstate from a bzr Tree.
492
1246
 
493
1247
        :param tree: The tree which should provide parent information and
494
1248
            inventory ids.
495
 
        """
496
 
        tree.lock_read()
497
 
        # XXX: aka the big ugly.: To fix this, turn it into:
498
 
        # init; set_path_id(root); set_parents(tree.get_parnets); write_inventory(tree.inventory)
499
 
        result = DirState()
500
 
        result._state_file = open(dir_state_filename, 'wb+')
501
 
 
502
 
        _encode = base64.encodestring
503
 
 
504
 
        parent_ids = tree.get_parent_ids()
505
 
        num_parents = len(parent_ids)
506
 
        if num_parents > 3:
507
 
            raise ValueError('Cannot handle more than 3 parents')
508
 
 
509
 
        parent_trees = []
510
 
        for parent_id in parent_ids:
511
 
            parent_trees.append(tree.branch.repository.revision_tree(parent_id))
512
 
            parent_trees[-1].lock_read()
513
 
        all_trees = [tree] + parent_trees
514
 
        num_trees = len(all_trees)
515
 
 
516
 
        # FIXME: is this utf8 safe?
517
 
 
518
 
        to_minikind = DirState._kind_to_minikind
519
 
        to_yesno = DirState._to_yesno
520
 
 
521
 
        st = os.lstat(tree.basedir)
522
 
        root_entries = []
523
 
        dirblocks = []
524
 
        for tree_index, tree in enumerate(all_trees):
525
 
            for path, tree_entry in tree.iter_entries_by_dir():
526
 
                dirname, basename = os.path.split(path.encode('utf8'))
527
 
                file_id = tree_entry.file_id.encode('utf8')
528
 
                kind = tree_entry.kind
529
 
                if kind == 'directory':
 
1249
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
1250
            If None, a DefaultSHA1Provider is used.
 
1251
        :return: a DirState object which is currently locked for writing.
 
1252
            (it was locked by DirState.initialize)
 
1253
        """
 
1254
        result = DirState.initialize(dir_state_filename,
 
1255
            sha1_provider=sha1_provider)
 
1256
        try:
 
1257
            tree.lock_read()
 
1258
            try:
 
1259
                parent_ids = tree.get_parent_ids()
 
1260
                num_parents = len(parent_ids)
 
1261
                parent_trees = []
 
1262
                for parent_id in parent_ids:
 
1263
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
 
1264
                    parent_trees.append((parent_id, parent_tree))
 
1265
                    parent_tree.lock_read()
 
1266
                result.set_parent_trees(parent_trees, [])
 
1267
                result.set_state_from_inventory(tree.inventory)
 
1268
            finally:
 
1269
                for revid, parent_tree in parent_trees:
 
1270
                    parent_tree.unlock()
 
1271
                tree.unlock()
 
1272
        except:
 
1273
            # The caller won't have a chance to unlock this, so make sure we
 
1274
            # cleanup ourselves
 
1275
            result.unlock()
 
1276
            raise
 
1277
        return result
 
1278
 
 
1279
    def update_by_delta(self, delta):
 
1280
        """Apply an inventory delta to the dirstate for tree 0
 
1281
 
 
1282
        This is the workhorse for apply_inventory_delta in dirstate based
 
1283
        trees.
 
1284
 
 
1285
        :param delta: An inventory delta.  See Inventory.apply_delta for
 
1286
            details.
 
1287
        """
 
1288
        self._read_dirblocks_if_needed()
 
1289
        encode = cache_utf8.encode
 
1290
        insertions = {}
 
1291
        removals = {}
 
1292
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1293
        # items or items placed under files/links/tree-references. We get
 
1294
        # references from every item in the delta that is not a deletion and
 
1295
        # is not itself the root.
 
1296
        parents = set()
 
1297
        # Added ids must not be in the dirstate already. This set holds those
 
1298
        # ids.
 
1299
        new_ids = set()
 
1300
        # This loop transforms the delta to single atomic operations that can
 
1301
        # be executed and validated.
 
1302
        for old_path, new_path, file_id, inv_entry in sorted(
 
1303
            inventory._check_delta_unique_old_paths(
 
1304
            inventory._check_delta_unique_new_paths(
 
1305
            inventory._check_delta_ids_match_entry(
 
1306
            inventory._check_delta_ids_are_valid(
 
1307
            inventory._check_delta_new_path_entry_both_or_None(delta))))),
 
1308
            reverse=True):
 
1309
            if (file_id in insertions) or (file_id in removals):
 
1310
                raise errors.InconsistentDelta(old_path or new_path, file_id,
 
1311
                    "repeated file_id")
 
1312
            if old_path is not None:
 
1313
                old_path = old_path.encode('utf-8')
 
1314
                removals[file_id] = old_path
 
1315
            else:
 
1316
                new_ids.add(file_id)
 
1317
            if new_path is not None:
 
1318
                if inv_entry is None:
 
1319
                    raise errors.InconsistentDelta(new_path, file_id,
 
1320
                        "new_path with no entry")
 
1321
                new_path = new_path.encode('utf-8')
 
1322
                dirname_utf8, basename = osutils.split(new_path)
 
1323
                if basename:
 
1324
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1325
                key = (dirname_utf8, basename, file_id)
 
1326
                minikind = DirState._kind_to_minikind[inv_entry.kind]
 
1327
                if minikind == 't':
 
1328
                    fingerprint = inv_entry.reference_revision or ''
 
1329
                else:
530
1330
                    fingerprint = ''
531
 
                    size = 0
532
 
                    executable = False
533
 
                elif kind == 'symlink':
534
 
                    fingerprint = tree.symlink_target(path)
535
 
                    size = 0
536
 
                    executable = False
537
 
                elif kind == 'file':
538
 
                    fingerprint = tree.get_file_sha1(tree_entry.file_id, path)
539
 
                    size = tree_entry.text_size
540
 
                    executable = tree.is_executable(tree_entry.file_id, path)
541
 
                else:
542
 
                    raise Exception
543
 
 
544
 
                key = (dirname, basename, file_id)
545
 
                if (dirname, basename) == ('', ''):
546
 
                    block = root_entries
547
 
                else:
548
 
                    # not a root entry
549
 
                    block_index = bisect.bisect_left(dirblocks, (dirname, []))
550
 
                    if block_index == len(dirblocks) or dirblocks[block_index][0] != dirname:
551
 
                        # no dirblock yet.
552
 
                        dirblocks.insert(block_index, (dirname, []))
553
 
                    block = dirblocks[block_index][1]
554
 
                # find the data for this path within block:
555
 
                entry_index = bisect.bisect_left(block, (key,))
556
 
                if entry_index == len(block) or block[entry_index][0] != key:
557
 
                    # new key in this block, add blank data
558
 
                    block.insert(entry_index, (key, [None] * num_trees))
559
 
                # get the right form of data for this trees type
560
 
                if tree_index == 0:
561
 
                    # current tree
562
 
                    st = os.lstat(tree.abspath(path))
563
 
                    tree_data = pack_stat(st)
564
 
                    if kind == 'file':
565
 
                        size = st.st_size
566
 
                else:
567
 
                    tree_data = tree_entry.revision.encode('utf8')
568
 
                block[entry_index][1][tree_index] = (
569
 
                    kind,
570
 
                    fingerprint,
571
 
                    size,
572
 
                    executable,
573
 
                    tree_data)
574
 
 
575
 
        result._set_data(parent_ids, root_entries, dirblocks)
576
 
        result.save()
577
 
        for tree in all_trees:
578
 
            tree.unlock()
579
 
        return result
 
1331
                insertions[file_id] = (key, minikind, inv_entry.executable,
 
1332
                                       fingerprint, new_path)
 
1333
            # Transform moves into delete+add pairs
 
1334
            if None not in (old_path, new_path):
 
1335
                for child in self._iter_child_entries(0, old_path):
 
1336
                    if child[0][2] in insertions or child[0][2] in removals:
 
1337
                        continue
 
1338
                    child_dirname = child[0][0]
 
1339
                    child_basename = child[0][1]
 
1340
                    minikind = child[1][0][0]
 
1341
                    fingerprint = child[1][0][4]
 
1342
                    executable = child[1][0][3]
 
1343
                    old_child_path = osutils.pathjoin(child_dirname,
 
1344
                                                      child_basename)
 
1345
                    removals[child[0][2]] = old_child_path
 
1346
                    child_suffix = child_dirname[len(old_path):]
 
1347
                    new_child_dirname = (new_path + child_suffix)
 
1348
                    key = (new_child_dirname, child_basename, child[0][2])
 
1349
                    new_child_path = osutils.pathjoin(new_child_dirname,
 
1350
                                                      child_basename)
 
1351
                    insertions[child[0][2]] = (key, minikind, executable,
 
1352
                                               fingerprint, new_child_path)
 
1353
        self._check_delta_ids_absent(new_ids, delta, 0)
 
1354
        try:
 
1355
            self._apply_removals(removals.iteritems())
 
1356
            self._apply_insertions(insertions.values())
 
1357
            # Validate parents
 
1358
            self._after_delta_check_parents(parents, 0)
 
1359
        except errors.BzrError, e:
 
1360
            self._changes_aborted = True
 
1361
            if 'integrity error' not in str(e):
 
1362
                raise
 
1363
            # _get_entry raises BzrError when a request is inconsistent; we
 
1364
            # want such errors to be shown as InconsistentDelta - and that 
 
1365
            # fits the behaviour we trigger.
 
1366
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
 
1367
 
 
1368
    def _apply_removals(self, removals):
 
1369
        for file_id, path in sorted(removals, reverse=True,
 
1370
            key=operator.itemgetter(1)):
 
1371
            dirname, basename = osutils.split(path)
 
1372
            block_i, entry_i, d_present, f_present = \
 
1373
                self._get_block_entry_index(dirname, basename, 0)
 
1374
            try:
 
1375
                entry = self._dirblocks[block_i][1][entry_i]
 
1376
            except IndexError:
 
1377
                self._changes_aborted = True
 
1378
                raise errors.InconsistentDelta(path, file_id,
 
1379
                    "Wrong path for old path.")
 
1380
            if not f_present or entry[1][0][0] in 'ar':
 
1381
                self._changes_aborted = True
 
1382
                raise errors.InconsistentDelta(path, file_id,
 
1383
                    "Wrong path for old path.")
 
1384
            if file_id != entry[0][2]:
 
1385
                self._changes_aborted = True
 
1386
                raise errors.InconsistentDelta(path, file_id,
 
1387
                    "Attempt to remove path has wrong id - found %r."
 
1388
                    % entry[0][2])
 
1389
            self._make_absent(entry)
 
1390
            # See if we have a malformed delta: deleting a directory must not
 
1391
            # leave crud behind. This increases the number of bisects needed
 
1392
            # substantially, but deletion or renames of large numbers of paths
 
1393
            # is rare enough it shouldn't be an issue (famous last words?) RBC
 
1394
            # 20080730.
 
1395
            block_i, entry_i, d_present, f_present = \
 
1396
                self._get_block_entry_index(path, '', 0)
 
1397
            if d_present:
 
1398
                # The dir block is still present in the dirstate; this could
 
1399
                # be due to it being in a parent tree, or a corrupt delta.
 
1400
                for child_entry in self._dirblocks[block_i][1]:
 
1401
                    if child_entry[1][0][0] not in ('r', 'a'):
 
1402
                        self._changes_aborted = True
 
1403
                        raise errors.InconsistentDelta(path, entry[0][2],
 
1404
                            "The file id was deleted but its children were "
 
1405
                            "not deleted.")
 
1406
 
 
1407
    def _apply_insertions(self, adds):
 
1408
        try:
 
1409
            for key, minikind, executable, fingerprint, path_utf8 in sorted(adds):
 
1410
                self.update_minimal(key, minikind, executable, fingerprint,
 
1411
                                    path_utf8=path_utf8)
 
1412
        except errors.NotVersionedError:
 
1413
            self._changes_aborted = True
 
1414
            raise errors.InconsistentDelta(path_utf8.decode('utf8'), key[2],
 
1415
                "Missing parent")
 
1416
 
 
1417
    def update_basis_by_delta(self, delta, new_revid):
 
1418
        """Update the parents of this tree after a commit.
 
1419
 
 
1420
        This gives the tree one parent, with revision id new_revid. The
 
1421
        inventory delta is applied to the current basis tree to generate the
 
1422
        inventory for the parent new_revid, and all other parent trees are
 
1423
        discarded.
 
1424
 
 
1425
        Note that an exception during the operation of this method will leave
 
1426
        the dirstate in a corrupt state where it should not be saved.
 
1427
 
 
1428
        Finally, we expect all changes to be synchronising the basis tree with
 
1429
        the working tree.
 
1430
 
 
1431
        :param new_revid: The new revision id for the trees parent.
 
1432
        :param delta: An inventory delta (see apply_inventory_delta) describing
 
1433
            the changes from the current left most parent revision to new_revid.
 
1434
        """
 
1435
        self._read_dirblocks_if_needed()
 
1436
        self._discard_merge_parents()
 
1437
        if self._ghosts != []:
 
1438
            raise NotImplementedError(self.update_basis_by_delta)
 
1439
        if len(self._parents) == 0:
 
1440
            # setup a blank tree, the most simple way.
 
1441
            empty_parent = DirState.NULL_PARENT_DETAILS
 
1442
            for entry in self._iter_entries():
 
1443
                entry[1].append(empty_parent)
 
1444
            self._parents.append(new_revid)
 
1445
 
 
1446
        self._parents[0] = new_revid
 
1447
 
 
1448
        delta = sorted(delta, reverse=True)
 
1449
        adds = []
 
1450
        changes = []
 
1451
        deletes = []
 
1452
        # The paths this function accepts are unicode and must be encoded as we
 
1453
        # go.
 
1454
        encode = cache_utf8.encode
 
1455
        inv_to_entry = self._inv_entry_to_details
 
1456
        # delta is now (deletes, changes), (adds) in reverse lexographical
 
1457
        # order.
 
1458
        # deletes in reverse lexographic order are safe to process in situ.
 
1459
        # renames are not, as a rename from any path could go to a path
 
1460
        # lexographically lower, so we transform renames into delete, add pairs,
 
1461
        # expanding them recursively as needed.
 
1462
        # At the same time, to reduce interface friction we convert the input
 
1463
        # inventory entries to dirstate.
 
1464
        root_only = ('', '')
 
1465
        # Accumulate parent references (path_utf8, id), to check for parentless
 
1466
        # items or items placed under files/links/tree-references. We get
 
1467
        # references from every item in the delta that is not a deletion and
 
1468
        # is not itself the root.
 
1469
        parents = set()
 
1470
        # Added ids must not be in the dirstate already. This set holds those
 
1471
        # ids.
 
1472
        new_ids = set()
 
1473
        for old_path, new_path, file_id, inv_entry in delta:
 
1474
            if inv_entry is not None and file_id != inv_entry.file_id:
 
1475
                raise errors.InconsistentDelta(new_path, file_id,
 
1476
                    "mismatched entry file_id %r" % inv_entry)
 
1477
            if new_path is not None:
 
1478
                if inv_entry is None:
 
1479
                    raise errors.InconsistentDelta(new_path, file_id,
 
1480
                        "new_path with no entry")
 
1481
                new_path_utf8 = encode(new_path)
 
1482
                # note the parent for validation
 
1483
                dirname_utf8, basename_utf8 = osutils.split(new_path_utf8)
 
1484
                if basename_utf8:
 
1485
                    parents.add((dirname_utf8, inv_entry.parent_id))
 
1486
            if old_path is None:
 
1487
                adds.append((None, encode(new_path), file_id,
 
1488
                    inv_to_entry(inv_entry), True))
 
1489
                new_ids.add(file_id)
 
1490
            elif new_path is None:
 
1491
                deletes.append((encode(old_path), None, file_id, None, True))
 
1492
            elif (old_path, new_path) != root_only:
 
1493
                # Renames:
 
1494
                # Because renames must preserve their children we must have
 
1495
                # processed all relocations and removes before hand. The sort
 
1496
                # order ensures we've examined the child paths, but we also
 
1497
                # have to execute the removals, or the split to an add/delete
 
1498
                # pair will result in the deleted item being reinserted, or
 
1499
                # renamed items being reinserted twice - and possibly at the
 
1500
                # wrong place. Splitting into a delete/add pair also simplifies
 
1501
                # the handling of entries with ('f', ...), ('r' ...) because
 
1502
                # the target of the 'r' is old_path here, and we add that to
 
1503
                # deletes, meaning that the add handler does not need to check
 
1504
                # for 'r' items on every pass.
 
1505
                self._update_basis_apply_deletes(deletes)
 
1506
                deletes = []
 
1507
                # Split into an add/delete pair recursively.
 
1508
                adds.append((None, new_path_utf8, file_id,
 
1509
                    inv_to_entry(inv_entry), False))
 
1510
                # Expunge deletes that we've seen so that deleted/renamed
 
1511
                # children of a rename directory are handled correctly.
 
1512
                new_deletes = reversed(list(self._iter_child_entries(1,
 
1513
                    encode(old_path))))
 
1514
                # Remove the current contents of the tree at orig_path, and
 
1515
                # reinsert at the correct new path.
 
1516
                for entry in new_deletes:
 
1517
                    if entry[0][0]:
 
1518
                        source_path = entry[0][0] + '/' + entry[0][1]
 
1519
                    else:
 
1520
                        source_path = entry[0][1]
 
1521
                    if new_path_utf8:
 
1522
                        target_path = new_path_utf8 + source_path[len(old_path):]
 
1523
                    else:
 
1524
                        if old_path == '':
 
1525
                            raise AssertionError("cannot rename directory to"
 
1526
                                " itself")
 
1527
                        target_path = source_path[len(old_path) + 1:]
 
1528
                    adds.append((None, target_path, entry[0][2], entry[1][1], False))
 
1529
                    deletes.append(
 
1530
                        (source_path, target_path, entry[0][2], None, False))
 
1531
                deletes.append(
 
1532
                    (encode(old_path), new_path, file_id, None, False))
 
1533
            else:
 
1534
                # changes to just the root should not require remove/insertion
 
1535
                # of everything.
 
1536
                changes.append((encode(old_path), encode(new_path), file_id,
 
1537
                    inv_to_entry(inv_entry)))
 
1538
        self._check_delta_ids_absent(new_ids, delta, 1)
 
1539
        try:
 
1540
            # Finish expunging deletes/first half of renames.
 
1541
            self._update_basis_apply_deletes(deletes)
 
1542
            # Reinstate second half of renames and new paths.
 
1543
            self._update_basis_apply_adds(adds)
 
1544
            # Apply in-situ changes.
 
1545
            self._update_basis_apply_changes(changes)
 
1546
            # Validate parents
 
1547
            self._after_delta_check_parents(parents, 1)
 
1548
        except errors.BzrError, e:
 
1549
            self._changes_aborted = True
 
1550
            if 'integrity error' not in str(e):
 
1551
                raise
 
1552
            # _get_entry raises BzrError when a request is inconsistent; we
 
1553
            # want such errors to be shown as InconsistentDelta - and that 
 
1554
            # fits the behaviour we trigger. Partof this is driven by dirstate
 
1555
            # only supporting deltas that turn the basis into a closer fit to
 
1556
            # the active tree.
 
1557
            raise errors.InconsistentDeltaDelta(delta, "error from _get_entry.")
 
1558
 
 
1559
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1560
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1561
        self._id_index = None
 
1562
        return
 
1563
 
 
1564
    def _check_delta_ids_absent(self, new_ids, delta, tree_index):
 
1565
        """Check that none of the file_ids in new_ids are present in a tree."""
 
1566
        if not new_ids:
 
1567
            return
 
1568
        id_index = self._get_id_index()
 
1569
        for file_id in new_ids:
 
1570
            for key in id_index.get(file_id, ()):
 
1571
                block_i, entry_i, d_present, f_present = \
 
1572
                    self._get_block_entry_index(key[0], key[1], tree_index)
 
1573
                if not f_present:
 
1574
                    # In a different tree
 
1575
                    continue
 
1576
                entry = self._dirblocks[block_i][1][entry_i]
 
1577
                if entry[0][2] != file_id:
 
1578
                    # Different file_id, so not what we want.
 
1579
                    continue
 
1580
                # NB: No changes made before this helper is called, so no need
 
1581
                # to set the _changes_aborted flag.
 
1582
                raise errors.InconsistentDelta(
 
1583
                    ("%s/%s" % key[0:2]).decode('utf8'), file_id,
 
1584
                    "This file_id is new in the delta but already present in "
 
1585
                    "the target")
 
1586
 
 
1587
    def _update_basis_apply_adds(self, adds):
 
1588
        """Apply a sequence of adds to tree 1 during update_basis_by_delta.
 
1589
 
 
1590
        They may be adds, or renames that have been split into add/delete
 
1591
        pairs.
 
1592
 
 
1593
        :param adds: A sequence of adds. Each add is a tuple:
 
1594
            (None, new_path_utf8, file_id, (entry_details), real_add). real_add
 
1595
            is False when the add is the second half of a remove-and-reinsert
 
1596
            pair created to handle renames and deletes.
 
1597
        """
 
1598
        # Adds are accumulated partly from renames, so can be in any input
 
1599
        # order - sort it.
 
1600
        adds.sort()
 
1601
        # adds is now in lexographic order, which places all parents before
 
1602
        # their children, so we can process it linearly.
 
1603
        absent = 'ar'
 
1604
        for old_path, new_path, file_id, new_details, real_add in adds:
 
1605
            # the entry for this file_id must be in tree 0.
 
1606
            entry = self._get_entry(0, file_id, new_path)
 
1607
            if entry[0] is None or entry[0][2] != file_id:
 
1608
                self._changes_aborted = True
 
1609
                raise errors.InconsistentDelta(new_path, file_id,
 
1610
                    'working tree does not contain new entry')
 
1611
            if real_add and entry[1][1][0] not in absent:
 
1612
                self._changes_aborted = True
 
1613
                raise errors.InconsistentDelta(new_path, file_id,
 
1614
                    'The entry was considered to be a genuinely new record,'
 
1615
                    ' but there was already an old record for it.')
 
1616
            # We don't need to update the target of an 'r' because the handling
 
1617
            # of renames turns all 'r' situations into a delete at the original
 
1618
            # location.
 
1619
            entry[1][1] = new_details
 
1620
 
 
1621
    def _update_basis_apply_changes(self, changes):
 
1622
        """Apply a sequence of changes to tree 1 during update_basis_by_delta.
 
1623
 
 
1624
        :param adds: A sequence of changes. Each change is a tuple:
 
1625
            (path_utf8, path_utf8, file_id, (entry_details))
 
1626
        """
 
1627
        absent = 'ar'
 
1628
        for old_path, new_path, file_id, new_details in changes:
 
1629
            # the entry for this file_id must be in tree 0.
 
1630
            entry = self._get_entry(0, file_id, new_path)
 
1631
            if entry[0] is None or entry[0][2] != file_id:
 
1632
                self._changes_aborted = True
 
1633
                raise errors.InconsistentDelta(new_path, file_id,
 
1634
                    'working tree does not contain new entry')
 
1635
            if (entry[1][0][0] in absent or
 
1636
                entry[1][1][0] in absent):
 
1637
                self._changes_aborted = True
 
1638
                raise errors.InconsistentDelta(new_path, file_id,
 
1639
                    'changed considered absent')
 
1640
            entry[1][1] = new_details
 
1641
 
 
1642
    def _update_basis_apply_deletes(self, deletes):
 
1643
        """Apply a sequence of deletes to tree 1 during update_basis_by_delta.
 
1644
 
 
1645
        They may be deletes, or renames that have been split into add/delete
 
1646
        pairs.
 
1647
 
 
1648
        :param deletes: A sequence of deletes. Each delete is a tuple:
 
1649
            (old_path_utf8, new_path_utf8, file_id, None, real_delete).
 
1650
            real_delete is True when the desired outcome is an actual deletion
 
1651
            rather than the rename handling logic temporarily deleting a path
 
1652
            during the replacement of a parent.
 
1653
        """
 
1654
        null = DirState.NULL_PARENT_DETAILS
 
1655
        for old_path, new_path, file_id, _, real_delete in deletes:
 
1656
            if real_delete != (new_path is None):
 
1657
                self._changes_aborted = True
 
1658
                raise AssertionError("bad delete delta")
 
1659
            # the entry for this file_id must be in tree 1.
 
1660
            dirname, basename = osutils.split(old_path)
 
1661
            block_index, entry_index, dir_present, file_present = \
 
1662
                self._get_block_entry_index(dirname, basename, 1)
 
1663
            if not file_present:
 
1664
                self._changes_aborted = True
 
1665
                raise errors.InconsistentDelta(old_path, file_id,
 
1666
                    'basis tree does not contain removed entry')
 
1667
            entry = self._dirblocks[block_index][1][entry_index]
 
1668
            if entry[0][2] != file_id:
 
1669
                self._changes_aborted = True
 
1670
                raise errors.InconsistentDelta(old_path, file_id,
 
1671
                    'mismatched file_id in tree 1')
 
1672
            if real_delete:
 
1673
                if entry[1][0][0] != 'a':
 
1674
                    self._changes_aborted = True
 
1675
                    raise errors.InconsistentDelta(old_path, file_id,
 
1676
                            'This was marked as a real delete, but the WT state'
 
1677
                            ' claims that it still exists and is versioned.')
 
1678
                del self._dirblocks[block_index][1][entry_index]
 
1679
            else:
 
1680
                if entry[1][0][0] == 'a':
 
1681
                    self._changes_aborted = True
 
1682
                    raise errors.InconsistentDelta(old_path, file_id,
 
1683
                        'The entry was considered a rename, but the source path'
 
1684
                        ' is marked as absent.')
 
1685
                    # For whatever reason, we were asked to rename an entry
 
1686
                    # that was originally marked as deleted. This could be
 
1687
                    # because we are renaming the parent directory, and the WT
 
1688
                    # current state has the file marked as deleted.
 
1689
                elif entry[1][0][0] == 'r':
 
1690
                    # implement the rename
 
1691
                    del self._dirblocks[block_index][1][entry_index]
 
1692
                else:
 
1693
                    # it is being resurrected here, so blank it out temporarily.
 
1694
                    self._dirblocks[block_index][1][entry_index][1][1] = null
 
1695
 
 
1696
    def _after_delta_check_parents(self, parents, index):
 
1697
        """Check that parents required by the delta are all intact.
 
1698
        
 
1699
        :param parents: An iterable of (path_utf8, file_id) tuples which are
 
1700
            required to be present in tree 'index' at path_utf8 with id file_id
 
1701
            and be a directory.
 
1702
        :param index: The column in the dirstate to check for parents in.
 
1703
        """
 
1704
        for dirname_utf8, file_id in parents:
 
1705
            # Get the entry - the ensures that file_id, dirname_utf8 exists and
 
1706
            # has the right file id.
 
1707
            entry = self._get_entry(index, file_id, dirname_utf8)
 
1708
            if entry[1] is None:
 
1709
                self._changes_aborted = True
 
1710
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1711
                    file_id, "This parent is not present.")
 
1712
            # Parents of things must be directories
 
1713
            if entry[1][index][0] != 'd':
 
1714
                self._changes_aborted = True
 
1715
                raise errors.InconsistentDelta(dirname_utf8.decode('utf8'),
 
1716
                    file_id, "This parent is not a directory.")
 
1717
 
 
1718
    def _observed_sha1(self, entry, sha1, stat_value,
 
1719
        _stat_to_minikind=_stat_to_minikind, _pack_stat=pack_stat):
 
1720
        """Note the sha1 of a file.
 
1721
 
 
1722
        :param entry: The entry the sha1 is for.
 
1723
        :param sha1: The observed sha1.
 
1724
        :param stat_value: The os.lstat for the file.
 
1725
        """
 
1726
        try:
 
1727
            minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
 
1728
        except KeyError:
 
1729
            # Unhandled kind
 
1730
            return None
 
1731
        packed_stat = _pack_stat(stat_value)
 
1732
        if minikind == 'f':
 
1733
            if self._cutoff_time is None:
 
1734
                self._sha_cutoff_time()
 
1735
            if (stat_value.st_mtime < self._cutoff_time
 
1736
                and stat_value.st_ctime < self._cutoff_time):
 
1737
                entry[1][0] = ('f', sha1, entry[1][0][2], entry[1][0][3],
 
1738
                    packed_stat)
 
1739
                self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1740
 
 
1741
    def _sha_cutoff_time(self):
 
1742
        """Return cutoff time.
 
1743
 
 
1744
        Files modified more recently than this time are at risk of being
 
1745
        undetectably modified and so can't be cached.
 
1746
        """
 
1747
        # Cache the cutoff time as long as we hold a lock.
 
1748
        # time.time() isn't super expensive (approx 3.38us), but
 
1749
        # when you call it 50,000 times it adds up.
 
1750
        # For comparison, os.lstat() costs 7.2us if it is hot.
 
1751
        self._cutoff_time = int(time.time()) - 3
 
1752
        return self._cutoff_time
 
1753
 
 
1754
    def _lstat(self, abspath, entry):
 
1755
        """Return the os.lstat value for this path."""
 
1756
        return os.lstat(abspath)
 
1757
 
 
1758
    def _sha1_file_and_mutter(self, abspath):
 
1759
        # when -Dhashcache is turned on, this is monkey-patched in to log
 
1760
        # file reads
 
1761
        trace.mutter("dirstate sha1 " + abspath)
 
1762
        return self._sha1_provider.sha1(abspath)
 
1763
 
 
1764
    def _is_executable(self, mode, old_executable):
 
1765
        """Is this file executable?"""
 
1766
        return bool(S_IEXEC & mode)
 
1767
 
 
1768
    def _is_executable_win32(self, mode, old_executable):
 
1769
        """On win32 the executable bit is stored in the dirstate."""
 
1770
        return old_executable
 
1771
 
 
1772
    if sys.platform == 'win32':
 
1773
        _is_executable = _is_executable_win32
 
1774
 
 
1775
    def _read_link(self, abspath, old_link):
 
1776
        """Read the target of a symlink"""
 
1777
        # TODO: jam 200700301 On Win32, this could just return the value
 
1778
        #       already in memory. However, this really needs to be done at a
 
1779
        #       higher level, because there either won't be anything on disk,
 
1780
        #       or the thing on disk will be a file.
 
1781
        fs_encoding = osutils._fs_enc
 
1782
        if isinstance(abspath, unicode):
 
1783
            # abspath is defined as the path to pass to lstat. readlink is
 
1784
            # buggy in python < 2.6 (it doesn't encode unicode path into FS
 
1785
            # encoding), so we need to encode ourselves knowing that unicode
 
1786
            # paths are produced by UnicodeDirReader on purpose.
 
1787
            abspath = abspath.encode(fs_encoding)
 
1788
        target = os.readlink(abspath)
 
1789
        if fs_encoding not in ('UTF-8', 'US-ASCII', 'ANSI_X3.4-1968'):
 
1790
            # Change encoding if needed
 
1791
            target = target.decode(fs_encoding).encode('UTF-8')
 
1792
        return target
580
1793
 
581
1794
    def get_ghosts(self):
582
1795
        """Return a list of the parent tree revision ids that are ghosts."""
605
1818
        """Create a line for the state file for parents information."""
606
1819
        return '\0'.join([str(len(parent_ids))] + parent_ids)
607
1820
 
 
1821
    def _get_fields_to_entry(self):
 
1822
        """Get a function which converts entry fields into a entry record.
 
1823
 
 
1824
        This handles size and executable, as well as parent records.
 
1825
 
 
1826
        :return: A function which takes a list of fields, and returns an
 
1827
            appropriate record for storing in memory.
 
1828
        """
 
1829
        # This is intentionally unrolled for performance
 
1830
        num_present_parents = self._num_present_parents()
 
1831
        if num_present_parents == 0:
 
1832
            def fields_to_entry_0_parents(fields, _int=int):
 
1833
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1834
                return (path_name_file_id_key, [
 
1835
                    ( # Current tree
 
1836
                        fields[3],                # minikind
 
1837
                        fields[4],                # fingerprint
 
1838
                        _int(fields[5]),          # size
 
1839
                        fields[6] == 'y',         # executable
 
1840
                        fields[7],                # packed_stat or revision_id
 
1841
                    )])
 
1842
            return fields_to_entry_0_parents
 
1843
        elif num_present_parents == 1:
 
1844
            def fields_to_entry_1_parent(fields, _int=int):
 
1845
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1846
                return (path_name_file_id_key, [
 
1847
                    ( # Current tree
 
1848
                        fields[3],                # minikind
 
1849
                        fields[4],                # fingerprint
 
1850
                        _int(fields[5]),          # size
 
1851
                        fields[6] == 'y',         # executable
 
1852
                        fields[7],                # packed_stat or revision_id
 
1853
                    ),
 
1854
                    ( # Parent 1
 
1855
                        fields[8],                # minikind
 
1856
                        fields[9],                # fingerprint
 
1857
                        _int(fields[10]),         # size
 
1858
                        fields[11] == 'y',        # executable
 
1859
                        fields[12],               # packed_stat or revision_id
 
1860
                    ),
 
1861
                    ])
 
1862
            return fields_to_entry_1_parent
 
1863
        elif num_present_parents == 2:
 
1864
            def fields_to_entry_2_parents(fields, _int=int):
 
1865
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1866
                return (path_name_file_id_key, [
 
1867
                    ( # Current tree
 
1868
                        fields[3],                # minikind
 
1869
                        fields[4],                # fingerprint
 
1870
                        _int(fields[5]),          # size
 
1871
                        fields[6] == 'y',         # executable
 
1872
                        fields[7],                # packed_stat or revision_id
 
1873
                    ),
 
1874
                    ( # Parent 1
 
1875
                        fields[8],                # minikind
 
1876
                        fields[9],                # fingerprint
 
1877
                        _int(fields[10]),         # size
 
1878
                        fields[11] == 'y',        # executable
 
1879
                        fields[12],               # packed_stat or revision_id
 
1880
                    ),
 
1881
                    ( # Parent 2
 
1882
                        fields[13],               # minikind
 
1883
                        fields[14],               # fingerprint
 
1884
                        _int(fields[15]),         # size
 
1885
                        fields[16] == 'y',        # executable
 
1886
                        fields[17],               # packed_stat or revision_id
 
1887
                    ),
 
1888
                    ])
 
1889
            return fields_to_entry_2_parents
 
1890
        else:
 
1891
            def fields_to_entry_n_parents(fields, _int=int):
 
1892
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
1893
                trees = [(fields[cur],                # minikind
 
1894
                          fields[cur+1],              # fingerprint
 
1895
                          _int(fields[cur+2]),        # size
 
1896
                          fields[cur+3] == 'y',       # executable
 
1897
                          fields[cur+4],              # stat or revision_id
 
1898
                         ) for cur in xrange(3, len(fields)-1, 5)]
 
1899
                return path_name_file_id_key, trees
 
1900
            return fields_to_entry_n_parents
 
1901
 
608
1902
    def get_parent_ids(self):
609
1903
        """Return a list of the parent tree ids for the directory state."""
610
1904
        self._read_header_if_needed()
619
1913
            be attempted.
620
1914
        :return: A tuple describing where the path is located, or should be
621
1915
            inserted. The tuple contains four fields: the block index, the row
622
 
            index, anda two booleans are True when the directory is present, and
623
 
            when the entire path is present.  There is no guarantee that either
 
1916
            index, the directory is present (boolean), the entire path is
 
1917
            present (boolean).  There is no guarantee that either
624
1918
            coordinate is currently reachable unless the found field for it is
625
1919
            True. For instance, a directory not present in the searched tree
626
1920
            may be returned with a value one greater than the current highest
630
1924
            rather it indicates that there are at least some files in some
631
1925
            tree present there.
632
1926
        """
633
 
        # looking up the root is not supported, because the root entries exist
634
 
        # outside the used coordinate system
635
 
        assert not (dirname == '' and basename == ''), 'blackhole lookup error'
636
1927
        self._read_dirblocks_if_needed()
637
 
        block_index = bisect.bisect_left(self._dirblocks, (dirname, []))
638
 
        if (block_index == len(self._dirblocks) or
639
 
            self._dirblocks[block_index][0] != dirname):
 
1928
        key = dirname, basename, ''
 
1929
        block_index, present = self._find_block_index_from_key(key)
 
1930
        if not present:
640
1931
            # no such directory - return the dir index and 0 for the row.
641
1932
            return block_index, 0, False, False
642
1933
        block = self._dirblocks[block_index][1] # access the entries only
643
 
        search = ((dirname, basename),)
644
 
        row_index = bisect.bisect_left(block, search)
645
 
        # linear search through present entries at this path to find the one
 
1934
        entry_index, present = self._find_entry_index(key, block)
 
1935
        # linear search through entries at this path to find the one
646
1936
        # requested.
647
 
        while row_index < len(block) and block[row_index][0][1] == basename:
648
 
            if block[row_index][1][tree_index] not in ('absent', 'relocated'):
649
 
                return block_index, row_index, True, True
650
 
            row += 1
651
 
        return block_index, row_index, True, False
 
1937
        while entry_index < len(block) and block[entry_index][0][1] == basename:
 
1938
            if block[entry_index][1][tree_index][0] not in 'ar':
 
1939
                # neither absent or relocated
 
1940
                return block_index, entry_index, True, True
 
1941
            entry_index += 1
 
1942
        return block_index, entry_index, True, False
652
1943
 
653
 
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
654
 
        """Get the dirstate entry for path in tree tree_index
 
1944
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None, include_deleted=False):
 
1945
        """Get the dirstate entry for path in tree tree_index.
655
1946
 
656
1947
        If either file_id or path is supplied, it is used as the key to lookup.
657
1948
        If both are supplied, the fastest lookup is used, and an error is
658
1949
        raised if they do not both point at the same row.
659
 
        
 
1950
 
660
1951
        :param tree_index: The index of the tree we wish to locate this path
661
1952
            in. If the path is present in that tree, the entry containing its
662
1953
            details is returned, otherwise (None, None) is returned
 
1954
            0 is the working tree, higher indexes are successive parent
 
1955
            trees.
663
1956
        :param fileid_utf8: A utf8 file_id to look up.
664
1957
        :param path_utf8: An utf8 path to be looked up.
 
1958
        :param include_deleted: If True, and performing a lookup via
 
1959
            fileid_utf8 rather than path_utf8, return an entry for deleted
 
1960
            (absent) paths.
665
1961
        :return: The dirstate entry tuple for path, or (None, None)
666
1962
        """
667
 
        if path_utf8 is not None:
668
 
            assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
669
1963
        self._read_dirblocks_if_needed()
670
1964
        if path_utf8 is not None:
 
1965
            if type(path_utf8) is not str:
 
1966
                raise errors.BzrError('path_utf8 is not a str: %s %r'
 
1967
                    % (type(path_utf8), path_utf8))
671
1968
            # path lookups are faster
672
 
            if path_utf8 == '':
673
 
                for entry in self._root_entries:
674
 
                    if entry[1][tree_index] not in ('absent', 'relocated'):
675
 
                        return entry
676
 
                raise Exception, 'rootless trees not supported yet'
677
 
            dirname, basename = os.path.split(path_utf8)
 
1969
            dirname, basename = osutils.split(path_utf8)
678
1970
            block_index, entry_index, dir_present, file_present = \
679
1971
                self._get_block_entry_index(dirname, basename, tree_index)
680
1972
            if not file_present:
681
1973
                return None, None
682
1974
            entry = self._dirblocks[block_index][1][entry_index]
683
 
            assert entry[0][2] and entry[1][tree_index][0] not in ('absent', 'relocated'), 'unversioned entry?!?!'
 
1975
            if not (entry[0][2] and entry[1][tree_index][0] not in ('a', 'r')):
 
1976
                raise AssertionError('unversioned entry?')
684
1977
            if fileid_utf8:
685
1978
                if entry[0][2] != fileid_utf8:
686
 
                    raise BzrError('integrity error ? : mismatching tree_index, file_id and path')
 
1979
                    self._changes_aborted = True
 
1980
                    raise errors.BzrError('integrity error ? : mismatching'
 
1981
                                          ' tree_index, file_id and path')
687
1982
            return entry
688
1983
        else:
689
 
            for entry in self._iter_entries():
690
 
                if entry[0][2] == fileid_utf8:
691
 
                    if entry[1][tree_index][0] == 'relocated':
692
 
                        # look up the real location directly by path
693
 
                        return self._get_entry(tree_index,
694
 
                            fileid_utf8=fileid_utf8,
695
 
                            path_utf8=entry[1][tree_index][0])
696
 
                    if entry[1][tree_index][0] == 'absent':
697
 
                        # not in the tree at all.
 
1984
            possible_keys = self._get_id_index().get(fileid_utf8, ())
 
1985
            if not possible_keys:
 
1986
                return None, None
 
1987
            for key in possible_keys:
 
1988
                block_index, present = \
 
1989
                    self._find_block_index_from_key(key)
 
1990
                # strange, probably indicates an out of date
 
1991
                # id index - for now, allow this.
 
1992
                if not present:
 
1993
                    continue
 
1994
                # WARNING: DO not change this code to use _get_block_entry_index
 
1995
                # as that function is not suitable: it does not use the key
 
1996
                # to lookup, and thus the wrong coordinates are returned.
 
1997
                block = self._dirblocks[block_index][1]
 
1998
                entry_index, present = self._find_entry_index(key, block)
 
1999
                if present:
 
2000
                    entry = self._dirblocks[block_index][1][entry_index]
 
2001
                    # TODO: We might want to assert that entry[0][2] ==
 
2002
                    #       fileid_utf8.
 
2003
                    if entry[1][tree_index][0] in 'fdlt':
 
2004
                        # this is the result we are looking for: the
 
2005
                        # real home of this file_id in this tree.
 
2006
                        return entry
 
2007
                    if entry[1][tree_index][0] == 'a':
 
2008
                        # there is no home for this entry in this tree
 
2009
                        if include_deleted:
 
2010
                            return entry
698
2011
                        return None, None
699
 
                    return entry
 
2012
                    if entry[1][tree_index][0] != 'r':
 
2013
                        raise AssertionError(
 
2014
                            "entry %r has invalid minikind %r for tree %r" \
 
2015
                            % (entry,
 
2016
                               entry[1][tree_index][0],
 
2017
                               tree_index))
 
2018
                    real_path = entry[1][tree_index][1]
 
2019
                    return self._get_entry(tree_index, fileid_utf8=fileid_utf8,
 
2020
                        path_utf8=real_path)
700
2021
            return None, None
701
2022
 
702
 
    @staticmethod
703
 
    def initialize(path):
 
2023
    @classmethod
 
2024
    def initialize(cls, path, sha1_provider=None):
704
2025
        """Create a new dirstate on path.
705
2026
 
706
2027
        The new dirstate will be an empty tree - that is it has no parents,
707
2028
        and only a root node - which has id ROOT_ID.
708
2029
 
709
2030
        :param path: The name of the file for the dirstate.
710
 
        :return: A DirState object.
 
2031
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2032
            If None, a DefaultSHA1Provider is used.
 
2033
        :return: A write-locked DirState object.
711
2034
        """
712
2035
        # This constructs a new DirState object on a path, sets the _state_file
713
2036
        # to a new empty file for that path. It then calls _set_data() with our
714
2037
        # stock empty dirstate information - a root with ROOT_ID, no children,
715
2038
        # and no parents. Finally it calls save() to ensure that this data will
716
2039
        # persist.
717
 
        result = DirState()
718
 
        result._state_file = open(path, 'wb+')
 
2040
        if sha1_provider is None:
 
2041
            sha1_provider = DefaultSHA1Provider()
 
2042
        result = cls(path, sha1_provider)
 
2043
        # root dir and root dir contents with no children.
 
2044
        empty_tree_dirblocks = [('', []), ('', [])]
719
2045
        # a new root directory, with a NULLSTAT.
720
 
        root_entries = [(('', '', bzrlib.inventory.ROOT_ID), [
721
 
                ('directory', '', 0, False, DirState.NULLSTAT),
722
 
            ])]
723
 
        root_parents = []
724
 
        empty_tree_dirblocks = [('', [])] # root dir contents - no entries.
725
 
        result._set_data([], root_entries, empty_tree_dirblocks)
 
2046
        empty_tree_dirblocks[0][1].append(
 
2047
            (('', '', inventory.ROOT_ID), [
 
2048
                ('d', '', 0, False, DirState.NULLSTAT),
 
2049
            ]))
 
2050
        result.lock_write()
726
2051
        try:
 
2052
            result._set_data([], empty_tree_dirblocks)
727
2053
            result.save()
728
2054
        except:
729
 
            result._state_file.close()
 
2055
            result.unlock()
730
2056
            raise
731
2057
        return result
732
2058
 
733
 
    def _inv_entry_to_details(self, inv_entry):
 
2059
    @staticmethod
 
2060
    def _inv_entry_to_details(inv_entry):
734
2061
        """Convert an inventory entry (from a revision tree) to state details.
735
2062
 
736
2063
        :param inv_entry: An inventory entry whose sha1 and link targets can be
739
2066
            id.
740
2067
        """
741
2068
        kind = inv_entry.kind
742
 
        tree_data = inv_entry.revision.encode('utf8')
743
 
        assert len(tree_data) > 0, 'empty revision for the inv_entry.'
 
2069
        minikind = DirState._kind_to_minikind[kind]
 
2070
        tree_data = inv_entry.revision
744
2071
        if kind == 'directory':
745
2072
            fingerprint = ''
746
2073
            size = 0
747
2074
            executable = False
748
2075
        elif kind == 'symlink':
749
 
            fingerprint = inv_entry.symlink_target or ''
 
2076
            if inv_entry.symlink_target is None:
 
2077
                fingerprint = ''
 
2078
            else:
 
2079
                fingerprint = inv_entry.symlink_target.encode('utf8')
750
2080
            size = 0
751
2081
            executable = False
752
2082
        elif kind == 'file':
753
2083
            fingerprint = inv_entry.text_sha1 or ''
754
2084
            size = inv_entry.text_size or 0
755
2085
            executable = inv_entry.executable
 
2086
        elif kind == 'tree-reference':
 
2087
            fingerprint = inv_entry.reference_revision or ''
 
2088
            size = 0
 
2089
            executable = False
756
2090
        else:
757
 
            raise Exception
758
 
        return (kind, fingerprint, size, executable, tree_data)
759
 
 
760
 
    def _iter_entries(self, root_entries=None, dirblocks=None):
 
2091
            raise Exception("can't pack %s" % inv_entry)
 
2092
        return (minikind, fingerprint, size, executable, tree_data)
 
2093
 
 
2094
    def _iter_child_entries(self, tree_index, path_utf8):
 
2095
        """Iterate over all the entries that are children of path_utf.
 
2096
 
 
2097
        This only returns entries that are present (not in 'a', 'r') in
 
2098
        tree_index. tree_index data is not refreshed, so if tree 0 is used,
 
2099
        results may differ from that obtained if paths were statted to
 
2100
        determine what ones were directories.
 
2101
 
 
2102
        Asking for the children of a non-directory will return an empty
 
2103
        iterator.
 
2104
        """
 
2105
        pending_dirs = []
 
2106
        next_pending_dirs = [path_utf8]
 
2107
        absent = 'ar'
 
2108
        while next_pending_dirs:
 
2109
            pending_dirs = next_pending_dirs
 
2110
            next_pending_dirs = []
 
2111
            for path in pending_dirs:
 
2112
                block_index, present = self._find_block_index_from_key(
 
2113
                    (path, '', ''))
 
2114
                if block_index == 0:
 
2115
                    block_index = 1
 
2116
                    if len(self._dirblocks) == 1:
 
2117
                        # asked for the children of the root with no other
 
2118
                        # contents.
 
2119
                        return
 
2120
                if not present:
 
2121
                    # children of a non-directory asked for.
 
2122
                    continue
 
2123
                block = self._dirblocks[block_index]
 
2124
                for entry in block[1]:
 
2125
                    kind = entry[1][tree_index][0]
 
2126
                    if kind not in absent:
 
2127
                        yield entry
 
2128
                    if kind == 'd':
 
2129
                        if entry[0][0]:
 
2130
                            path = entry[0][0] + '/' + entry[0][1]
 
2131
                        else:
 
2132
                            path = entry[0][1]
 
2133
                        next_pending_dirs.append(path)
 
2134
 
 
2135
    def _iter_entries(self):
761
2136
        """Iterate over all the entries in the dirstate.
762
2137
 
763
2138
        Each yelt item is an entry in the standard format described in the
764
2139
        docstring of bzrlib.dirstate.
765
 
 
766
 
        :param root_entries: Allows overriding of the root entries to be
767
 
            reported.
768
 
        :param dirblocks: Allows overriding of the source dirblock data.
769
2140
        """
770
2141
        self._read_dirblocks_if_needed()
771
 
        if root_entries is None:
772
 
            root_entries = self._root_entries
773
 
        if dirblocks is None:
774
 
            dirblocks = self._dirblocks
775
 
        for entry in root_entries:
776
 
            yield entry
777
 
        for directory in dirblocks:
 
2142
        for directory in self._dirblocks:
778
2143
            for entry in directory[1]:
779
2144
                yield entry
780
2145
 
 
2146
    def _get_id_index(self):
 
2147
        """Get an id index of self._dirblocks.
 
2148
        
 
2149
        This maps from file_id => [(directory, name, file_id)] entries where
 
2150
        that file_id appears in one of the trees.
 
2151
        """
 
2152
        if self._id_index is None:
 
2153
            id_index = {}
 
2154
            for key, tree_details in self._iter_entries():
 
2155
                self._add_to_id_index(id_index, key)
 
2156
            self._id_index = id_index
 
2157
        return self._id_index
 
2158
 
 
2159
    def _add_to_id_index(self, id_index, entry_key):
 
2160
        """Add this entry to the _id_index mapping."""
 
2161
        # This code used to use a set for every entry in the id_index. However,
 
2162
        # it is *rare* to have more than one entry. So a set is a large
 
2163
        # overkill. And even when we do, we won't ever have more than the
 
2164
        # number of parent trees. Which is still a small number (rarely >2). As
 
2165
        # such, we use a simple tuple, and do our own uniqueness checks. While
 
2166
        # the 'in' check is O(N) since N is nicely bounded it shouldn't ever
 
2167
        # cause quadratic failure.
 
2168
        # TODO: This should use StaticTuple
 
2169
        file_id = entry_key[2]
 
2170
        entry_key = static_tuple.StaticTuple.from_sequence(entry_key)
 
2171
        if file_id not in id_index:
 
2172
            id_index[file_id] = static_tuple.StaticTuple(entry_key,)
 
2173
        else:
 
2174
            entry_keys = id_index[file_id]
 
2175
            if entry_key not in entry_keys:
 
2176
                id_index[file_id] = entry_keys + (entry_key,)
 
2177
 
 
2178
    def _remove_from_id_index(self, id_index, entry_key):
 
2179
        """Remove this entry from the _id_index mapping.
 
2180
 
 
2181
        It is an programming error to call this when the entry_key is not
 
2182
        already present.
 
2183
        """
 
2184
        file_id = entry_key[2]
 
2185
        entry_keys = list(id_index[file_id])
 
2186
        entry_keys.remove(entry_key)
 
2187
        id_index[file_id] = static_tuple.StaticTuple.from_sequence(entry_keys)
 
2188
 
781
2189
    def _get_output_lines(self, lines):
782
 
        """format lines for final output.
 
2190
        """Format lines for final output.
783
2191
 
784
 
        :param lines: A sequece of lines containing the parents list and the
 
2192
        :param lines: A sequence of lines containing the parents list and the
785
2193
            path lines.
786
2194
        """
787
 
        output_lines = ['#bazaar dirstate flat format 2\n']
 
2195
        output_lines = [DirState.HEADER_FORMAT_3]
788
2196
        lines.append('') # a final newline
789
2197
        inventory_text = '\0\n\0'.join(lines)
790
 
        output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
 
2198
        output_lines.append('crc32: %s\n' % (zlib.crc32(inventory_text),))
791
2199
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
792
2200
        num_entries = len(lines)-3
793
2201
        output_lines.append('num_entries: %s\n' % (num_entries,))
795
2203
        return output_lines
796
2204
 
797
2205
    def _make_deleted_row(self, fileid_utf8, parents):
798
 
        """Return a deleted for for fileid_utf8."""
 
2206
        """Return a deleted row for fileid_utf8."""
799
2207
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
800
2208
            ''), parents
801
2209
 
 
2210
    def _num_present_parents(self):
 
2211
        """The number of parent entries in each record row."""
 
2212
        return len(self._parents) - len(self._ghosts)
 
2213
 
802
2214
    @staticmethod
803
 
    def on_file(path):
804
 
        """Construct a DirState on the file at path path."""
805
 
        result = DirState()
806
 
        result._state_file = open(path, 'rb+')
 
2215
    def on_file(path, sha1_provider=None):
 
2216
        """Construct a DirState on the file at path "path".
 
2217
 
 
2218
        :param path: The path at which the dirstate file on disk should live.
 
2219
        :param sha1_provider: an object meeting the SHA1Provider interface.
 
2220
            If None, a DefaultSHA1Provider is used.
 
2221
        :return: An unlocked DirState object, associated with the given path.
 
2222
        """
 
2223
        if sha1_provider is None:
 
2224
            sha1_provider = DefaultSHA1Provider()
 
2225
        result = DirState(path, sha1_provider)
807
2226
        return result
808
2227
 
809
2228
    def _read_dirblocks_if_needed(self):
810
2229
        """Read in all the dirblocks from the file if they are not in memory.
811
 
        
812
 
        This populates self._root_entries and self._dirblocks, and sets 
813
 
        self._dirblock_state to IN_MEMORY_UNMODIFIED. It is not currently ready
814
 
        for incremental block loading.
 
2230
 
 
2231
        This populates self._dirblocks, and sets self._dirblock_state to
 
2232
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
 
2233
        loading.
815
2234
        """
816
2235
        self._read_header_if_needed()
817
2236
        if self._dirblock_state == DirState.NOT_IN_MEMORY:
818
 
            # the _state_file pointer will be positioned at the start of the 
819
 
            # dirblocks.
820
 
            text = self._state_file.read()
821
 
            # TODO: check the adler checksums. adler_measured = zlib.adler32(text)
822
 
 
823
 
            fields = text.split('\0')
824
 
            # Remove the last blank entry
825
 
            trailing = fields.pop()
826
 
            assert trailing == ''
827
 
            # consider turning fields into a tuple.
828
 
 
829
 
            # skip the first field which is the trailing null from the header.
830
 
            cur = 1
831
 
            # Each line now has an extra '\n' field which is not used
832
 
            # so we just skip over it
833
 
            # entry size:
834
 
            #  3 fields for the key
835
 
            #  + number of fields per tree_data (5) * tree count
836
 
            #  + newline
837
 
            num_present_parents = len(self._parents) - len(self._ghosts)
838
 
            tree_count = 1 + num_present_parents
839
 
            entry_size = 3 + 5 * tree_count + 1
840
 
            expected_field_count = entry_size * self._num_entries
841
 
            if len(fields) - cur > expected_field_count:
842
 
                fields = fields[:expected_field_count + cur]
843
 
                trace.mutter('Unexpectedly long dirstate field count!')
844
 
                print "XXX: incorrectly truncated dirstate file bug triggered."
845
 
            field_count = len(fields)
846
 
            # this checks our adjustment, and also catches file too short.
847
 
            assert field_count - cur == expected_field_count, \
848
 
                'field count incorrect %s != %s, entry_size=%s, '\
849
 
                'num_entries=%s fields=%r' % (
850
 
                    field_count - cur, expected_field_count, entry_size,
851
 
                    self._num_entries, fields)
852
 
 
853
 
            # Fast path the case where there are 1 or 2 parents
854
 
            if num_present_parents == 0:
855
 
                # key, [current tree]
856
 
                entries = [(tuple(fields[pos:pos + 3]), [fields[pos + 3:pos + 8]])
857
 
                    for pos in xrange(cur, field_count, entry_size)]
858
 
            elif num_present_parents == 1:
859
 
                # key,
860
 
                entries = [(tuple(fields[pos:pos + 3]),
861
 
                #   [current tree,             parent 1]
862
 
                    [fields[pos + 3:pos + 8], fields[pos + 8:pos + 13], ])
863
 
                    for pos in xrange(cur, field_count, entry_size)]
864
 
            elif num_present_parents == 2:
865
 
                # key,
866
 
                entries = [(tuple(fields[pos:pos + 3]),
867
 
                #   [current tree,             parent 1, 
868
 
                    [fields[pos + 3:pos + 8], fields[pos + 8:pos + 13],
869
 
                #   parent 2]
870
 
                    fields[pos + 13:pos + 18], ])
871
 
                    for pos in xrange(cur, field_count, entry_size)]
872
 
            else:
873
 
                entries = [(
874
 
                    tuple(fields[pos:pos+3]), #key
875
 
                    tuple([fields[chunk:chunk+5] for 
876
 
                        chunk in xrange(pos + 3, pos+entry_size-1, 5)]))
877
 
                            for pos in xrange(cur, field_count, entry_size)
878
 
                ]
879
 
 
880
 
            assert len(entries) == self._num_entries, '%s != %s entries' % (len(entries),
881
 
                self._num_entries)
882
 
 
883
 
            def _line_to_entry(line):
884
 
                """Convert freshly read tree details to the final form.
885
 
                
886
 
                This converts size and minikind for use and makes it into a 
887
 
                tuple.
888
 
                """
889
 
                for tree in line[1]:
890
 
                    # convert the minikind to kind
891
 
                    tree[0] = self._minikind_to_kind[tree[0]]
892
 
                    # convert the size to an int
893
 
                    tree[2] = int(tree[2])
894
 
                    tree[3] = tree[3] == 'y'
895
 
                return line[0], map(tuple, line[1])
896
 
            new_entries = map(_line_to_entry, entries)
897
 
            self._entries_to_current_state(new_entries)
898
 
            self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
2237
            _read_dirblocks(self)
899
2238
 
900
2239
    def _read_header(self):
901
2240
        """This reads in the metadata header, and the parent ids.
903
2242
        After reading in, the file should be positioned at the null
904
2243
        just before the start of the first record in the file.
905
2244
 
906
 
        :return: (expected adler checksum, number of entries, parent list)
 
2245
        :return: (expected crc checksum, number of entries, parent list)
907
2246
        """
908
2247
        self._read_prelude()
909
2248
        parent_line = self._state_file.readline()
910
2249
        info = parent_line.split('\0')
911
2250
        num_parents = int(info[0])
912
 
        assert num_parents == len(info)-2, 'incorrect parent info line'
913
2251
        self._parents = info[1:-1]
914
 
 
915
2252
        ghost_line = self._state_file.readline()
916
2253
        info = ghost_line.split('\0')
917
2254
        num_ghosts = int(info[1])
918
 
        assert num_ghosts == len(info)-3, 'incorrect ghost info line'
919
2255
        self._ghosts = info[2:-1]
920
2256
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2257
        self._end_of_header = self._state_file.tell()
921
2258
 
922
2259
    def _read_header_if_needed(self):
923
2260
        """Read the header of the dirstate file if needed."""
 
2261
        # inline this as it will be called a lot
 
2262
        if not self._lock_token:
 
2263
            raise errors.ObjectNotLocked(self)
924
2264
        if self._header_state == DirState.NOT_IN_MEMORY:
925
2265
            self._read_header()
926
2266
 
927
2267
    def _read_prelude(self):
928
 
        """Read in the prelude header of the dirstate file
 
2268
        """Read in the prelude header of the dirstate file.
929
2269
 
930
 
        This only reads in the stuff that is not connected to the adler
 
2270
        This only reads in the stuff that is not connected to the crc
931
2271
        checksum. The position will be correct to read in the rest of
932
2272
        the file and check the checksum after this point.
933
2273
        The next entry in the file should be the number of parents,
934
2274
        and their ids. Followed by a newline.
935
2275
        """
936
2276
        header = self._state_file.readline()
937
 
        assert header == '#bazaar dirstate flat format 2\n', \
938
 
            'invalid header line: %r' % (header,)
939
 
        adler_line = self._state_file.readline()
940
 
        assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
941
 
        self.adler_expected = int(adler_line[len('adler32: '):-1])
 
2277
        if header != DirState.HEADER_FORMAT_3:
 
2278
            raise errors.BzrError(
 
2279
                'invalid header line: %r' % (header,))
 
2280
        crc_line = self._state_file.readline()
 
2281
        if not crc_line.startswith('crc32: '):
 
2282
            raise errors.BzrError('missing crc32 checksum: %r' % crc_line)
 
2283
        self.crc_expected = int(crc_line[len('crc32: '):-1])
942
2284
        num_entries_line = self._state_file.readline()
943
 
        assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
 
2285
        if not num_entries_line.startswith('num_entries: '):
 
2286
            raise errors.BzrError('missing num_entries line')
944
2287
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
945
 
    
 
2288
 
 
2289
    def sha1_from_stat(self, path, stat_result, _pack_stat=pack_stat):
 
2290
        """Find a sha1 given a stat lookup."""
 
2291
        return self._get_packed_stat_index().get(_pack_stat(stat_result), None)
 
2292
 
 
2293
    def _get_packed_stat_index(self):
 
2294
        """Get a packed_stat index of self._dirblocks."""
 
2295
        if self._packed_stat_index is None:
 
2296
            index = {}
 
2297
            for key, tree_details in self._iter_entries():
 
2298
                if tree_details[0][0] == 'f':
 
2299
                    index[tree_details[0][4]] = tree_details[0][1]
 
2300
            self._packed_stat_index = index
 
2301
        return self._packed_stat_index
 
2302
 
946
2303
    def save(self):
947
2304
        """Save any pending changes created during this session.
948
 
        
 
2305
 
949
2306
        We reuse the existing file, because that prevents race conditions with
950
 
        file creation, and we expect to be using oslocks on it in the near 
951
 
        future to prevent concurrent modification and reads - because dirstates
952
 
        incremental data aggretation is not compatible with reading a modified
953
 
        file, and replacing a file in use by another process is impossible on 
954
 
        windows.
 
2307
        file creation, and use oslocks on it to prevent concurrent modification
 
2308
        and reads - because dirstate's incremental data aggregation is not
 
2309
        compatible with reading a modified file, and replacing a file in use by
 
2310
        another process is impossible on Windows.
955
2311
 
956
2312
        A dirstate in read only mode should be smart enough though to validate
957
2313
        that the file has not changed, and otherwise discard its cache and
958
2314
        start over, to allow for fine grained read lock duration, so 'status'
959
2315
        wont block 'commit' - for example.
960
2316
        """
 
2317
        if self._changes_aborted:
 
2318
            # Should this be a warning? For now, I'm expecting that places that
 
2319
            # mark it inconsistent will warn, making a warning here redundant.
 
2320
            trace.mutter('Not saving DirState because '
 
2321
                    '_changes_aborted is set.')
 
2322
            return
961
2323
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
962
2324
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
963
 
            self._state_file.seek(0)
964
 
            self._state_file.writelines(self.get_lines())
965
 
            self._state_file.truncate()
966
 
            self._state_file.flush()
967
 
            self._header_state = DirState.IN_MEMORY_UNMODIFIED
968
 
            self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
969
 
 
970
 
    def _set_data(self, parent_ids, root_entries, dirblocks):
 
2325
 
 
2326
            grabbed_write_lock = False
 
2327
            if self._lock_state != 'w':
 
2328
                grabbed_write_lock, new_lock = self._lock_token.temporary_write_lock()
 
2329
                # Switch over to the new lock, as the old one may be closed.
 
2330
                # TODO: jam 20070315 We should validate the disk file has
 
2331
                #       not changed contents. Since temporary_write_lock may
 
2332
                #       not be an atomic operation.
 
2333
                self._lock_token = new_lock
 
2334
                self._state_file = new_lock.f
 
2335
                if not grabbed_write_lock:
 
2336
                    # We couldn't grab a write lock, so we switch back to a read one
 
2337
                    return
 
2338
            try:
 
2339
                self._state_file.seek(0)
 
2340
                self._state_file.writelines(self.get_lines())
 
2341
                self._state_file.truncate()
 
2342
                self._state_file.flush()
 
2343
                self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
2344
                self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
2345
            finally:
 
2346
                if grabbed_write_lock:
 
2347
                    self._lock_token = self._lock_token.restore_read_lock()
 
2348
                    self._state_file = self._lock_token.f
 
2349
                    # TODO: jam 20070315 We should validate the disk file has
 
2350
                    #       not changed contents. Since restore_read_lock may
 
2351
                    #       not be an atomic operation.
 
2352
 
 
2353
    def _set_data(self, parent_ids, dirblocks):
971
2354
        """Set the full dirstate data in memory.
972
2355
 
973
2356
        This is an internal function used to completely replace the objects
974
2357
        in memory state. It puts the dirstate into state 'full-dirty'.
975
2358
 
976
2359
        :param parent_ids: A list of parent tree revision ids.
977
 
        :param root_entrie: The root entries: A list of entries, one per fileid found
978
 
            at the root.
979
2360
        :param dirblocks: A list containing one tuple for each directory in the
980
 
            tree. Each tuple contains the directory path and a list of entries 
 
2361
            tree. Each tuple contains the directory path and a list of entries
981
2362
            found in that directory.
982
2363
        """
983
2364
        # our memory copy is now authoritative.
984
2365
        self._dirblocks = dirblocks
985
 
        self._root_entries = root_entries
986
2366
        self._header_state = DirState.IN_MEMORY_MODIFIED
987
2367
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
988
2368
        self._parents = list(parent_ids)
 
2369
        self._id_index = None
 
2370
        self._packed_stat_index = None
989
2371
 
990
2372
    def set_path_id(self, path, new_id):
991
2373
        """Change the id of path to new_id in the current working tree.
992
2374
 
993
2375
        :param path: The path inside the tree to set - '' is the root, 'foo'
994
2376
            is the path foo in the root.
995
 
        :param new_id: The new id to assign to the path. If unicode, it will
996
 
            be encoded to utf8. In future this will be deprecated: avoid using
997
 
            unicode ids if possible.
 
2377
        :param new_id: The new id to assign to the path. This must be a utf8
 
2378
            file id (not unicode, and not None).
998
2379
        """
999
 
        # TODO: start warning here.
1000
 
        if new_id.__class__ == unicode:
1001
 
            new_id = new_id.encode('utf8')
1002
2380
        self._read_dirblocks_if_needed()
1003
2381
        if len(path):
1004
 
            import pdb;pdb.set_trace()
1005
 
            # logic not written
 
2382
            # TODO: logic not written
1006
2383
            raise NotImplementedError(self.set_path_id)
1007
2384
        # TODO: check new id is unique
1008
 
        entry = self._get_entry(0, path_utf8='')
1009
 
        # TODO: version of _get_block_entry_index that works with the root so
1010
 
        # we dont look up this twice.
1011
 
        index = self._root_entries.index(entry)
1012
 
        if new_id == entry[0][2]:
1013
 
            # no change
 
2385
        entry = self._get_entry(0, path_utf8=path)
 
2386
        if entry[0][2] == new_id:
 
2387
            # Nothing to change.
1014
2388
            return
1015
 
        if len(entry[1]) > 1:
1016
 
            # TODO: split the record.
1017
 
            raise NotImplementedError(self.set_path_id)
1018
 
            root_info, root_parents = self._root_entrie
1019
 
            if len(root_parents):
1020
 
                self.add_deleted(root_info[3], root_parents)
1021
 
        # replace the entry:
1022
 
        self._root_entries[index] = (('', '', new_id), entry[1])
 
2389
        # mark the old path absent, and insert a new root path
 
2390
        self._make_absent(entry)
 
2391
        self.update_minimal(('', '', new_id), 'd',
 
2392
            path_utf8='', packed_stat=entry[1][0][4])
1023
2393
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1024
2394
 
1025
2395
    def set_parent_trees(self, trees, ghosts):
1026
2396
        """Set the parent trees for the dirstate.
1027
2397
 
1028
2398
        :param trees: A list of revision_id, tree tuples. tree must be provided
1029
 
            even if the revision_id refers to a ghost: supply an empty tree in 
 
2399
            even if the revision_id refers to a ghost: supply an empty tree in
1030
2400
            this case.
1031
2401
        :param ghosts: A list of the revision_ids that are ghosts at the time
1032
2402
            of setting.
1033
 
        """ 
1034
 
        # TODO: generate a list of parent indexes to preserve to save 
 
2403
        """
 
2404
        # TODO: generate a list of parent indexes to preserve to save
1035
2405
        # processing specific parent trees. In the common case one tree will
1036
2406
        # be preserved - the left most parent.
1037
2407
        # TODO: if the parent tree is a dirstate, we might want to walk them
1038
2408
        # all by path in parallel for 'optimal' common-case performance.
1039
2409
        # generate new root row.
1040
2410
        self._read_dirblocks_if_needed()
1041
 
        old_roots = self._root_entries
1042
 
        root_info = self._root_entries[0]
1043
 
        new_parent_count = len(trees)
1044
2411
        # TODO future sketch: Examine the existing parents to generate a change
1045
2412
        # map and then walk the new parent trees only, mapping them into the
1046
2413
        # dirstate. Walk the dirstate at the same time to remove unreferenced
1047
2414
        # entries.
1048
 
        # for now: 
1049
 
        # sketch: loop over all entries in the dirstate, cherry picking 
 
2415
        # for now:
 
2416
        # sketch: loop over all entries in the dirstate, cherry picking
1050
2417
        # entries from the parent trees, if they are not ghost trees.
1051
2418
        # after we finish walking the dirstate, all entries not in the dirstate
1052
2419
        # are deletes, so we want to append them to the end as per the design
1057
2424
        #   links. We dont't trivially use the inventory from other trees
1058
2425
        #   because this leads to either double touching, or to accessing
1059
2426
        #   missing keys,
1060
 
        # - find other keys containing a path 
1061
 
        # We accumulate each entry via this dictionary, including the root 
 
2427
        # - find other keys containing a path
 
2428
        # We accumulate each entry via this dictionary, including the root
1062
2429
        by_path = {}
1063
2430
        id_index = {}
1064
2431
        # we could do parallel iterators, but because file id data may be
1068
2435
        # parent, but for now the common cases are adding a new parent (merge),
1069
2436
        # and replacing completely (commit), and commit is more common: so
1070
2437
        # optimise merge later.
1071
 
        
 
2438
 
1072
2439
        # ---- start generation of full tree mapping data
1073
2440
        # what trees should we use?
1074
2441
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
1075
 
        # how many trees do we end up with 
 
2442
        # how many trees do we end up with
1076
2443
        parent_count = len(parent_trees)
1077
2444
 
1078
2445
        # one: the current tree
1079
2446
        for entry in self._iter_entries():
1080
2447
            # skip entries not in the current tree
1081
 
            if entry[1][0][0] in ('absent', 'relocated'):
 
2448
            if entry[1][0][0] in 'ar': # absent, relocated
1082
2449
                continue
1083
2450
            by_path[entry[0]] = [entry[1][0]] + \
1084
2451
                [DirState.NULL_PARENT_DETAILS] * parent_count
1085
 
            id_index[entry[0][2]] = set([entry[0]])
1086
 
        
 
2452
            # TODO: Possibly inline this, since we know it isn't present yet
 
2453
            #       id_index[entry[0][2]] = (entry[0],)
 
2454
            self._add_to_id_index(id_index, entry[0])
 
2455
 
1087
2456
        # now the parent trees:
1088
2457
        for tree_index, tree in enumerate(parent_trees):
1089
2458
            # the index is off by one, adjust it.
1103
2472
                # avoid checking all known paths for the id when generating a
1104
2473
                # new entry at this path: by adding the id->path mapping last,
1105
2474
                # all the mappings are valid and have correct relocation
1106
 
                # records where needed. 
1107
 
                file_id = entry.file_id.encode('utf8')
 
2475
                # records where needed.
 
2476
                file_id = entry.file_id
1108
2477
                path_utf8 = path.encode('utf8')
1109
 
                dirname, basename = os.path.split(path_utf8)
 
2478
                dirname, basename = osutils.split(path_utf8)
1110
2479
                new_entry_key = (dirname, basename, file_id)
1111
2480
                # tree index consistency: All other paths for this id in this tree
1112
2481
                # index must point to the correct path.
1113
 
                for entry_key in id_index.setdefault(file_id, set()):
 
2482
                for entry_key in id_index.get(file_id, ()):
1114
2483
                    # TODO:PROFILING: It might be faster to just update
1115
2484
                    # rather than checking if we need to, and then overwrite
1116
2485
                    # the one we are located at.
1118
2487
                        # this file id is at a different path in one of the
1119
2488
                        # other trees, so put absent pointers there
1120
2489
                        # This is the vertical axis in the matrix, all pointing
1121
 
                        # tot he real path.
1122
 
                        by_path[entry_key][tree_index] = ('relocated', path_utf8, 0, False, '')
1123
 
                # by path consistency: Insert into an existing path record (trivial), or 
 
2490
                        # to the real path.
 
2491
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
2492
                # by path consistency: Insert into an existing path record (trivial), or
1124
2493
                # add a new one with relocation pointers for the other tree indexes.
1125
 
                if new_entry_key in id_index[file_id]:
 
2494
                entry_keys = id_index.get(file_id, ())
 
2495
                if new_entry_key in entry_keys:
1126
2496
                    # there is already an entry where this data belongs, just insert it.
1127
2497
                    by_path[new_entry_key][tree_index] = \
1128
2498
                        self._inv_entry_to_details(entry)
1133
2503
                    new_details = []
1134
2504
                    for lookup_index in xrange(tree_index):
1135
2505
                        # boundary case: this is the first occurence of file_id
1136
 
                        # so there are no id_indexs, possibly take this out of
 
2506
                        # so there are no id_indexes, possibly take this out of
1137
2507
                        # the loop?
1138
 
                        if not len(id_index[file_id]):
 
2508
                        if not len(entry_keys):
1139
2509
                            new_details.append(DirState.NULL_PARENT_DETAILS)
1140
2510
                        else:
1141
2511
                            # grab any one entry, use it to find the right path.
1142
 
                            # TODO: optimise this to reduce memory use in highly 
 
2512
                            # TODO: optimise this to reduce memory use in highly
1143
2513
                            # fragmented situations by reusing the relocation
1144
2514
                            # records.
1145
 
                            a_key = iter(id_index[file_id]).next()
1146
 
                            if by_path[a_key][lookup_index][0] in ('relocated', 'absent'):
 
2515
                            a_key = iter(entry_keys).next()
 
2516
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
1147
2517
                                # its a pointer or missing statement, use it as is.
1148
2518
                                new_details.append(by_path[a_key][lookup_index])
1149
2519
                            else:
1150
2520
                                # we have the right key, make a pointer to it.
1151
2521
                                real_path = ('/'.join(a_key[0:2])).strip('/')
1152
 
                                new_details.append(('relocated', real_path, 0, False, ''))
 
2522
                                new_details.append(('r', real_path, 0, False, ''))
1153
2523
                    new_details.append(self._inv_entry_to_details(entry))
1154
2524
                    new_details.extend(new_location_suffix)
1155
2525
                    by_path[new_entry_key] = new_details
1156
 
                    id_index[file_id].add(new_entry_key)
 
2526
                    self._add_to_id_index(id_index, new_entry_key)
1157
2527
        # --- end generation of full tree mappings
1158
2528
 
1159
2529
        # sort and output all the entries
1160
 
        new_entries = sorted(by_path.items())
 
2530
        new_entries = self._sort_entries(by_path.items())
1161
2531
        self._entries_to_current_state(new_entries)
1162
2532
        self._parents = [rev_id for rev_id, tree in trees]
1163
2533
        self._ghosts = list(ghosts)
1164
2534
        self._header_state = DirState.IN_MEMORY_MODIFIED
1165
2535
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2536
        self._id_index = id_index
 
2537
 
 
2538
    def _sort_entries(self, entry_list):
 
2539
        """Given a list of entries, sort them into the right order.
 
2540
 
 
2541
        This is done when constructing a new dirstate from trees - normally we
 
2542
        try to keep everything in sorted blocks all the time, but sometimes
 
2543
        it's easier to sort after the fact.
 
2544
        """
 
2545
        def _key(entry):
 
2546
            # sort by: directory parts, file name, file id
 
2547
            return entry[0][0].split('/'), entry[0][1], entry[0][2]
 
2548
        return sorted(entry_list, key=_key)
1166
2549
 
1167
2550
    def set_state_from_inventory(self, new_inv):
1168
 
        """Set new_inv as the current state. 
 
2551
        """Set new_inv as the current state.
1169
2552
 
1170
2553
        This API is called by tree transform, and will usually occur with
1171
2554
        existing parent trees.
1172
2555
 
1173
2556
        :param new_inv: The inventory object to set current state from.
1174
2557
        """
 
2558
        if 'evil' in debug.debug_flags:
 
2559
            trace.mutter_callsite(1,
 
2560
                "set_state_from_inventory called; please mutate the tree instead")
 
2561
        tracing = 'dirstate' in debug.debug_flags
 
2562
        if tracing:
 
2563
            trace.mutter("set_state_from_inventory trace:")
1175
2564
        self._read_dirblocks_if_needed()
1176
2565
        # sketch:
1177
 
        #  generate a byid index of the dirstate
1178
 
        id_index = {}
1179
 
        for key, tree_details in self._iter_entries():
1180
 
            id_index.setdefault(key[2], set()).add(key)
1181
 
 
1182
 
        num_present_parents = len(self._parents) - len(self._ghosts)
1183
 
        # incremental algorithm:
1184
 
        # two iterators: current data and new data, both in dirblock order. 
 
2566
        # Two iterators: current data and new data, both in dirblock order.
 
2567
        # We zip them together, which tells about entries that are new in the
 
2568
        # inventory, or removed in the inventory, or present in both and
 
2569
        # possibly changed.
 
2570
        #
 
2571
        # You might think we could just synthesize a new dirstate directly
 
2572
        # since we're processing it in the right order.  However, we need to
 
2573
        # also consider there may be any number of parent trees and relocation
 
2574
        # pointers, and we don't want to duplicate that here.
1185
2575
        new_iterator = new_inv.iter_entries_by_dir()
1186
2576
        # we will be modifying the dirstate, so we need a stable iterator. In
1187
2577
        # future we might write one, for now we just clone the state into a
1188
 
        # list - which is a shallow copy, so each 
 
2578
        # list using a copy so that we see every original item and don't have
 
2579
        # to adjust the position when items are inserted or deleted in the
 
2580
        # underlying dirstate.
1189
2581
        old_iterator = iter(list(self._iter_entries()))
1190
2582
        # both must have roots so this is safe:
1191
2583
        current_new = new_iterator.next()
1197
2589
                return None
1198
2590
        while current_new or current_old:
1199
2591
            # skip entries in old that are not really there
1200
 
            if current_old and current_old[1][0][0] in ('relocated', 'absent'):
 
2592
            if current_old and current_old[1][0][0] in 'ar':
 
2593
                # relocated or absent
1201
2594
                current_old = advance(old_iterator)
1202
2595
                continue
1203
2596
            if current_new:
1204
2597
                # convert new into dirblock style
1205
2598
                new_path_utf8 = current_new[0].encode('utf8')
1206
 
                new_dirname, new_basename = os.path.split(new_path_utf8)
1207
 
                new_id = current_new[1].file_id.encode('utf8')
 
2599
                new_dirname, new_basename = osutils.split(new_path_utf8)
 
2600
                new_id = current_new[1].file_id
1208
2601
                new_entry_key = (new_dirname, new_basename, new_id)
 
2602
                current_new_minikind = \
 
2603
                    DirState._kind_to_minikind[current_new[1].kind]
 
2604
                if current_new_minikind == 't':
 
2605
                    fingerprint = current_new[1].reference_revision or ''
 
2606
                else:
 
2607
                    # We normally only insert or remove records, or update
 
2608
                    # them when it has significantly changed.  Then we want to
 
2609
                    # erase its fingerprint.  Unaffected records should
 
2610
                    # normally not be updated at all.
 
2611
                    fingerprint = ''
1209
2612
            else:
1210
2613
                # for safety disable variables
1211
 
                new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
 
2614
                new_path_utf8 = new_dirname = new_basename = new_id = \
 
2615
                    new_entry_key = None
1212
2616
            # 5 cases, we dont have a value that is strictly greater than everything, so
1213
2617
            # we make both end conditions explicit
1214
2618
            if not current_old:
1215
2619
                # old is finished: insert current_new into the state.
1216
 
                self.update_minimal(new_entry_key, current_new[1].kind,
1217
 
                    num_present_parents, executable=current_new[1].executable,
1218
 
                    id_index=id_index, path_utf8=new_path_utf8)
 
2620
                if tracing:
 
2621
                    trace.mutter("Appending from new '%s'.",
 
2622
                        new_path_utf8.decode('utf8'))
 
2623
                self.update_minimal(new_entry_key, current_new_minikind,
 
2624
                    executable=current_new[1].executable,
 
2625
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2626
                    fullscan=True)
1219
2627
                current_new = advance(new_iterator)
1220
2628
            elif not current_new:
1221
2629
                # new is finished
1222
 
                self._make_absent(num_present_parents, current_old, id_index)
 
2630
                if tracing:
 
2631
                    trace.mutter("Truncating from old '%s/%s'.",
 
2632
                        current_old[0][0].decode('utf8'),
 
2633
                        current_old[0][1].decode('utf8'))
 
2634
                self._make_absent(current_old)
1223
2635
                current_old = advance(old_iterator)
1224
2636
            elif new_entry_key == current_old[0]:
1225
2637
                # same -  common case
 
2638
                # We're looking at the same path and id in both the dirstate
 
2639
                # and inventory, so just need to update the fields in the
 
2640
                # dirstate from the one in the inventory.
1226
2641
                # TODO: update the record if anything significant has changed.
1227
2642
                # the minimal required trigger is if the execute bit or cached
1228
2643
                # kind has changed.
1229
2644
                if (current_old[1][0][3] != current_new[1].executable or
1230
 
                    current_old[1][0][0] != current_new[1].kind):
1231
 
                    self.update_minimal(current_old[0], current_new[1].kind,
1232
 
                        num_present_parents,
 
2645
                    current_old[1][0][0] != current_new_minikind):
 
2646
                    if tracing:
 
2647
                        trace.mutter("Updating in-place change '%s'.",
 
2648
                            new_path_utf8.decode('utf8'))
 
2649
                    self.update_minimal(current_old[0], current_new_minikind,
1233
2650
                        executable=current_new[1].executable,
1234
 
                        id_index=id_index, path_utf8=new_path_utf8)
 
2651
                        path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2652
                        fullscan=True)
1235
2653
                # both sides are dealt with, move on
1236
2654
                current_old = advance(old_iterator)
1237
2655
                current_new = advance(new_iterator)
1238
 
            elif new_entry_key < current_old[0]:
 
2656
            elif (cmp_by_dirs(new_dirname, current_old[0][0]) < 0
 
2657
                  or (new_dirname == current_old[0][0]
 
2658
                      and new_entry_key[1:] < current_old[0][1:])):
1239
2659
                # new comes before:
1240
2660
                # add a entry for this and advance new
1241
 
                self.update_minimal(new_entry_key, current_new[1].kind,
1242
 
                    num_present_parents, executable=current_new[1].executable,
1243
 
                    id_index=id_index, path_utf8=new_path_utf8)
 
2661
                if tracing:
 
2662
                    trace.mutter("Inserting from new '%s'.",
 
2663
                        new_path_utf8.decode('utf8'))
 
2664
                self.update_minimal(new_entry_key, current_new_minikind,
 
2665
                    executable=current_new[1].executable,
 
2666
                    path_utf8=new_path_utf8, fingerprint=fingerprint,
 
2667
                    fullscan=True)
1244
2668
                current_new = advance(new_iterator)
1245
2669
            else:
1246
 
                # old comes before:
1247
 
                self._make_absent(num_present_parents, current_old, id_index)
 
2670
                # we've advanced past the place where the old key would be,
 
2671
                # without seeing it in the new list.  so it must be gone.
 
2672
                if tracing:
 
2673
                    trace.mutter("Deleting from old '%s/%s'.",
 
2674
                        current_old[0][0].decode('utf8'),
 
2675
                        current_old[0][1].decode('utf8'))
 
2676
                self._make_absent(current_old)
1248
2677
                current_old = advance(old_iterator)
1249
2678
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1250
 
 
1251
 
    def _make_absent(self, num_present_parents, current_old, id_index):
1252
 
        # remove old from the state, advance old
1253
 
        # to remove old, we have two conditions:
1254
 
        # either its the last reference to this path that we are
1255
 
        # removing, or its not. If its the last reference, we remove
1256
 
        # the entire row and remove the path from the id mapping. If
1257
 
        # its not the last reference, we just set it to absent.
1258
 
        last_reference = True
1259
 
        for lookup_index in xrange(1, num_present_parents + 1):
1260
 
            if current_old[1][lookup_index] not in ('absent', 'relocated'):
1261
 
                last_reference = False
1262
 
                break
1263
 
        if not last_reference:
1264
 
            # common case, theres a parent at this path
1265
 
            current_old[1][0] = DirState.NULL_PARENT_DETAILS
1266
 
        else:
1267
 
            # there are no more references at this path
1268
 
            id_index[current_old[0][2]].remove(current_old[0])
1269
 
            # are there others (which will need to be changed
1270
 
            # from relocated to absent for index 0)?
1271
 
            for update_key in id_index[current_old[0][2]]:
1272
 
                # update the entry for 0 to say absent: there is a parent at
1273
 
                # that path, but nothing in this tree for that file id anymore.
1274
 
                update_block_index, present = \
1275
 
                    self._find_block_index_from_key(update_key)
1276
 
                assert present
1277
 
                update_entry_index, present = \
1278
 
                    self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
1279
 
                assert present
1280
 
                update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
1281
 
                # it must currently be relocated
1282
 
                assert update_tree_details[0][0] == 'relocated'
1283
 
                update_tree_details[0] = DirState.NULL_PARENT_DETAILS
 
2679
        self._id_index = None
 
2680
        self._packed_stat_index = None
 
2681
        if tracing:
 
2682
            trace.mutter("set_state_from_inventory complete.")
 
2683
 
 
2684
    def _make_absent(self, current_old):
 
2685
        """Mark current_old - an entry - as absent for tree 0.
 
2686
 
 
2687
        :return: True if this was the last details entry for the entry key:
 
2688
            that is, if the underlying block has had the entry removed, thus
 
2689
            shrinking in length.
 
2690
        """
 
2691
        # build up paths that this id will be left at after the change is made,
 
2692
        # so we can update their cross references in tree 0
 
2693
        all_remaining_keys = set()
 
2694
        # Dont check the working tree, because it's going.
 
2695
        for details in current_old[1][1:]:
 
2696
            if details[0] not in 'ar': # absent, relocated
 
2697
                all_remaining_keys.add(current_old[0])
 
2698
            elif details[0] == 'r': # relocated
 
2699
                # record the key for the real path.
 
2700
                all_remaining_keys.add(tuple(osutils.split(details[1])) + (current_old[0][2],))
 
2701
            # absent rows are not present at any path.
 
2702
        last_reference = current_old[0] not in all_remaining_keys
 
2703
        if last_reference:
 
2704
            # the current row consists entire of the current item (being marked
 
2705
            # absent), and relocated or absent entries for the other trees:
 
2706
            # Remove it, its meaningless.
1284
2707
            block = self._find_block(current_old[0])
1285
2708
            entry_index, present = self._find_entry_index(current_old[0], block[1])
1286
 
            assert present
 
2709
            if not present:
 
2710
                raise AssertionError('could not find entry for %s' % (current_old,))
1287
2711
            block[1].pop(entry_index)
1288
 
 
1289
 
    def update_minimal(self, key, kind, num_present_parents, executable=False,
1290
 
        fingerprint='', packed_stat=None, size=0, id_index=None,
1291
 
        path_utf8=None):
1292
 
        """Update an entry to the state in tree 0."""
1293
 
        if key[0:2] == ('', ''):
1294
 
            block = self._root_entries
1295
 
        else:
1296
 
            block = self._find_block(key)[1]
 
2712
            # if we have an id_index in use, remove this key from it for this id.
 
2713
            if self._id_index is not None:
 
2714
                self._remove_from_id_index(self._id_index, current_old[0])
 
2715
        # update all remaining keys for this id to record it as absent. The
 
2716
        # existing details may either be the record we are marking as deleted
 
2717
        # (if there were other trees with the id present at this path), or may
 
2718
        # be relocations.
 
2719
        for update_key in all_remaining_keys:
 
2720
            update_block_index, present = \
 
2721
                self._find_block_index_from_key(update_key)
 
2722
            if not present:
 
2723
                raise AssertionError('could not find block for %s' % (update_key,))
 
2724
            update_entry_index, present = \
 
2725
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
 
2726
            if not present:
 
2727
                raise AssertionError('could not find entry for %s' % (update_key,))
 
2728
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
 
2729
            # it must not be absent at the moment
 
2730
            if update_tree_details[0][0] == 'a': # absent
 
2731
                raise AssertionError('bad row %r' % (update_tree_details,))
 
2732
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
 
2733
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
2734
        return last_reference
 
2735
 
 
2736
    def update_minimal(self, key, minikind, executable=False, fingerprint='',
 
2737
        packed_stat=None, size=0, path_utf8=None, fullscan=False):
 
2738
        """Update an entry to the state in tree 0.
 
2739
 
 
2740
        This will either create a new entry at 'key' or update an existing one.
 
2741
        It also makes sure that any other records which might mention this are
 
2742
        updated as well.
 
2743
 
 
2744
        :param key: (dir, name, file_id) for the new entry
 
2745
        :param minikind: The type for the entry ('f' == 'file', 'd' ==
 
2746
                'directory'), etc.
 
2747
        :param executable: Should the executable bit be set?
 
2748
        :param fingerprint: Simple fingerprint for new entry: canonical-form
 
2749
            sha1 for files, referenced revision id for subtrees, etc.
 
2750
        :param packed_stat: Packed stat value for new entry.
 
2751
        :param size: Size information for new entry
 
2752
        :param path_utf8: key[0] + '/' + key[1], just passed in to avoid doing
 
2753
                extra computation.
 
2754
        :param fullscan: If True then a complete scan of the dirstate is being
 
2755
            done and checking for duplicate rows should not be done. This
 
2756
            should only be set by set_state_from_inventory and similar methods.
 
2757
 
 
2758
        If packed_stat and fingerprint are not given, they're invalidated in
 
2759
        the entry.
 
2760
        """
 
2761
        block = self._find_block(key)[1]
1297
2762
        if packed_stat is None:
1298
2763
            packed_stat = DirState.NULLSTAT
 
2764
        # XXX: Some callers pass '' as the packed_stat, and it seems to be
 
2765
        # sometimes present in the dirstate - this seems oddly inconsistent.
 
2766
        # mbp 20071008
1299
2767
        entry_index, present = self._find_entry_index(key, block)
1300
 
        new_details = (kind, fingerprint, size, executable, packed_stat)
1301
 
        assert id_index, 'need an id index to do updates for now !'
 
2768
        new_details = (minikind, fingerprint, size, executable, packed_stat)
 
2769
        id_index = self._get_id_index()
1302
2770
        if not present:
 
2771
            # New record. Check there isn't a entry at this path already.
 
2772
            if not fullscan:
 
2773
                low_index, _ = self._find_entry_index(key[0:2] + ('',), block)
 
2774
                while low_index < len(block):
 
2775
                    entry = block[low_index]
 
2776
                    if entry[0][0:2] == key[0:2]:
 
2777
                        if entry[1][0][0] not in 'ar':
 
2778
                            # This entry has the same path (but a different id) as
 
2779
                            # the new entry we're adding, and is present in ths
 
2780
                            # tree.
 
2781
                            raise errors.InconsistentDelta(
 
2782
                                ("%s/%s" % key[0:2]).decode('utf8'), key[2],
 
2783
                                "Attempt to add item at path already occupied by "
 
2784
                                "id %r" % entry[0][2])
 
2785
                        low_index += 1
 
2786
                    else:
 
2787
                        break
1303
2788
            # new entry, synthesis cross reference here,
1304
 
            existing_keys = id_index.setdefault(key[2], set())
 
2789
            existing_keys = id_index.get(key[2], ())
1305
2790
            if not existing_keys:
1306
2791
                # not currently in the state, simplest case
1307
2792
                new_entry = key, [new_details] + self._empty_parent_info()
1310
2795
                # grab one of them and use it to generate parent
1311
2796
                # relocation/absent entries.
1312
2797
                new_entry = key, [new_details]
1313
 
                for other_key in existing_keys:
 
2798
                # existing_keys can be changed as we iterate.
 
2799
                for other_key in tuple(existing_keys):
1314
2800
                    # change the record at other to be a pointer to this new
1315
2801
                    # record. The loop looks similar to the change to
1316
2802
                    # relocations when updating an existing record but its not:
1317
2803
                    # the test for existing kinds is different: this can be
1318
2804
                    # factored out to a helper though.
1319
 
                    other_block_index, present = self._find_block_index_from_key(other_key)
1320
 
                    assert present
1321
 
                    other_entry_index, present = self._find_entry_index(other_key, self._dirblocks[other_block_index][1])
1322
 
                    assert present
1323
 
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
1324
 
                        ('relocated', path_utf8, 0, False, '')
 
2805
                    other_block_index, present = self._find_block_index_from_key(
 
2806
                        other_key)
 
2807
                    if not present:
 
2808
                        raise AssertionError('could not find block for %s' % (
 
2809
                            other_key,))
 
2810
                    other_block = self._dirblocks[other_block_index][1]
 
2811
                    other_entry_index, present = self._find_entry_index(
 
2812
                        other_key, other_block)
 
2813
                    if not present:
 
2814
                        raise AssertionError(
 
2815
                            'update_minimal: could not find other entry for %s'
 
2816
                            % (other_key,))
 
2817
                    if path_utf8 is None:
 
2818
                        raise AssertionError('no path')
 
2819
                    # Turn this other location into a reference to the new
 
2820
                    # location. This also updates the aliased iterator
 
2821
                    # (current_old in set_state_from_inventory) so that the old
 
2822
                    # entry, if not already examined, is skipped over by that
 
2823
                    # loop.
 
2824
                    other_entry = other_block[other_entry_index]
 
2825
                    other_entry[1][0] = ('r', path_utf8, 0, False, '')
 
2826
                    if self._maybe_remove_row(other_block, other_entry_index,
 
2827
                                              id_index):
 
2828
                        # If the row holding this was removed, we need to
 
2829
                        # recompute where this entry goes
 
2830
                        entry_index, _ = self._find_entry_index(key, block)
1325
2831
 
 
2832
                # This loop:
 
2833
                # adds a tuple to the new details for each column
 
2834
                #  - either by copying an existing relocation pointer inside that column
 
2835
                #  - or by creating a new pointer to the right row inside that column
 
2836
                num_present_parents = self._num_present_parents()
 
2837
                if num_present_parents:
 
2838
                    # TODO: This re-evaluates the existing_keys set, do we need
 
2839
                    #       to do that ourselves?
 
2840
                    other_key = list(existing_keys)[0]
1326
2841
                for lookup_index in xrange(1, num_present_parents + 1):
1327
2842
                    # grab any one entry, use it to find the right path.
1328
 
                    # TODO: optimise this to reduce memory use in highly 
 
2843
                    # TODO: optimise this to reduce memory use in highly
1329
2844
                    # fragmented situations by reusing the relocation
1330
2845
                    # records.
1331
2846
                    update_block_index, present = \
1332
2847
                        self._find_block_index_from_key(other_key)
1333
 
                    assert present
 
2848
                    if not present:
 
2849
                        raise AssertionError('could not find block for %s' % (other_key,))
1334
2850
                    update_entry_index, present = \
1335
2851
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
1336
 
                    assert present
 
2852
                    if not present:
 
2853
                        raise AssertionError('update_minimal: could not find entry for %s' % (other_key,))
1337
2854
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
1338
 
                    if update_details[0] in ('relocated', 'absent'):
 
2855
                    if update_details[0] in 'ar': # relocated, absent
1339
2856
                        # its a pointer or absent in lookup_index's tree, use
1340
2857
                        # it as is.
1341
2858
                        new_entry[1].append(update_details)
1342
2859
                    else:
1343
2860
                        # we have the right key, make a pointer to it.
1344
 
                        pointer_path = os.path.join(other_key[0:2])
1345
 
                        new_details.append(('relocated', pointer_path, 0, False, ''))
 
2861
                        pointer_path = osutils.pathjoin(*other_key[0:2])
 
2862
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
1346
2863
            block.insert(entry_index, new_entry)
1347
 
            existing_keys.add(key)
 
2864
            self._add_to_id_index(id_index, key)
1348
2865
        else:
1349
 
            # Does the new state matter? 
 
2866
            # Does the new state matter?
1350
2867
            block[entry_index][1][0] = new_details
1351
2868
            # parents cannot be affected by what we do.
1352
 
            # other occurences of this id can be found 
 
2869
            # other occurences of this id can be found
1353
2870
            # from the id index.
1354
2871
            # ---
1355
2872
            # tree index consistency: All other paths for this id in this tree
1357
2874
            # we may have passed entries in the state with this file id already
1358
2875
            # that were absent - where parent entries are - and they need to be
1359
2876
            # converted to relocated.
1360
 
            assert path_utf8 is not None
1361
 
            for entry_key in id_index.setdefault(key[2], set()):
 
2877
            if path_utf8 is None:
 
2878
                raise AssertionError('no path')
 
2879
            existing_keys = id_index.get(key[2], ())
 
2880
            if key not in existing_keys:
 
2881
                raise AssertionError('We found the entry in the blocks, but'
 
2882
                    ' the key is not in the id_index.'
 
2883
                    ' key: %s, existing_keys: %s' % (key, existing_keys))
 
2884
            for entry_key in existing_keys:
1362
2885
                # TODO:PROFILING: It might be faster to just update
1363
2886
                # rather than checking if we need to, and then overwrite
1364
2887
                # the one we are located at.
1368
2891
                    # This is the vertical axis in the matrix, all pointing
1369
2892
                    # to the real path.
1370
2893
                    block_index, present = self._find_block_index_from_key(entry_key)
1371
 
                    assert present
 
2894
                    if not present:
 
2895
                        raise AssertionError('not present: %r', entry_key)
1372
2896
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
1373
 
                    assert present
 
2897
                    if not present:
 
2898
                        raise AssertionError('not present: %r', entry_key)
1374
2899
                    self._dirblocks[block_index][1][entry_index][1][0] = \
1375
 
                        ('relocated', path_utf8, 0, False, '')
 
2900
                        ('r', path_utf8, 0, False, '')
 
2901
        # add a containing dirblock if needed.
 
2902
        if new_details[0] == 'd':
 
2903
            subdir_key = (osutils.pathjoin(*key[0:2]), '', '')
 
2904
            block_index, present = self._find_block_index_from_key(subdir_key)
 
2905
            if not present:
 
2906
                self._dirblocks.insert(block_index, (subdir_key[0], []))
1376
2907
 
1377
2908
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
1378
2909
 
1379
 
 
1380
 
 
1381
 
def pack_stat(st, _encode=base64.encodestring, _pack=struct.pack):
1382
 
    """Convert stat values into a packed representation."""
1383
 
    # jam 20060614 it isn't really worth removing more entries if we
1384
 
    # are going to leave it in packed form.
1385
 
    # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
1386
 
    # With all entries filesize is 5.9M and read time is mabye 280ms
1387
 
    # well within the noise margin
1388
 
 
1389
 
    # base64.encode always adds a final newline, so strip it off
1390
 
    return _encode(_pack('>llllll'
1391
 
        , st.st_size, st.st_mtime, st.st_ctime
1392
 
        , st.st_dev, st.st_ino, st.st_mode))[:-1]
1393
 
 
 
2910
    def _maybe_remove_row(self, block, index, id_index):
 
2911
        """Remove index if it is absent or relocated across the row.
 
2912
        
 
2913
        id_index is updated accordingly.
 
2914
        :return: True if we removed the row, False otherwise
 
2915
        """
 
2916
        present_in_row = False
 
2917
        entry = block[index]
 
2918
        for column in entry[1]:
 
2919
            if column[0] not in 'ar':
 
2920
                present_in_row = True
 
2921
                break
 
2922
        if not present_in_row:
 
2923
            block.pop(index)
 
2924
            self._remove_from_id_index(id_index, entry[0])
 
2925
            return True
 
2926
        return False
 
2927
 
 
2928
    def _validate(self):
 
2929
        """Check that invariants on the dirblock are correct.
 
2930
 
 
2931
        This can be useful in debugging; it shouldn't be necessary in
 
2932
        normal code.
 
2933
 
 
2934
        This must be called with a lock held.
 
2935
        """
 
2936
        # NOTE: This must always raise AssertionError not just assert,
 
2937
        # otherwise it may not behave properly under python -O
 
2938
        #
 
2939
        # TODO: All entries must have some content that's not 'a' or 'r',
 
2940
        # otherwise it could just be removed.
 
2941
        #
 
2942
        # TODO: All relocations must point directly to a real entry.
 
2943
        #
 
2944
        # TODO: No repeated keys.
 
2945
        #
 
2946
        # -- mbp 20070325
 
2947
        from pprint import pformat
 
2948
        self._read_dirblocks_if_needed()
 
2949
        if len(self._dirblocks) > 0:
 
2950
            if not self._dirblocks[0][0] == '':
 
2951
                raise AssertionError(
 
2952
                    "dirblocks don't start with root block:\n" + \
 
2953
                    pformat(self._dirblocks))
 
2954
        if len(self._dirblocks) > 1:
 
2955
            if not self._dirblocks[1][0] == '':
 
2956
                raise AssertionError(
 
2957
                    "dirblocks missing root directory:\n" + \
 
2958
                    pformat(self._dirblocks))
 
2959
        # the dirblocks are sorted by their path components, name, and dir id
 
2960
        dir_names = [d[0].split('/')
 
2961
                for d in self._dirblocks[1:]]
 
2962
        if dir_names != sorted(dir_names):
 
2963
            raise AssertionError(
 
2964
                "dir names are not in sorted order:\n" + \
 
2965
                pformat(self._dirblocks) + \
 
2966
                "\nkeys:\n" +
 
2967
                pformat(dir_names))
 
2968
        for dirblock in self._dirblocks:
 
2969
            # within each dirblock, the entries are sorted by filename and
 
2970
            # then by id.
 
2971
            for entry in dirblock[1]:
 
2972
                if dirblock[0] != entry[0][0]:
 
2973
                    raise AssertionError(
 
2974
                        "entry key for %r"
 
2975
                        "doesn't match directory name in\n%r" %
 
2976
                        (entry, pformat(dirblock)))
 
2977
            if dirblock[1] != sorted(dirblock[1]):
 
2978
                raise AssertionError(
 
2979
                    "dirblock for %r is not sorted:\n%s" % \
 
2980
                    (dirblock[0], pformat(dirblock)))
 
2981
 
 
2982
        def check_valid_parent():
 
2983
            """Check that the current entry has a valid parent.
 
2984
 
 
2985
            This makes sure that the parent has a record,
 
2986
            and that the parent isn't marked as "absent" in the
 
2987
            current tree. (It is invalid to have a non-absent file in an absent
 
2988
            directory.)
 
2989
            """
 
2990
            if entry[0][0:2] == ('', ''):
 
2991
                # There should be no parent for the root row
 
2992
                return
 
2993
            parent_entry = self._get_entry(tree_index, path_utf8=entry[0][0])
 
2994
            if parent_entry == (None, None):
 
2995
                raise AssertionError(
 
2996
                    "no parent entry for: %s in tree %s"
 
2997
                    % (this_path, tree_index))
 
2998
            if parent_entry[1][tree_index][0] != 'd':
 
2999
                raise AssertionError(
 
3000
                    "Parent entry for %s is not marked as a valid"
 
3001
                    " directory. %s" % (this_path, parent_entry,))
 
3002
 
 
3003
        # For each file id, for each tree: either
 
3004
        # the file id is not present at all; all rows with that id in the
 
3005
        # key have it marked as 'absent'
 
3006
        # OR the file id is present under exactly one name; any other entries
 
3007
        # that mention that id point to the correct name.
 
3008
        #
 
3009
        # We check this with a dict per tree pointing either to the present
 
3010
        # name, or None if absent.
 
3011
        tree_count = self._num_present_parents() + 1
 
3012
        id_path_maps = [dict() for i in range(tree_count)]
 
3013
        # Make sure that all renamed entries point to the correct location.
 
3014
        for entry in self._iter_entries():
 
3015
            file_id = entry[0][2]
 
3016
            this_path = osutils.pathjoin(entry[0][0], entry[0][1])
 
3017
            if len(entry[1]) != tree_count:
 
3018
                raise AssertionError(
 
3019
                "wrong number of entry details for row\n%s" \
 
3020
                ",\nexpected %d" % \
 
3021
                (pformat(entry), tree_count))
 
3022
            absent_positions = 0
 
3023
            for tree_index, tree_state in enumerate(entry[1]):
 
3024
                this_tree_map = id_path_maps[tree_index]
 
3025
                minikind = tree_state[0]
 
3026
                if minikind in 'ar':
 
3027
                    absent_positions += 1
 
3028
                # have we seen this id before in this column?
 
3029
                if file_id in this_tree_map:
 
3030
                    previous_path, previous_loc = this_tree_map[file_id]
 
3031
                    # any later mention of this file must be consistent with
 
3032
                    # what was said before
 
3033
                    if minikind == 'a':
 
3034
                        if previous_path is not None:
 
3035
                            raise AssertionError(
 
3036
                            "file %s is absent in row %r but also present " \
 
3037
                            "at %r"% \
 
3038
                            (file_id, entry, previous_path))
 
3039
                    elif minikind == 'r':
 
3040
                        target_location = tree_state[1]
 
3041
                        if previous_path != target_location:
 
3042
                            raise AssertionError(
 
3043
                            "file %s relocation in row %r but also at %r" \
 
3044
                            % (file_id, entry, previous_path))
 
3045
                    else:
 
3046
                        # a file, directory, etc - may have been previously
 
3047
                        # pointed to by a relocation, which must point here
 
3048
                        if previous_path != this_path:
 
3049
                            raise AssertionError(
 
3050
                                "entry %r inconsistent with previous path %r "
 
3051
                                "seen at %r" %
 
3052
                                (entry, previous_path, previous_loc))
 
3053
                        check_valid_parent()
 
3054
                else:
 
3055
                    if minikind == 'a':
 
3056
                        # absent; should not occur anywhere else
 
3057
                        this_tree_map[file_id] = None, this_path
 
3058
                    elif minikind == 'r':
 
3059
                        # relocation, must occur at expected location
 
3060
                        this_tree_map[file_id] = tree_state[1], this_path
 
3061
                    else:
 
3062
                        this_tree_map[file_id] = this_path, this_path
 
3063
                        check_valid_parent()
 
3064
            if absent_positions == tree_count:
 
3065
                raise AssertionError(
 
3066
                    "entry %r has no data for any tree." % (entry,))
 
3067
        if self._id_index is not None:
 
3068
            for file_id, entry_keys in self._id_index.iteritems():
 
3069
                for entry_key in entry_keys:
 
3070
                    if entry_key[2] != file_id:
 
3071
                        raise AssertionError(
 
3072
                            'file_id %r did not match entry key %s'
 
3073
                            % (file_id, entry_key))
 
3074
                if len(entry_keys) != len(set(entry_keys)):
 
3075
                    raise AssertionError(
 
3076
                        'id_index contained non-unique data for %s'
 
3077
                        % (entry_keys,))
 
3078
 
 
3079
    def _wipe_state(self):
 
3080
        """Forget all state information about the dirstate."""
 
3081
        self._header_state = DirState.NOT_IN_MEMORY
 
3082
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
3083
        self._changes_aborted = False
 
3084
        self._parents = []
 
3085
        self._ghosts = []
 
3086
        self._dirblocks = []
 
3087
        self._id_index = None
 
3088
        self._packed_stat_index = None
 
3089
        self._end_of_header = None
 
3090
        self._cutoff_time = None
 
3091
        self._split_path_cache = {}
 
3092
 
 
3093
    def lock_read(self):
 
3094
        """Acquire a read lock on the dirstate."""
 
3095
        if self._lock_token is not None:
 
3096
            raise errors.LockContention(self._lock_token)
 
3097
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
 
3098
        #       already in memory, we could read just the header and check for
 
3099
        #       any modification. If not modified, we can just leave things
 
3100
        #       alone
 
3101
        self._lock_token = lock.ReadLock(self._filename)
 
3102
        self._lock_state = 'r'
 
3103
        self._state_file = self._lock_token.f
 
3104
        self._wipe_state()
 
3105
 
 
3106
    def lock_write(self):
 
3107
        """Acquire a write lock on the dirstate."""
 
3108
        if self._lock_token is not None:
 
3109
            raise errors.LockContention(self._lock_token)
 
3110
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
 
3111
        #       already in memory, we could read just the header and check for
 
3112
        #       any modification. If not modified, we can just leave things
 
3113
        #       alone
 
3114
        self._lock_token = lock.WriteLock(self._filename)
 
3115
        self._lock_state = 'w'
 
3116
        self._state_file = self._lock_token.f
 
3117
        self._wipe_state()
 
3118
 
 
3119
    def unlock(self):
 
3120
        """Drop any locks held on the dirstate."""
 
3121
        if self._lock_token is None:
 
3122
            raise errors.LockNotHeld(self)
 
3123
        # TODO: jam 20070301 Rather than wiping completely, if the blocks are
 
3124
        #       already in memory, we could read just the header and check for
 
3125
        #       any modification. If not modified, we can just leave things
 
3126
        #       alone
 
3127
        self._state_file = None
 
3128
        self._lock_state = None
 
3129
        self._lock_token.unlock()
 
3130
        self._lock_token = None
 
3131
        self._split_path_cache = {}
 
3132
 
 
3133
    def _requires_lock(self):
 
3134
        """Check that a lock is currently held by someone on the dirstate."""
 
3135
        if not self._lock_token:
 
3136
            raise errors.ObjectNotLocked(self)
 
3137
 
 
3138
 
 
3139
def py_update_entry(state, entry, abspath, stat_value,
 
3140
                 _stat_to_minikind=DirState._stat_to_minikind,
 
3141
                 _pack_stat=pack_stat):
 
3142
    """Update the entry based on what is actually on disk.
 
3143
 
 
3144
    This function only calculates the sha if it needs to - if the entry is
 
3145
    uncachable, or clearly different to the first parent's entry, no sha
 
3146
    is calculated, and None is returned.
 
3147
 
 
3148
    :param state: The dirstate this entry is in.
 
3149
    :param entry: This is the dirblock entry for the file in question.
 
3150
    :param abspath: The path on disk for this file.
 
3151
    :param stat_value: The stat value done on the path.
 
3152
    :return: None, or The sha1 hexdigest of the file (40 bytes) or link
 
3153
        target of a symlink.
 
3154
    """
 
3155
    try:
 
3156
        minikind = _stat_to_minikind[stat_value.st_mode & 0170000]
 
3157
    except KeyError:
 
3158
        # Unhandled kind
 
3159
        return None
 
3160
    packed_stat = _pack_stat(stat_value)
 
3161
    (saved_minikind, saved_link_or_sha1, saved_file_size,
 
3162
     saved_executable, saved_packed_stat) = entry[1][0]
 
3163
 
 
3164
    if minikind == 'd' and saved_minikind == 't':
 
3165
        minikind = 't'
 
3166
    if (minikind == saved_minikind
 
3167
        and packed_stat == saved_packed_stat):
 
3168
        # The stat hasn't changed since we saved, so we can re-use the
 
3169
        # saved sha hash.
 
3170
        if minikind == 'd':
 
3171
            return None
 
3172
 
 
3173
        # size should also be in packed_stat
 
3174
        if saved_file_size == stat_value.st_size:
 
3175
            return saved_link_or_sha1
 
3176
 
 
3177
    # If we have gotten this far, that means that we need to actually
 
3178
    # process this entry.
 
3179
    link_or_sha1 = None
 
3180
    if minikind == 'f':
 
3181
        executable = state._is_executable(stat_value.st_mode,
 
3182
                                         saved_executable)
 
3183
        if state._cutoff_time is None:
 
3184
            state._sha_cutoff_time()
 
3185
        if (stat_value.st_mtime < state._cutoff_time
 
3186
            and stat_value.st_ctime < state._cutoff_time
 
3187
            and len(entry[1]) > 1
 
3188
            and entry[1][1][0] != 'a'):
 
3189
            # Could check for size changes for further optimised
 
3190
            # avoidance of sha1's. However the most prominent case of
 
3191
            # over-shaing is during initial add, which this catches.
 
3192
            # Besides, if content filtering happens, size and sha
 
3193
            # are calculated at the same time, so checking just the size
 
3194
            # gains nothing w.r.t. performance.
 
3195
            link_or_sha1 = state._sha1_file(abspath)
 
3196
            entry[1][0] = ('f', link_or_sha1, stat_value.st_size,
 
3197
                           executable, packed_stat)
 
3198
        else:
 
3199
            entry[1][0] = ('f', '', stat_value.st_size,
 
3200
                           executable, DirState.NULLSTAT)
 
3201
    elif minikind == 'd':
 
3202
        link_or_sha1 = None
 
3203
        entry[1][0] = ('d', '', 0, False, packed_stat)
 
3204
        if saved_minikind != 'd':
 
3205
            # This changed from something into a directory. Make sure we
 
3206
            # have a directory block for it. This doesn't happen very
 
3207
            # often, so this doesn't have to be super fast.
 
3208
            block_index, entry_index, dir_present, file_present = \
 
3209
                state._get_block_entry_index(entry[0][0], entry[0][1], 0)
 
3210
            state._ensure_block(block_index, entry_index,
 
3211
                               osutils.pathjoin(entry[0][0], entry[0][1]))
 
3212
    elif minikind == 'l':
 
3213
        link_or_sha1 = state._read_link(abspath, saved_link_or_sha1)
 
3214
        if state._cutoff_time is None:
 
3215
            state._sha_cutoff_time()
 
3216
        if (stat_value.st_mtime < state._cutoff_time
 
3217
            and stat_value.st_ctime < state._cutoff_time):
 
3218
            entry[1][0] = ('l', link_or_sha1, stat_value.st_size,
 
3219
                           False, packed_stat)
 
3220
        else:
 
3221
            entry[1][0] = ('l', '', stat_value.st_size,
 
3222
                           False, DirState.NULLSTAT)
 
3223
    state._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
3224
    return link_or_sha1
 
3225
 
 
3226
 
 
3227
class ProcessEntryPython(object):
 
3228
 
 
3229
    __slots__ = ["old_dirname_to_file_id", "new_dirname_to_file_id",
 
3230
        "last_source_parent", "last_target_parent", "include_unchanged",
 
3231
        "partial", "use_filesystem_for_exec", "utf8_decode",
 
3232
        "searched_specific_files", "search_specific_files",
 
3233
        "searched_exact_paths", "search_specific_file_parents", "seen_ids",
 
3234
        "state", "source_index", "target_index", "want_unversioned", "tree"]
 
3235
 
 
3236
    def __init__(self, include_unchanged, use_filesystem_for_exec,
 
3237
        search_specific_files, state, source_index, target_index,
 
3238
        want_unversioned, tree):
 
3239
        self.old_dirname_to_file_id = {}
 
3240
        self.new_dirname_to_file_id = {}
 
3241
        # Are we doing a partial iter_changes?
 
3242
        self.partial = search_specific_files != set([''])
 
3243
        # Using a list so that we can access the values and change them in
 
3244
        # nested scope. Each one is [path, file_id, entry]
 
3245
        self.last_source_parent = [None, None]
 
3246
        self.last_target_parent = [None, None]
 
3247
        self.include_unchanged = include_unchanged
 
3248
        self.use_filesystem_for_exec = use_filesystem_for_exec
 
3249
        self.utf8_decode = cache_utf8._utf8_decode
 
3250
        # for all search_indexs in each path at or under each element of
 
3251
        # search_specific_files, if the detail is relocated: add the id, and
 
3252
        # add the relocated path as one to search if its not searched already.
 
3253
        # If the detail is not relocated, add the id.
 
3254
        self.searched_specific_files = set()
 
3255
        # When we search exact paths without expanding downwards, we record
 
3256
        # that here.
 
3257
        self.searched_exact_paths = set()
 
3258
        self.search_specific_files = search_specific_files
 
3259
        # The parents up to the root of the paths we are searching.
 
3260
        # After all normal paths are returned, these specific items are returned.
 
3261
        self.search_specific_file_parents = set()
 
3262
        # The ids we've sent out in the delta.
 
3263
        self.seen_ids = set()
 
3264
        self.state = state
 
3265
        self.source_index = source_index
 
3266
        self.target_index = target_index
 
3267
        if target_index != 0:
 
3268
            # A lot of code in here depends on target_index == 0
 
3269
            raise errors.BzrError('unsupported target index')
 
3270
        self.want_unversioned = want_unversioned
 
3271
        self.tree = tree
 
3272
 
 
3273
    def _process_entry(self, entry, path_info, pathjoin=osutils.pathjoin):
 
3274
        """Compare an entry and real disk to generate delta information.
 
3275
 
 
3276
        :param path_info: top_relpath, basename, kind, lstat, abspath for
 
3277
            the path of entry. If None, then the path is considered absent in 
 
3278
            the target (Perhaps we should pass in a concrete entry for this ?)
 
3279
            Basename is returned as a utf8 string because we expect this
 
3280
            tuple will be ignored, and don't want to take the time to
 
3281
            decode.
 
3282
        :return: (iter_changes_result, changed). If the entry has not been
 
3283
            handled then changed is None. Otherwise it is False if no content
 
3284
            or metadata changes have occurred, and True if any content or
 
3285
            metadata change has occurred. If self.include_unchanged is True then
 
3286
            if changed is not None, iter_changes_result will always be a result
 
3287
            tuple. Otherwise, iter_changes_result is None unless changed is
 
3288
            True.
 
3289
        """
 
3290
        if self.source_index is None:
 
3291
            source_details = DirState.NULL_PARENT_DETAILS
 
3292
        else:
 
3293
            source_details = entry[1][self.source_index]
 
3294
        target_details = entry[1][self.target_index]
 
3295
        target_minikind = target_details[0]
 
3296
        if path_info is not None and target_minikind in 'fdlt':
 
3297
            if not (self.target_index == 0):
 
3298
                raise AssertionError()
 
3299
            link_or_sha1 = update_entry(self.state, entry,
 
3300
                abspath=path_info[4], stat_value=path_info[3])
 
3301
            # The entry may have been modified by update_entry
 
3302
            target_details = entry[1][self.target_index]
 
3303
            target_minikind = target_details[0]
 
3304
        else:
 
3305
            link_or_sha1 = None
 
3306
        file_id = entry[0][2]
 
3307
        source_minikind = source_details[0]
 
3308
        if source_minikind in 'fdltr' and target_minikind in 'fdlt':
 
3309
            # claimed content in both: diff
 
3310
            #   r    | fdlt   |      | add source to search, add id path move and perform
 
3311
            #        |        |      | diff check on source-target
 
3312
            #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
3313
            #        |        |      | ???
 
3314
            if source_minikind in 'r':
 
3315
                # add the source to the search path to find any children it
 
3316
                # has.  TODO ? : only add if it is a container ?
 
3317
                if not osutils.is_inside_any(self.searched_specific_files,
 
3318
                                             source_details[1]):
 
3319
                    self.search_specific_files.add(source_details[1])
 
3320
                # generate the old path; this is needed for stating later
 
3321
                # as well.
 
3322
                old_path = source_details[1]
 
3323
                old_dirname, old_basename = os.path.split(old_path)
 
3324
                path = pathjoin(entry[0][0], entry[0][1])
 
3325
                old_entry = self.state._get_entry(self.source_index,
 
3326
                                             path_utf8=old_path)
 
3327
                # update the source details variable to be the real
 
3328
                # location.
 
3329
                if old_entry == (None, None):
 
3330
                    raise errors.CorruptDirstate(self.state._filename,
 
3331
                        "entry '%s/%s' is considered renamed from %r"
 
3332
                        " but source does not exist\n"
 
3333
                        "entry: %s" % (entry[0][0], entry[0][1], old_path, entry))
 
3334
                source_details = old_entry[1][self.source_index]
 
3335
                source_minikind = source_details[0]
 
3336
            else:
 
3337
                old_dirname = entry[0][0]
 
3338
                old_basename = entry[0][1]
 
3339
                old_path = path = None
 
3340
            if path_info is None:
 
3341
                # the file is missing on disk, show as removed.
 
3342
                content_change = True
 
3343
                target_kind = None
 
3344
                target_exec = False
 
3345
            else:
 
3346
                # source and target are both versioned and disk file is present.
 
3347
                target_kind = path_info[2]
 
3348
                if target_kind == 'directory':
 
3349
                    if path is None:
 
3350
                        old_path = path = pathjoin(old_dirname, old_basename)
 
3351
                    self.new_dirname_to_file_id[path] = file_id
 
3352
                    if source_minikind != 'd':
 
3353
                        content_change = True
 
3354
                    else:
 
3355
                        # directories have no fingerprint
 
3356
                        content_change = False
 
3357
                    target_exec = False
 
3358
                elif target_kind == 'file':
 
3359
                    if source_minikind != 'f':
 
3360
                        content_change = True
 
3361
                    else:
 
3362
                        # Check the sha. We can't just rely on the size as
 
3363
                        # content filtering may mean differ sizes actually
 
3364
                        # map to the same content
 
3365
                        if link_or_sha1 is None:
 
3366
                            # Stat cache miss:
 
3367
                            statvalue, link_or_sha1 = \
 
3368
                                self.state._sha1_provider.stat_and_sha1(
 
3369
                                path_info[4])
 
3370
                            self.state._observed_sha1(entry, link_or_sha1,
 
3371
                                statvalue)
 
3372
                        content_change = (link_or_sha1 != source_details[1])
 
3373
                    # Target details is updated at update_entry time
 
3374
                    if self.use_filesystem_for_exec:
 
3375
                        # We don't need S_ISREG here, because we are sure
 
3376
                        # we are dealing with a file.
 
3377
                        target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
 
3378
                    else:
 
3379
                        target_exec = target_details[3]
 
3380
                elif target_kind == 'symlink':
 
3381
                    if source_minikind != 'l':
 
3382
                        content_change = True
 
3383
                    else:
 
3384
                        content_change = (link_or_sha1 != source_details[1])
 
3385
                    target_exec = False
 
3386
                elif target_kind == 'tree-reference':
 
3387
                    if source_minikind != 't':
 
3388
                        content_change = True
 
3389
                    else:
 
3390
                        content_change = False
 
3391
                    target_exec = False
 
3392
                else:
 
3393
                    if path is None:
 
3394
                        path = pathjoin(old_dirname, old_basename)
 
3395
                    raise errors.BadFileKindError(path, path_info[2])
 
3396
            if source_minikind == 'd':
 
3397
                if path is None:
 
3398
                    old_path = path = pathjoin(old_dirname, old_basename)
 
3399
                self.old_dirname_to_file_id[old_path] = file_id
 
3400
            # parent id is the entry for the path in the target tree
 
3401
            if old_basename and old_dirname == self.last_source_parent[0]:
 
3402
                source_parent_id = self.last_source_parent[1]
 
3403
            else:
 
3404
                try:
 
3405
                    source_parent_id = self.old_dirname_to_file_id[old_dirname]
 
3406
                except KeyError:
 
3407
                    source_parent_entry = self.state._get_entry(self.source_index,
 
3408
                                                           path_utf8=old_dirname)
 
3409
                    source_parent_id = source_parent_entry[0][2]
 
3410
                if source_parent_id == entry[0][2]:
 
3411
                    # This is the root, so the parent is None
 
3412
                    source_parent_id = None
 
3413
                else:
 
3414
                    self.last_source_parent[0] = old_dirname
 
3415
                    self.last_source_parent[1] = source_parent_id
 
3416
            new_dirname = entry[0][0]
 
3417
            if entry[0][1] and new_dirname == self.last_target_parent[0]:
 
3418
                target_parent_id = self.last_target_parent[1]
 
3419
            else:
 
3420
                try:
 
3421
                    target_parent_id = self.new_dirname_to_file_id[new_dirname]
 
3422
                except KeyError:
 
3423
                    # TODO: We don't always need to do the lookup, because the
 
3424
                    #       parent entry will be the same as the source entry.
 
3425
                    target_parent_entry = self.state._get_entry(self.target_index,
 
3426
                                                           path_utf8=new_dirname)
 
3427
                    if target_parent_entry == (None, None):
 
3428
                        raise AssertionError(
 
3429
                            "Could not find target parent in wt: %s\nparent of: %s"
 
3430
                            % (new_dirname, entry))
 
3431
                    target_parent_id = target_parent_entry[0][2]
 
3432
                if target_parent_id == entry[0][2]:
 
3433
                    # This is the root, so the parent is None
 
3434
                    target_parent_id = None
 
3435
                else:
 
3436
                    self.last_target_parent[0] = new_dirname
 
3437
                    self.last_target_parent[1] = target_parent_id
 
3438
 
 
3439
            source_exec = source_details[3]
 
3440
            changed = (content_change
 
3441
                or source_parent_id != target_parent_id
 
3442
                or old_basename != entry[0][1]
 
3443
                or source_exec != target_exec
 
3444
                )
 
3445
            if not changed and not self.include_unchanged:
 
3446
                return None, False
 
3447
            else:
 
3448
                if old_path is None:
 
3449
                    old_path = path = pathjoin(old_dirname, old_basename)
 
3450
                    old_path_u = self.utf8_decode(old_path)[0]
 
3451
                    path_u = old_path_u
 
3452
                else:
 
3453
                    old_path_u = self.utf8_decode(old_path)[0]
 
3454
                    if old_path == path:
 
3455
                        path_u = old_path_u
 
3456
                    else:
 
3457
                        path_u = self.utf8_decode(path)[0]
 
3458
                source_kind = DirState._minikind_to_kind[source_minikind]
 
3459
                return (entry[0][2],
 
3460
                       (old_path_u, path_u),
 
3461
                       content_change,
 
3462
                       (True, True),
 
3463
                       (source_parent_id, target_parent_id),
 
3464
                       (self.utf8_decode(old_basename)[0], self.utf8_decode(entry[0][1])[0]),
 
3465
                       (source_kind, target_kind),
 
3466
                       (source_exec, target_exec)), changed
 
3467
        elif source_minikind in 'a' and target_minikind in 'fdlt':
 
3468
            # looks like a new file
 
3469
            path = pathjoin(entry[0][0], entry[0][1])
 
3470
            # parent id is the entry for the path in the target tree
 
3471
            # TODO: these are the same for an entire directory: cache em.
 
3472
            parent_id = self.state._get_entry(self.target_index,
 
3473
                                         path_utf8=entry[0][0])[0][2]
 
3474
            if parent_id == entry[0][2]:
 
3475
                parent_id = None
 
3476
            if path_info is not None:
 
3477
                # Present on disk:
 
3478
                if self.use_filesystem_for_exec:
 
3479
                    # We need S_ISREG here, because we aren't sure if this
 
3480
                    # is a file or not.
 
3481
                    target_exec = bool(
 
3482
                        stat.S_ISREG(path_info[3].st_mode)
 
3483
                        and stat.S_IEXEC & path_info[3].st_mode)
 
3484
                else:
 
3485
                    target_exec = target_details[3]
 
3486
                return (entry[0][2],
 
3487
                       (None, self.utf8_decode(path)[0]),
 
3488
                       True,
 
3489
                       (False, True),
 
3490
                       (None, parent_id),
 
3491
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3492
                       (None, path_info[2]),
 
3493
                       (None, target_exec)), True
 
3494
            else:
 
3495
                # Its a missing file, report it as such.
 
3496
                return (entry[0][2],
 
3497
                       (None, self.utf8_decode(path)[0]),
 
3498
                       False,
 
3499
                       (False, True),
 
3500
                       (None, parent_id),
 
3501
                       (None, self.utf8_decode(entry[0][1])[0]),
 
3502
                       (None, None),
 
3503
                       (None, False)), True
 
3504
        elif source_minikind in 'fdlt' and target_minikind in 'a':
 
3505
            # unversioned, possibly, or possibly not deleted: we dont care.
 
3506
            # if its still on disk, *and* theres no other entry at this
 
3507
            # path [we dont know this in this routine at the moment -
 
3508
            # perhaps we should change this - then it would be an unknown.
 
3509
            old_path = pathjoin(entry[0][0], entry[0][1])
 
3510
            # parent id is the entry for the path in the target tree
 
3511
            parent_id = self.state._get_entry(self.source_index, path_utf8=entry[0][0])[0][2]
 
3512
            if parent_id == entry[0][2]:
 
3513
                parent_id = None
 
3514
            return (entry[0][2],
 
3515
                   (self.utf8_decode(old_path)[0], None),
 
3516
                   True,
 
3517
                   (True, False),
 
3518
                   (parent_id, None),
 
3519
                   (self.utf8_decode(entry[0][1])[0], None),
 
3520
                   (DirState._minikind_to_kind[source_minikind], None),
 
3521
                   (source_details[3], None)), True
 
3522
        elif source_minikind in 'fdlt' and target_minikind in 'r':
 
3523
            # a rename; could be a true rename, or a rename inherited from
 
3524
            # a renamed parent. TODO: handle this efficiently. Its not
 
3525
            # common case to rename dirs though, so a correct but slow
 
3526
            # implementation will do.
 
3527
            if not osutils.is_inside_any(self.searched_specific_files, target_details[1]):
 
3528
                self.search_specific_files.add(target_details[1])
 
3529
        elif source_minikind in 'ra' and target_minikind in 'ra':
 
3530
            # neither of the selected trees contain this file,
 
3531
            # so skip over it. This is not currently directly tested, but
 
3532
            # is indirectly via test_too_much.TestCommands.test_conflicts.
 
3533
            pass
 
3534
        else:
 
3535
            raise AssertionError("don't know how to compare "
 
3536
                "source_minikind=%r, target_minikind=%r"
 
3537
                % (source_minikind, target_minikind))
 
3538
            ## import pdb;pdb.set_trace()
 
3539
        return None, None
 
3540
 
 
3541
    def __iter__(self):
 
3542
        return self
 
3543
 
 
3544
    def _gather_result_for_consistency(self, result):
 
3545
        """Check a result we will yield to make sure we are consistent later.
 
3546
        
 
3547
        This gathers result's parents into a set to output later.
 
3548
 
 
3549
        :param result: A result tuple.
 
3550
        """
 
3551
        if not self.partial or not result[0]:
 
3552
            return
 
3553
        self.seen_ids.add(result[0])
 
3554
        new_path = result[1][1]
 
3555
        if new_path:
 
3556
            # Not the root and not a delete: queue up the parents of the path.
 
3557
            self.search_specific_file_parents.update(
 
3558
                osutils.parent_directories(new_path.encode('utf8')))
 
3559
            # Add the root directory which parent_directories does not
 
3560
            # provide.
 
3561
            self.search_specific_file_parents.add('')
 
3562
 
 
3563
    def iter_changes(self):
 
3564
        """Iterate over the changes."""
 
3565
        utf8_decode = cache_utf8._utf8_decode
 
3566
        _cmp_by_dirs = cmp_by_dirs
 
3567
        _process_entry = self._process_entry
 
3568
        search_specific_files = self.search_specific_files
 
3569
        searched_specific_files = self.searched_specific_files
 
3570
        splitpath = osutils.splitpath
 
3571
        # sketch:
 
3572
        # compare source_index and target_index at or under each element of search_specific_files.
 
3573
        # follow the following comparison table. Note that we only want to do diff operations when
 
3574
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo
 
3575
        # for the target.
 
3576
        # cases:
 
3577
        #
 
3578
        # Source | Target | disk | action
 
3579
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
3580
        #        |        |      | diff check on source-target
 
3581
        #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
3582
        #        |        |      | ???
 
3583
        #   r    |  a     |      | add source to search
 
3584
        #   r    |  a     |  a   |
 
3585
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
3586
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
3587
        #   a    | fdlt   |      | add new id
 
3588
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
3589
        #   a    |  a     |      | not present in either tree, skip
 
3590
        #   a    |  a     |  a   | not present in any tree, skip
 
3591
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
3592
        #        |        |      | may not be selected by the users list of paths.
 
3593
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
3594
        #        |        |      | may not be selected by the users list of paths.
 
3595
        #  fdlt  | fdlt   |      | content in both: diff them
 
3596
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
3597
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
3598
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
3599
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
3600
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
3601
        #        |        |      | this id at the other path.
 
3602
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
3603
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
3604
        #        |        |      | this id at the other path.
 
3605
 
 
3606
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
 
3607
        #       keeping a cache of directories that we have seen.
 
3608
 
 
3609
        while search_specific_files:
 
3610
            # TODO: the pending list should be lexically sorted?  the
 
3611
            # interface doesn't require it.
 
3612
            current_root = search_specific_files.pop()
 
3613
            current_root_unicode = current_root.decode('utf8')
 
3614
            searched_specific_files.add(current_root)
 
3615
            # process the entries for this containing directory: the rest will be
 
3616
            # found by their parents recursively.
 
3617
            root_entries = self.state._entries_for_path(current_root)
 
3618
            root_abspath = self.tree.abspath(current_root_unicode)
 
3619
            try:
 
3620
                root_stat = os.lstat(root_abspath)
 
3621
            except OSError, e:
 
3622
                if e.errno == errno.ENOENT:
 
3623
                    # the path does not exist: let _process_entry know that.
 
3624
                    root_dir_info = None
 
3625
                else:
 
3626
                    # some other random error: hand it up.
 
3627
                    raise
 
3628
            else:
 
3629
                root_dir_info = ('', current_root,
 
3630
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
3631
                    root_abspath)
 
3632
                if root_dir_info[2] == 'directory':
 
3633
                    if self.tree._directory_is_tree_reference(
 
3634
                        current_root.decode('utf8')):
 
3635
                        root_dir_info = root_dir_info[:2] + \
 
3636
                            ('tree-reference',) + root_dir_info[3:]
 
3637
 
 
3638
            if not root_entries and not root_dir_info:
 
3639
                # this specified path is not present at all, skip it.
 
3640
                continue
 
3641
            path_handled = False
 
3642
            for entry in root_entries:
 
3643
                result, changed = _process_entry(entry, root_dir_info)
 
3644
                if changed is not None:
 
3645
                    path_handled = True
 
3646
                    if changed:
 
3647
                        self._gather_result_for_consistency(result)
 
3648
                    if changed or self.include_unchanged:
 
3649
                        yield result
 
3650
            if self.want_unversioned and not path_handled and root_dir_info:
 
3651
                new_executable = bool(
 
3652
                    stat.S_ISREG(root_dir_info[3].st_mode)
 
3653
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
 
3654
                yield (None,
 
3655
                       (None, current_root_unicode),
 
3656
                       True,
 
3657
                       (False, False),
 
3658
                       (None, None),
 
3659
                       (None, splitpath(current_root_unicode)[-1]),
 
3660
                       (None, root_dir_info[2]),
 
3661
                       (None, new_executable)
 
3662
                      )
 
3663
            initial_key = (current_root, '', '')
 
3664
            block_index, _ = self.state._find_block_index_from_key(initial_key)
 
3665
            if block_index == 0:
 
3666
                # we have processed the total root already, but because the
 
3667
                # initial key matched it we should skip it here.
 
3668
                block_index +=1
 
3669
            if root_dir_info and root_dir_info[2] == 'tree-reference':
 
3670
                current_dir_info = None
 
3671
            else:
 
3672
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
 
3673
                try:
 
3674
                    current_dir_info = dir_iterator.next()
 
3675
                except OSError, e:
 
3676
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
3677
                    # python 2.5 has e.errno == EINVAL,
 
3678
                    #            and e.winerror == ERROR_DIRECTORY
 
3679
                    e_winerror = getattr(e, 'winerror', None)
 
3680
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
3681
                    # there may be directories in the inventory even though
 
3682
                    # this path is not a file on disk: so mark it as end of
 
3683
                    # iterator
 
3684
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
3685
                        current_dir_info = None
 
3686
                    elif (sys.platform == 'win32'
 
3687
                          and (e.errno in win_errors
 
3688
                               or e_winerror in win_errors)):
 
3689
                        current_dir_info = None
 
3690
                    else:
 
3691
                        raise
 
3692
                else:
 
3693
                    if current_dir_info[0][0] == '':
 
3694
                        # remove .bzr from iteration
 
3695
                        bzr_index = bisect.bisect_left(current_dir_info[1], ('.bzr',))
 
3696
                        if current_dir_info[1][bzr_index][0] != '.bzr':
 
3697
                            raise AssertionError()
 
3698
                        del current_dir_info[1][bzr_index]
 
3699
            # walk until both the directory listing and the versioned metadata
 
3700
            # are exhausted.
 
3701
            if (block_index < len(self.state._dirblocks) and
 
3702
                osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3703
                current_block = self.state._dirblocks[block_index]
 
3704
            else:
 
3705
                current_block = None
 
3706
            while (current_dir_info is not None or
 
3707
                   current_block is not None):
 
3708
                if (current_dir_info and current_block
 
3709
                    and current_dir_info[0][0] != current_block[0]):
 
3710
                    if _cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
 
3711
                        # filesystem data refers to paths not covered by the dirblock.
 
3712
                        # this has two possibilities:
 
3713
                        # A) it is versioned but empty, so there is no block for it
 
3714
                        # B) it is not versioned.
 
3715
 
 
3716
                        # if (A) then we need to recurse into it to check for
 
3717
                        # new unknown files or directories.
 
3718
                        # if (B) then we should ignore it, because we don't
 
3719
                        # recurse into unknown directories.
 
3720
                        path_index = 0
 
3721
                        while path_index < len(current_dir_info[1]):
 
3722
                                current_path_info = current_dir_info[1][path_index]
 
3723
                                if self.want_unversioned:
 
3724
                                    if current_path_info[2] == 'directory':
 
3725
                                        if self.tree._directory_is_tree_reference(
 
3726
                                            current_path_info[0].decode('utf8')):
 
3727
                                            current_path_info = current_path_info[:2] + \
 
3728
                                                ('tree-reference',) + current_path_info[3:]
 
3729
                                    new_executable = bool(
 
3730
                                        stat.S_ISREG(current_path_info[3].st_mode)
 
3731
                                        and stat.S_IEXEC & current_path_info[3].st_mode)
 
3732
                                    yield (None,
 
3733
                                        (None, utf8_decode(current_path_info[0])[0]),
 
3734
                                        True,
 
3735
                                        (False, False),
 
3736
                                        (None, None),
 
3737
                                        (None, utf8_decode(current_path_info[1])[0]),
 
3738
                                        (None, current_path_info[2]),
 
3739
                                        (None, new_executable))
 
3740
                                # dont descend into this unversioned path if it is
 
3741
                                # a dir
 
3742
                                if current_path_info[2] in ('directory',
 
3743
                                                            'tree-reference'):
 
3744
                                    del current_dir_info[1][path_index]
 
3745
                                    path_index -= 1
 
3746
                                path_index += 1
 
3747
 
 
3748
                        # This dir info has been handled, go to the next
 
3749
                        try:
 
3750
                            current_dir_info = dir_iterator.next()
 
3751
                        except StopIteration:
 
3752
                            current_dir_info = None
 
3753
                    else:
 
3754
                        # We have a dirblock entry for this location, but there
 
3755
                        # is no filesystem path for this. This is most likely
 
3756
                        # because a directory was removed from the disk.
 
3757
                        # We don't have to report the missing directory,
 
3758
                        # because that should have already been handled, but we
 
3759
                        # need to handle all of the files that are contained
 
3760
                        # within.
 
3761
                        for current_entry in current_block[1]:
 
3762
                            # entry referring to file not present on disk.
 
3763
                            # advance the entry only, after processing.
 
3764
                            result, changed = _process_entry(current_entry, None)
 
3765
                            if changed is not None:
 
3766
                                if changed:
 
3767
                                    self._gather_result_for_consistency(result)
 
3768
                                if changed or self.include_unchanged:
 
3769
                                    yield result
 
3770
                        block_index +=1
 
3771
                        if (block_index < len(self.state._dirblocks) and
 
3772
                            osutils.is_inside(current_root,
 
3773
                                              self.state._dirblocks[block_index][0])):
 
3774
                            current_block = self.state._dirblocks[block_index]
 
3775
                        else:
 
3776
                            current_block = None
 
3777
                    continue
 
3778
                entry_index = 0
 
3779
                if current_block and entry_index < len(current_block[1]):
 
3780
                    current_entry = current_block[1][entry_index]
 
3781
                else:
 
3782
                    current_entry = None
 
3783
                advance_entry = True
 
3784
                path_index = 0
 
3785
                if current_dir_info and path_index < len(current_dir_info[1]):
 
3786
                    current_path_info = current_dir_info[1][path_index]
 
3787
                    if current_path_info[2] == 'directory':
 
3788
                        if self.tree._directory_is_tree_reference(
 
3789
                            current_path_info[0].decode('utf8')):
 
3790
                            current_path_info = current_path_info[:2] + \
 
3791
                                ('tree-reference',) + current_path_info[3:]
 
3792
                else:
 
3793
                    current_path_info = None
 
3794
                advance_path = True
 
3795
                path_handled = False
 
3796
                while (current_entry is not None or
 
3797
                    current_path_info is not None):
 
3798
                    if current_entry is None:
 
3799
                        # the check for path_handled when the path is advanced
 
3800
                        # will yield this path if needed.
 
3801
                        pass
 
3802
                    elif current_path_info is None:
 
3803
                        # no path is fine: the per entry code will handle it.
 
3804
                        result, changed = _process_entry(current_entry, current_path_info)
 
3805
                        if changed is not None:
 
3806
                            if changed:
 
3807
                                self._gather_result_for_consistency(result)
 
3808
                            if changed or self.include_unchanged:
 
3809
                                yield result
 
3810
                    elif (current_entry[0][1] != current_path_info[1]
 
3811
                          or current_entry[1][self.target_index][0] in 'ar'):
 
3812
                        # The current path on disk doesn't match the dirblock
 
3813
                        # record. Either the dirblock is marked as absent, or
 
3814
                        # the file on disk is not present at all in the
 
3815
                        # dirblock. Either way, report about the dirblock
 
3816
                        # entry, and let other code handle the filesystem one.
 
3817
 
 
3818
                        # Compare the basename for these files to determine
 
3819
                        # which comes first
 
3820
                        if current_path_info[1] < current_entry[0][1]:
 
3821
                            # extra file on disk: pass for now, but only
 
3822
                            # increment the path, not the entry
 
3823
                            advance_entry = False
 
3824
                        else:
 
3825
                            # entry referring to file not present on disk.
 
3826
                            # advance the entry only, after processing.
 
3827
                            result, changed = _process_entry(current_entry, None)
 
3828
                            if changed is not None:
 
3829
                                if changed:
 
3830
                                    self._gather_result_for_consistency(result)
 
3831
                                if changed or self.include_unchanged:
 
3832
                                    yield result
 
3833
                            advance_path = False
 
3834
                    else:
 
3835
                        result, changed = _process_entry(current_entry, current_path_info)
 
3836
                        if changed is not None:
 
3837
                            path_handled = True
 
3838
                            if changed:
 
3839
                                self._gather_result_for_consistency(result)
 
3840
                            if changed or self.include_unchanged:
 
3841
                                yield result
 
3842
                    if advance_entry and current_entry is not None:
 
3843
                        entry_index += 1
 
3844
                        if entry_index < len(current_block[1]):
 
3845
                            current_entry = current_block[1][entry_index]
 
3846
                        else:
 
3847
                            current_entry = None
 
3848
                    else:
 
3849
                        advance_entry = True # reset the advance flaga
 
3850
                    if advance_path and current_path_info is not None:
 
3851
                        if not path_handled:
 
3852
                            # unversioned in all regards
 
3853
                            if self.want_unversioned:
 
3854
                                new_executable = bool(
 
3855
                                    stat.S_ISREG(current_path_info[3].st_mode)
 
3856
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
 
3857
                                try:
 
3858
                                    relpath_unicode = utf8_decode(current_path_info[0])[0]
 
3859
                                except UnicodeDecodeError:
 
3860
                                    raise errors.BadFilenameEncoding(
 
3861
                                        current_path_info[0], osutils._fs_enc)
 
3862
                                yield (None,
 
3863
                                    (None, relpath_unicode),
 
3864
                                    True,
 
3865
                                    (False, False),
 
3866
                                    (None, None),
 
3867
                                    (None, utf8_decode(current_path_info[1])[0]),
 
3868
                                    (None, current_path_info[2]),
 
3869
                                    (None, new_executable))
 
3870
                            # dont descend into this unversioned path if it is
 
3871
                            # a dir
 
3872
                            if current_path_info[2] in ('directory'):
 
3873
                                del current_dir_info[1][path_index]
 
3874
                                path_index -= 1
 
3875
                        # dont descend the disk iterator into any tree
 
3876
                        # paths.
 
3877
                        if current_path_info[2] == 'tree-reference':
 
3878
                            del current_dir_info[1][path_index]
 
3879
                            path_index -= 1
 
3880
                        path_index += 1
 
3881
                        if path_index < len(current_dir_info[1]):
 
3882
                            current_path_info = current_dir_info[1][path_index]
 
3883
                            if current_path_info[2] == 'directory':
 
3884
                                if self.tree._directory_is_tree_reference(
 
3885
                                    current_path_info[0].decode('utf8')):
 
3886
                                    current_path_info = current_path_info[:2] + \
 
3887
                                        ('tree-reference',) + current_path_info[3:]
 
3888
                        else:
 
3889
                            current_path_info = None
 
3890
                        path_handled = False
 
3891
                    else:
 
3892
                        advance_path = True # reset the advance flagg.
 
3893
                if current_block is not None:
 
3894
                    block_index += 1
 
3895
                    if (block_index < len(self.state._dirblocks) and
 
3896
                        osutils.is_inside(current_root, self.state._dirblocks[block_index][0])):
 
3897
                        current_block = self.state._dirblocks[block_index]
 
3898
                    else:
 
3899
                        current_block = None
 
3900
                if current_dir_info is not None:
 
3901
                    try:
 
3902
                        current_dir_info = dir_iterator.next()
 
3903
                    except StopIteration:
 
3904
                        current_dir_info = None
 
3905
        for result in self._iter_specific_file_parents():
 
3906
            yield result
 
3907
 
 
3908
    def _iter_specific_file_parents(self):
 
3909
        """Iter over the specific file parents."""
 
3910
        while self.search_specific_file_parents:
 
3911
            # Process the parent directories for the paths we were iterating.
 
3912
            # Even in extremely large trees this should be modest, so currently
 
3913
            # no attempt is made to optimise.
 
3914
            path_utf8 = self.search_specific_file_parents.pop()
 
3915
            if osutils.is_inside_any(self.searched_specific_files, path_utf8):
 
3916
                # We've examined this path.
 
3917
                continue
 
3918
            if path_utf8 in self.searched_exact_paths:
 
3919
                # We've examined this path.
 
3920
                continue
 
3921
            path_entries = self.state._entries_for_path(path_utf8)
 
3922
            # We need either one or two entries. If the path in
 
3923
            # self.target_index has moved (so the entry in source_index is in
 
3924
            # 'ar') then we need to also look for the entry for this path in
 
3925
            # self.source_index, to output the appropriate delete-or-rename.
 
3926
            selected_entries = []
 
3927
            found_item = False
 
3928
            for candidate_entry in path_entries:
 
3929
                # Find entries present in target at this path:
 
3930
                if candidate_entry[1][self.target_index][0] not in 'ar':
 
3931
                    found_item = True
 
3932
                    selected_entries.append(candidate_entry)
 
3933
                # Find entries present in source at this path:
 
3934
                elif (self.source_index is not None and
 
3935
                    candidate_entry[1][self.source_index][0] not in 'ar'):
 
3936
                    found_item = True
 
3937
                    if candidate_entry[1][self.target_index][0] == 'a':
 
3938
                        # Deleted, emit it here.
 
3939
                        selected_entries.append(candidate_entry)
 
3940
                    else:
 
3941
                        # renamed, emit it when we process the directory it
 
3942
                        # ended up at.
 
3943
                        self.search_specific_file_parents.add(
 
3944
                            candidate_entry[1][self.target_index][1])
 
3945
            if not found_item:
 
3946
                raise AssertionError(
 
3947
                    "Missing entry for specific path parent %r, %r" % (
 
3948
                    path_utf8, path_entries))
 
3949
            path_info = self._path_info(path_utf8, path_utf8.decode('utf8'))
 
3950
            for entry in selected_entries:
 
3951
                if entry[0][2] in self.seen_ids:
 
3952
                    continue
 
3953
                result, changed = self._process_entry(entry, path_info)
 
3954
                if changed is None:
 
3955
                    raise AssertionError(
 
3956
                        "Got entry<->path mismatch for specific path "
 
3957
                        "%r entry %r path_info %r " % (
 
3958
                        path_utf8, entry, path_info))
 
3959
                # Only include changes - we're outside the users requested
 
3960
                # expansion.
 
3961
                if changed:
 
3962
                    self._gather_result_for_consistency(result)
 
3963
                    if (result[6][0] == 'directory' and
 
3964
                        result[6][1] != 'directory'):
 
3965
                        # This stopped being a directory, the old children have
 
3966
                        # to be included.
 
3967
                        if entry[1][self.source_index][0] == 'r':
 
3968
                            # renamed, take the source path
 
3969
                            entry_path_utf8 = entry[1][self.source_index][1]
 
3970
                        else:
 
3971
                            entry_path_utf8 = path_utf8
 
3972
                        initial_key = (entry_path_utf8, '', '')
 
3973
                        block_index, _ = self.state._find_block_index_from_key(
 
3974
                            initial_key)
 
3975
                        if block_index == 0:
 
3976
                            # The children of the root are in block index 1.
 
3977
                            block_index +=1
 
3978
                        current_block = None
 
3979
                        if block_index < len(self.state._dirblocks):
 
3980
                            current_block = self.state._dirblocks[block_index]
 
3981
                            if not osutils.is_inside(
 
3982
                                entry_path_utf8, current_block[0]):
 
3983
                                # No entries for this directory at all.
 
3984
                                current_block = None
 
3985
                        if current_block is not None:
 
3986
                            for entry in current_block[1]:
 
3987
                                if entry[1][self.source_index][0] in 'ar':
 
3988
                                    # Not in the source tree, so doesn't have to be
 
3989
                                    # included.
 
3990
                                    continue
 
3991
                                # Path of the entry itself.
 
3992
 
 
3993
                                self.search_specific_file_parents.add(
 
3994
                                    osutils.pathjoin(*entry[0][:2]))
 
3995
                if changed or self.include_unchanged:
 
3996
                    yield result
 
3997
            self.searched_exact_paths.add(path_utf8)
 
3998
 
 
3999
    def _path_info(self, utf8_path, unicode_path):
 
4000
        """Generate path_info for unicode_path.
 
4001
 
 
4002
        :return: None if unicode_path does not exist, or a path_info tuple.
 
4003
        """
 
4004
        abspath = self.tree.abspath(unicode_path)
 
4005
        try:
 
4006
            stat = os.lstat(abspath)
 
4007
        except OSError, e:
 
4008
            if e.errno == errno.ENOENT:
 
4009
                # the path does not exist.
 
4010
                return None
 
4011
            else:
 
4012
                raise
 
4013
        utf8_basename = utf8_path.rsplit('/', 1)[-1]
 
4014
        dir_info = (utf8_path, utf8_basename,
 
4015
            osutils.file_kind_from_stat_mode(stat.st_mode), stat,
 
4016
            abspath)
 
4017
        if dir_info[2] == 'directory':
 
4018
            if self.tree._directory_is_tree_reference(
 
4019
                unicode_path):
 
4020
                self.root_dir_info = self.root_dir_info[:2] + \
 
4021
                    ('tree-reference',) + self.root_dir_info[3:]
 
4022
        return dir_info
 
4023
 
 
4024
 
 
4025
# Try to load the compiled form if possible
 
4026
try:
 
4027
    from bzrlib._dirstate_helpers_pyx import (
 
4028
        _read_dirblocks,
 
4029
        bisect_dirblock,
 
4030
        _bisect_path_left,
 
4031
        _bisect_path_right,
 
4032
        cmp_by_dirs,
 
4033
        ProcessEntryC as _process_entry,
 
4034
        update_entry as update_entry,
 
4035
        )
 
4036
except ImportError, e:
 
4037
    osutils.failed_to_load_extension(e)
 
4038
    from bzrlib._dirstate_helpers_py import (
 
4039
        _read_dirblocks,
 
4040
        bisect_dirblock,
 
4041
        _bisect_path_left,
 
4042
        _bisect_path_right,
 
4043
        cmp_by_dirs,
 
4044
        )
 
4045
    # FIXME: It would be nice to be able to track moved lines so that the
 
4046
    # corresponding python code can be moved to the _dirstate_helpers_py
 
4047
    # module. I don't want to break the history for this important piece of
 
4048
    # code so I left the code here -- vila 20090622
 
4049
    update_entry = py_update_entry
 
4050
    _process_entry = ProcessEntryPython