/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/dirstate.py

  • Committer: Aaron Bentley
  • Date: 2007-02-24 15:31:00 UTC
  • mto: (2255.2.152 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: aaron.bentley@utoronto.ca-20070224153100-2wjayj3uwtges1u2
Fix update to set unique roots, and work with dirstate

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
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
 
16
 
 
17
"""DirState objects record the state of a directory and its bzr metadata.
 
18
 
 
19
Pseudo EBNF grammar for the state file. Fields are separated by NULLs, and
 
20
lines by NL. The field delimiters are ommitted in the grammar, line delimiters
 
21
are not - this is done for clarity of reading. All string data is in utf8.
 
22
 
 
23
MINIKIND = "f" | "d" | "l" | "a" | "r";
 
24
NL = "\n";
 
25
NULL = "\0";
 
26
WHOLE_NUMBER = {digit}, digit;
 
27
BOOLEAN = "y" | "n";
 
28
REVISION_ID = a non-empty utf8 string;
 
29
 
 
30
dirstate format = header line, full checksum, row count, parent details,
 
31
 ghost_details, entries;
 
32
header line = "#bazaar dirstate flat format 2", NL;
 
33
full checksum = "adler32: ", ["-"], WHOLE_NUMBER, NL;
 
34
row count = "num_entries: ", digit, NL;
 
35
parent_details = WHOLE NUMBER, {REVISION_ID}* NL;
 
36
ghost_details = WHOLE NUMBER, {REVISION_ID}*, NL;
 
37
entries = {entry};
 
38
entry = entry_key, current_entry_details, {parent_entry_details};
 
39
entry_key = dirname,  basename, fileid;
 
40
current_entry_details = common_entry_details, working_entry_details;
 
41
parent_entry_details = common_entry_details, history_entry_details;
 
42
common_entry_details = MINIKIND, fingerprint, size, executable
 
43
working_entry_details = packed_stat
 
44
history_entry_details = REVISION_ID;
 
45
executable = BOOLEAN;
 
46
size = WHOLE_NUMBER;
 
47
fingerprint = a nonempty utf8 sequence with meaning defined by minikind.
 
48
 
 
49
Given this definition, the following is useful to know:
 
50
entry (aka row) - all the data for a given key.
 
51
entry[0]: The key (dirname, basename, fileid)
 
52
entry[0][0]: dirname
 
53
entry[0][1]: basename
 
54
entry[0][2]: fileid
 
55
entry[1]: The tree(s) data for this path and id combination.
 
56
entry[1][0]: The current tree
 
57
entry[1][1]: The second tree
 
58
 
 
59
For an entry for a tree, we have (using tree 0 - current tree) to demonstrate:
 
60
entry[1][0][0]: minikind
 
61
entry[1][0][1]: fingerprint
 
62
entry[1][0][2]: size
 
63
entry[1][0][3]: executable
 
64
entry[1][0][4]: packed_stat
 
65
OR (for non tree-0)
 
66
entry[1][1][4]: revision_id
 
67
 
 
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 /
 
76
etc.
 
77
 
 
78
Kinds:
 
79
'r' is a relocated entry: This path is not present in this tree with this id,
 
80
    but the id can be found at another location. The fingerprint is used to
 
81
    point to the target location.
 
82
'a' is an absent entry: In that tree the id is not present at this path.
 
83
'd' is a directory entry: This path in this tree is a directory with the
 
84
    current file id. There is no fingerprint for directories.
 
85
'f' is a file entry: As for directory, but its a file. The fingerprint is a
 
86
    sha1 value.
 
87
'l' is a symlink entry: As for directory, but a symlink. The fingerprint is the
 
88
    link target.
 
89
 
 
90
 
 
91
--- Format 1 had the following different definition: ---
 
92
rows = dirname, NULL, basename, NULL, MINIKIND, NULL, fileid_utf8, NULL,
 
93
    WHOLE NUMBER (* size *), NULL, packed stat, NULL, sha1|symlink target, 
 
94
    {PARENT ROW}
 
95
PARENT ROW = NULL, revision_utf8, NULL, MINIKIND, NULL, dirname, NULL,
 
96
    basename, NULL, WHOLE NUMBER (* size *), NULL, "y" | "n", NULL,
 
97
    SHA1
 
98
 
 
99
PARENT ROW's are emitted for every parent that is not in the ghosts details
 
100
line. That is, if the parents are foo, bar, baz, and the ghosts are bar, then
 
101
each row will have a PARENT ROW for foo and baz, but not for bar.
 
102
 
 
103
 
 
104
In any tree, a kind of 'moved' indicates that the fingerprint field
 
105
(which we treat as opaque data specific to the 'kind' anyway) has the
 
106
details for the id of this row in that tree.
 
107
 
 
108
I'm strongly tempted to add a id->path index as well, but I think that
 
109
where we need id->path mapping; we also usually read the whole file, so
 
110
I'm going to skip that for the moment, as we have the ability to locate
 
111
via bisect any path in any tree, and if we lookup things by path, we can
 
112
accumulate a id->path mapping as we go, which will tend to match what we
 
113
looked for.
 
114
 
 
115
I plan to implement this asap, so please speak up now to alter/tweak the
 
116
design - and once we stabilise on this, I'll update the wiki page for
 
117
it.
 
118
 
 
119
The rationale for all this is that we want fast operations for the
 
120
common case (diff/status/commit/merge on all files) and extremely fast
 
121
operations for the less common but still occurs a lot status/diff/commit
 
122
on specific files). Operations on specific files involve a scan for all
 
123
the children of a path, *in every involved tree*, which the current
 
124
format did not accommodate. 
 
125
----
 
126
 
 
127
Design priorities:
 
128
 1) Fast end to end use for bzr's top 5 uses cases. (commmit/diff/status/merge/???)
 
129
 2) fall back current object model as needed.
 
130
 3) scale usably to the largest trees known today - say 50K entries. (mozilla
 
131
    is an example of this)
 
132
 
 
133
 
 
134
Locking:
 
135
 Eventually reuse dirstate objects across locks IFF the dirstate file has not
 
136
 been modified, but will require that we flush/ignore cached stat-hit data
 
137
 because we wont want to restat all files on disk just because a lock was
 
138
 acquired, yet we cannot trust the data after the previous lock was released.
 
139
 
 
140
Memory representation:
 
141
 vector of all directories, and vector of the childen ?
 
142
   i.e. 
 
143
     root_entrie = (direntry for root, [parent_direntries_for_root]), 
 
144
     dirblocks = [
 
145
     ('', ['data for achild', 'data for bchild', 'data for cchild'])
 
146
     ('dir', ['achild', 'cchild', 'echild'])
 
147
     ]
 
148
    - single bisect to find N subtrees from a path spec
 
149
    - in-order for serialisation - this is 'dirblock' grouping.
 
150
    - insertion of a file '/a' affects only the '/' child-vector, that is, to
 
151
      insert 10K elements from scratch does not generates O(N^2) memoves of a
 
152
      single vector, rather each individual, which tends to be limited to a 
 
153
      manageable number. Will scale badly on trees with 10K entries in a 
 
154
      single directory. compare with Inventory.InventoryDirectory which has
 
155
      a dictionary for the children. No bisect capability, can only probe for
 
156
      exact matches, or grab all elements and sorta.
 
157
    - Whats the risk of error here? Once we have the base format being processed
 
158
      we should have a net win regardless of optimality. So we are going to 
 
159
      go with what seems reasonably.
 
160
open questions:
 
161
 
 
162
maybe we should do a test profile of these core structure - 10K simulated searches/lookups/etc?
 
163
 
 
164
Objects for each row?
 
165
The lifetime of Dirstate objects is current per lock, but see above for
 
166
possible extensions. The lifetime of a row from a dirstate is expected to be
 
167
very short in the optimistic case: which we are optimising for. For instance,
 
168
subtree status will determine from analysis of the disk data what rows need to
 
169
be examined at all, and will be able to determine from a single row whether
 
170
that file has altered or not, so we are aiming to process tens of thousands of
 
171
entries each second within the dirstate context, before exposing anything to
 
172
the larger codebase. This suggests we want the time for a single file
 
173
comparison to be < 0.1 milliseconds. That would give us 10000 paths per second
 
174
processed, and to scale to 100 thousand we'll another order of magnitude to do
 
175
that. Now, as the lifetime for all unchanged entries is the time to parse, stat
 
176
the file on disk, and then immediately discard, the overhead of object creation
 
177
becomes a significant cost.
 
178
 
 
179
Figures: Creating a tuple from from 3 elements was profiled at 0.0625
 
180
microseconds, whereas creating a object which is subclassed from tuple was
 
181
0.500 microseconds, and creating an object with 3 elements and slots was 3
 
182
microseconds long. 0.1 milliseconds is 100 microseconds, and ideally we'll get
 
183
down to 10 microseconds for the total processing - having 33% of that be object
 
184
creation is a huge overhead. There is a potential cost in using tuples within
 
185
each row which is that the conditional code to do comparisons may be slower
 
186
than method invocation, but method invocation is known to be slow due to stack
 
187
frame creation, so avoiding methods in these tight inner loops in unfortunately
 
188
desirable. We can consider a pyrex version of this with objects in future if
 
189
desired.
 
190
 
 
191
"""
 
192
 
 
193
 
 
194
import base64
 
195
import bisect
 
196
import cStringIO
 
197
import os
 
198
import sha
 
199
import struct
 
200
import zlib
 
201
 
 
202
from bzrlib import (
 
203
    errors,
 
204
    lock,
 
205
    trace,
 
206
    )
 
207
import bzrlib.inventory
 
208
from bzrlib import osutils
 
209
from bzrlib.osutils import (
 
210
    pathjoin,
 
211
    sha_file,
 
212
    sha_string,
 
213
    walkdirs,
 
214
    )
 
215
 
 
216
 
 
217
class DirState(object):
 
218
    """Record directory and metadata state for fast access.
 
219
 
 
220
    A dirstate is a specialised data structure for managing local working
 
221
    tree state information. Its not yet well defined whether it is platform
 
222
    specific, and if it is how we detect/parameterise that.
 
223
    """
 
224
 
 
225
    _kind_to_minikind = {'absent':'a', 'file':'f', 'directory':'d', 'relocated':'r', 'symlink':'l'}
 
226
    _minikind_to_kind = {'a':'absent', 'f':'file', 'd':'directory', 'l':'symlink', 'r':'relocated'}
 
227
    _to_yesno = {True:'y', False: 'n'} # TODO profile the performance gain
 
228
     # of using int conversion rather than a dict here. AND BLAME ANDREW IF
 
229
     # it is faster.
 
230
 
 
231
    # TODO: jam 20070221 Make sure we handle when there are duplicated records
 
232
    #       (like when we remove + add the same path, or we have a rename)
 
233
    # TODO: jam 20070221 Figure out what to do if we have a record that exceeds
 
234
    #       the BISECT_PAGE_SIZE.
 
235
    BISECT_PAGE_SIZE = 4096
 
236
 
 
237
    NOT_IN_MEMORY = 0
 
238
    IN_MEMORY_UNMODIFIED = 1
 
239
    IN_MEMORY_MODIFIED = 2
 
240
 
 
241
    # A pack_stat (the x's) that is just noise and will never match the output
 
242
    # of base64 encode.
 
243
    NULLSTAT = 'x' * 32
 
244
    NULL_PARENT_DETAILS = ('a', '', 0, False, '')
 
245
 
 
246
    def __init__(self, path):
 
247
        """Create a  DirState object.
 
248
 
 
249
        Attributes of note:
 
250
 
 
251
        :attr _root_entrie: The root row of the directory/file information,
 
252
            - contains the path to / - '', ''
 
253
            - kind of 'directory',
 
254
            - the file id of the root in utf8
 
255
            - size of 0
 
256
            - a packed state
 
257
            - and no sha information.
 
258
        :param path: The path at which the dirstate file on disk should live.
 
259
        """
 
260
        # _header_state and _dirblock_state represent the current state
 
261
        # of the dirstate metadata and the per-row data respectiely.
 
262
        # NOT_IN_MEMORY indicates that no data is in memory
 
263
        # IN_MEMORY_UNMODIFIED indicates that what we have in memory
 
264
        #   is the same as is on disk
 
265
        # IN_MEMORY_MODIFIED indicates that we have a modified version
 
266
        #   of what is on disk. 
 
267
        # In future we will add more granularity, for instance _dirblock_state
 
268
        # will probably support partially-in-memory as a separate variable,
 
269
        # allowing for partially-in-memory unmodified and partially-in-memory
 
270
        # modified states.
 
271
        self._header_state = DirState.NOT_IN_MEMORY
 
272
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
273
        self._dirblocks = []
 
274
        self._ghosts = []
 
275
        self._parents = []
 
276
        self._state_file = None
 
277
        self._filename = path
 
278
        self._lock_token = None
 
279
 
 
280
    def add(self, path, file_id, kind, stat, link_or_sha1):
 
281
        """Add a path to be tracked.
 
282
 
 
283
        :param path: The path within the dirstate - '' is the root, 'foo' is the
 
284
            path foo within the root, 'foo/bar' is the path bar within foo 
 
285
            within the root.
 
286
        :param file_id: The file id of the path being added.
 
287
        :param kind: The kind of the path.
 
288
        :param stat: The output of os.lstate for the path.
 
289
        :param link_or_sha1: The sha value of the file, or the target of a
 
290
            symlink. '' for directories.
 
291
        """
 
292
        # adding a file:
 
293
        # find the block its in. 
 
294
        # find the location in the block.
 
295
        # check its not there
 
296
        # add it.
 
297
        #------- copied from bzrlib.inventory.make_entry
 
298
        # --- normalized_filename wants a unicode basename only, so get one.
 
299
        dirname, basename = os.path.split(path)
 
300
        # we dont import normalized_filename directly because we want to be
 
301
        # able to change the implementation at runtime for tests.
 
302
        norm_name, can_access = osutils.normalized_filename(basename)
 
303
        if norm_name != basename:
 
304
            if can_access:
 
305
                basename = norm_name
 
306
            else:
 
307
                raise errors.InvalidNormalization(path)
 
308
        # now that we've normalised, we need the correct utf8 path and 
 
309
        # dirname and basename elements. This single encode and split should be
 
310
        # faster than three separate encodes.
 
311
        utf8path = (dirname + '/' + basename).strip('/').encode('utf8')
 
312
        dirname, basename = os.path.split(utf8path)
 
313
        assert file_id.__class__ == str, \
 
314
            "must be a utf8 file_id not %s" % (type(file_id))
 
315
        entry_key = (dirname, basename, file_id)
 
316
        self._read_dirblocks_if_needed()
 
317
        block_index, present = self._find_block_index_from_key(entry_key)
 
318
        if not present:
 
319
            # TODO: This test is not complete - an empty directory, or a
 
320
            # directory for a parent tree will fool it.
 
321
            # some parent path has not been added - its an error to add this
 
322
            # child
 
323
            raise errors.NotVersionedError(path, str(self))
 
324
        block = self._dirblocks[block_index][1]
 
325
        if stat is None:
 
326
            size = 0
 
327
            packed_stat = DirState.NULLSTAT
 
328
        else:
 
329
            size = stat.st_size
 
330
            packed_stat = pack_stat(stat)
 
331
        parent_info = self._empty_parent_info()
 
332
        minikind = DirState._kind_to_minikind[kind]
 
333
        if kind == 'file':
 
334
            entry_data = entry_key, [
 
335
                (minikind, link_or_sha1, size, False, packed_stat),
 
336
                ] + parent_info
 
337
        elif kind == 'directory':
 
338
            entry_data = entry_key, [
 
339
                (minikind, '', 0, False, packed_stat),
 
340
                ] + parent_info
 
341
        elif kind == 'symlink':
 
342
            entry_data = entry_key, [
 
343
                (minikind, link_or_sha1, size, False, packed_stat),
 
344
                ] + parent_info
 
345
        else:
 
346
            raise errors.BzrError('unknown kind %r' % kind)
 
347
        entry_index, present = self._find_entry_index(entry_key, block)
 
348
        assert not present, "basename %r already added" % basename
 
349
        block.insert(entry_index, entry_data)
 
350
 
 
351
        if kind == 'directory':
 
352
           # insert a new dirblock
 
353
           self._ensure_block(block_index, entry_index, utf8path)
 
354
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
355
 
 
356
    def _empty_parent_info(self):
 
357
        return [DirState.NULL_PARENT_DETAILS] * (len(self._parents) -
 
358
                                                    len(self._ghosts))
 
359
 
 
360
    def _ensure_block(self, parent_block_index, parent_row_index, dirname):
 
361
        """Enssure a block for dirname exists.
 
362
        
 
363
        This function exists to let callers which know that there is a
 
364
        directory dirname ensure that the block for it exists. This block can
 
365
        fail to exist because of demand loading, or because a directory had no
 
366
        children. In either case it is not an error. It is however an error to
 
367
        call this if there is no parent entry for the directory, and thus the
 
368
        function requires the coordinates of such an entry to be provided.
 
369
 
 
370
        The root row is special cased and can be indicated with a parent block
 
371
        and row index of -1
 
372
 
 
373
        :param parent_block_index: The index of the block in which dirname's row
 
374
            exists.
 
375
        :param parent_row_index: The index in the parent block where the row
 
376
            exists.
 
377
        :param dirname: The utf8 dirname to ensure there is a block for.
 
378
        :return: The index for the block.
 
379
        """
 
380
        assert dirname != ''
 
381
        # the basename of the directory must be the end of its full name.
 
382
        if not (parent_block_index == -1 and
 
383
            parent_block_index == -1 and dirname == ''):
 
384
            assert dirname.endswith(
 
385
                self._dirblocks[parent_block_index][1][parent_row_index][0][1])
 
386
        block_index, present = self._find_block_index_from_key((dirname, '', ''))
 
387
        if not present:
 
388
            ## In future, when doing partial parsing, this should load and 
 
389
            # populate the entire block.
 
390
            self._dirblocks.insert(block_index, (dirname, []))
 
391
        return block_index
 
392
 
 
393
    def _entries_to_current_state(self, new_entries):
 
394
        """Load new_entries into self.dirblocks.
 
395
 
 
396
        Process new_entries into the current state object, making them the active
 
397
        state.
 
398
 
 
399
        :param new_entries: A sorted list of entries. This function does not sort
 
400
            to prevent unneeded overhead when callers have a sorted list already.
 
401
        :return: Nothing.
 
402
        """
 
403
        assert new_entries[0][0][0:2] == ('', ''), \
 
404
            "Missing root row %r" % new_entries[0][0]
 
405
        # The two blocks here are deliberate: the root block and the 
 
406
        # contents-of-root block.
 
407
        self._dirblocks = [('', []), ('', [])]
 
408
        current_block = self._dirblocks[0][1]
 
409
        current_dirname = ''
 
410
        root_key = ('', '')
 
411
        append_entry = current_block.append
 
412
        for entry in new_entries:
 
413
            if entry[0][0] != current_dirname:
 
414
                # new block - different dirname
 
415
                current_block = []
 
416
                current_dirname = entry[0][0]
 
417
                self._dirblocks.append((current_dirname, current_block))
 
418
                append_entry = current_block.append
 
419
            # append the entry to the current block
 
420
            append_entry(entry)
 
421
        self._split_root_dirblock_into_contents()
 
422
 
 
423
    def _split_root_dirblock_into_contents(self):
 
424
        """Split the root dirblocks into root and contents-of-root.
 
425
 
 
426
        After parsing by path, we end up with root entries and contents-of-root
 
427
        entries in the same block. This loop splits them out again.
 
428
        """
 
429
        # The above loop leaves the "root block" entries mixed with the
 
430
        # "contents-of-root block". But we don't want an if check on
 
431
        # all entries, so instead we just fix it up here.
 
432
        assert self._dirblocks[1] == ('', [])
 
433
        root_block = []
 
434
        contents_of_root_block = []
 
435
        for entry in self._dirblocks[0][1]:
 
436
            if not entry[0][1]: # This is a root entry
 
437
                root_block.append(entry)
 
438
            else:
 
439
                contents_of_root_block.append(entry)
 
440
        self._dirblocks[0] = ('', root_block)
 
441
        self._dirblocks[1] = ('', contents_of_root_block)
 
442
 
 
443
    def _entry_to_line(self, entry):
 
444
        """Serialize entry to a NULL delimited line ready for _get_output_lines.
 
445
        
 
446
        :param entry: An entry_tuple as defined in the module docstring.
 
447
        """
 
448
        entire_entry = list(entry[0])
 
449
        for tree_number, tree_data in enumerate(entry[1]):
 
450
            # (minikind, fingerprint, size, executable, tree_specific_string)
 
451
            entire_entry.extend(tree_data)
 
452
            # 3 for the key, 5 for the fields per tree.
 
453
            tree_offset = 3 + tree_number * 5
 
454
            # minikind
 
455
            entire_entry[tree_offset + 0] = tree_data[0]
 
456
            # size
 
457
            entire_entry[tree_offset + 2] = str(tree_data[2])
 
458
            # executable
 
459
            entire_entry[tree_offset + 3] = DirState._to_yesno[tree_data[3]]
 
460
        return '\0'.join(entire_entry)
 
461
 
 
462
    def _fields_per_row(self):
 
463
        """How many null separated fields should be in each entry row.
 
464
 
 
465
        Each line now has an extra '\n' field which is not used
 
466
        so we just skip over it
 
467
        entry size:
 
468
            3 fields for the key
 
469
            + number of fields per tree_data (5) * tree count
 
470
            + newline
 
471
         """
 
472
        tree_count = 1 + self._num_present_parents()
 
473
        return 3 + 5 * tree_count + 1
 
474
 
 
475
    def _find_block(self, key, add_if_missing=False):
 
476
        """Return the block that key should be present in.
 
477
 
 
478
        :param key: A dirstate entry key.
 
479
        :return: The block tuple.
 
480
        """
 
481
        block_index, present = self._find_block_index_from_key(key)
 
482
        if not present:
 
483
            if not add_if_missing:
 
484
                # check to see if key is versioned itself - we might want to
 
485
                # add it anyway, because dirs with no entries dont get a
 
486
                # dirblock at parse time.
 
487
                # This is an uncommon branch to take: most dirs have children,
 
488
                # and most code works with versioned paths.
 
489
                parent_base, parent_name = os.path.split(key[0])
 
490
                if not self._get_block_entry_index(parent_base, parent_name, 0)[3]:
 
491
                    # some parent path has not been added - its an error to add
 
492
                    # this child
 
493
                    raise errors.NotVersionedError(key[0:2], str(self))
 
494
            self._dirblocks.insert(block_index, (key[0], []))
 
495
        return self._dirblocks[block_index]
 
496
 
 
497
    def _find_block_index_from_key(self, key):
 
498
        """Find the dirblock index for a key.
 
499
 
 
500
        :return: The block index, True if the block for the key is present.
 
501
        """
 
502
        if key[0:2] == ('', ''):
 
503
            return 0, True
 
504
        block_index = bisect.bisect_left(self._dirblocks, (key[0], []), 1)
 
505
        # _right returns one-past-where-key is so we have to subtract
 
506
        # one to use it. we use _right here because there are two
 
507
        # '' blocks - the root, and the contents of root
 
508
        # we always have a minimum of 2 in self._dirblocks: root and
 
509
        # root-contents, and for '', we get 2 back, so this is 
 
510
        # simple and correct:
 
511
        present = (block_index < len(self._dirblocks) and
 
512
            self._dirblocks[block_index][0] == key[0])
 
513
        return block_index, present
 
514
 
 
515
    def _find_entry_index(self, key, block):
 
516
        """Find the entry index for a key in a block.
 
517
 
 
518
        :return: The entry index, True if the entry for the key is present.
 
519
        """
 
520
        entry_index = bisect.bisect_left(block, (key, []))
 
521
        present = (entry_index < len(block) and
 
522
            block[entry_index][0] == key)
 
523
        return entry_index, present
 
524
 
 
525
    @staticmethod
 
526
    def from_tree(tree, dir_state_filename):
 
527
        """Create a dirstate from a bzr Tree.
 
528
 
 
529
        :param tree: The tree which should provide parent information and
 
530
            inventory ids.
 
531
        :return: a DirState object which is currently locked for writing.
 
532
            (it was locked by DirState.initialize)
 
533
        """
 
534
        result = DirState.initialize(dir_state_filename)
 
535
        try:
 
536
            tree.lock_read()
 
537
            try:
 
538
                parent_ids = tree.get_parent_ids()
 
539
                num_parents = len(parent_ids)
 
540
                parent_trees = []
 
541
                for parent_id in parent_ids:
 
542
                    parent_tree = tree.branch.repository.revision_tree(parent_id)
 
543
                    parent_trees.append((parent_id, parent_tree))
 
544
                    parent_tree.lock_read()
 
545
                result.set_parent_trees(parent_trees, [])
 
546
                result.set_state_from_inventory(tree.inventory)
 
547
            finally:
 
548
                for revid, parent_tree in parent_trees:
 
549
                    parent_tree.unlock()
 
550
                tree.unlock()
 
551
        except:
 
552
            # The caller won't have a chance to unlock this, so make sure we
 
553
            # cleanup ourselves
 
554
            result.unlock()
 
555
            raise
 
556
        return result
 
557
 
 
558
    def get_ghosts(self):
 
559
        """Return a list of the parent tree revision ids that are ghosts."""
 
560
        self._read_header_if_needed()
 
561
        return self._ghosts
 
562
 
 
563
    def get_lines(self):
 
564
        """Serialise the entire dirstate to a sequence of lines."""
 
565
        if (self._header_state == DirState.IN_MEMORY_UNMODIFIED and
 
566
            self._dirblock_state == DirState.IN_MEMORY_UNMODIFIED):
 
567
            # read whats on disk.
 
568
            self._state_file.seek(0)
 
569
            return self._state_file.readlines()
 
570
        lines = []
 
571
        lines.append(self._get_parents_line(self.get_parent_ids()))
 
572
        lines.append(self._get_ghosts_line(self._ghosts))
 
573
        # append the root line which is special cased
 
574
        lines.extend(map(self._entry_to_line, self._iter_entries()))
 
575
        return self._get_output_lines(lines)
 
576
 
 
577
    def _get_ghosts_line(self, ghost_ids):
 
578
        """Create a line for the state file for ghost information."""
 
579
        return '\0'.join([str(len(ghost_ids))] + ghost_ids)
 
580
 
 
581
    def _get_parents_line(self, parent_ids):
 
582
        """Create a line for the state file for parents information."""
 
583
        return '\0'.join([str(len(parent_ids))] + parent_ids)
 
584
 
 
585
    def _get_fields_to_entry(self):
 
586
        """Get a function which converts entry fields into a entry record.
 
587
 
 
588
        This handles size and executable, as well as parent records.
 
589
 
 
590
        :return: A function which takes a list of fields, and returns an
 
591
            appropriate record for storing in memory.
 
592
        """
 
593
        # This is intentionally unrolled for performance
 
594
        num_present_parents = self._num_present_parents()
 
595
        if num_present_parents == 0:
 
596
            def fields_to_entry_0_parents(fields, _int=int):
 
597
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
598
                return (path_name_file_id_key, [
 
599
                    ( # Current tree
 
600
                        fields[3],                # minikind
 
601
                        fields[4],                # fingerprint
 
602
                        _int(fields[5]),          # size
 
603
                        fields[6] == 'y',         # executable
 
604
                        fields[7],                # packed_stat or revision_id
 
605
                    )])
 
606
            return fields_to_entry_0_parents
 
607
        elif num_present_parents == 1:
 
608
            def fields_to_entry_1_parent(fields, _int=int):
 
609
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
610
                return (path_name_file_id_key, [
 
611
                    ( # Current tree
 
612
                        fields[3],                # minikind
 
613
                        fields[4],                # fingerprint
 
614
                        _int(fields[5]),          # size
 
615
                        fields[6] == 'y',         # executable
 
616
                        fields[7],                # packed_stat or revision_id
 
617
                    ),
 
618
                    ( # Parent 1
 
619
                        fields[8],                # minikind
 
620
                        fields[9],                # fingerprint
 
621
                        _int(fields[10]),         # size
 
622
                        fields[11] == 'y',        # executable
 
623
                        fields[12],               # packed_stat or revision_id
 
624
                    ),
 
625
                    ])
 
626
            return fields_to_entry_1_parent
 
627
        elif num_present_parents == 2:
 
628
            def fields_to_entry_2_parents(fields, _int=int):
 
629
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
630
                return (path_name_file_id_key, [
 
631
                    ( # Current tree
 
632
                        fields[3],                # minikind
 
633
                        fields[4],                # fingerprint
 
634
                        _int(fields[5]),          # size
 
635
                        fields[6] == 'y',         # executable
 
636
                        fields[7],                # packed_stat or revision_id
 
637
                    ),
 
638
                    ( # Parent 1
 
639
                        fields[8],                # minikind
 
640
                        fields[9],                # fingerprint
 
641
                        _int(fields[10]),         # size
 
642
                        fields[11] == 'y',        # executable
 
643
                        fields[12],               # packed_stat or revision_id
 
644
                    ),
 
645
                    ( # Parent 2
 
646
                        fields[13],               # minikind
 
647
                        fields[14],               # fingerprint
 
648
                        _int(fields[15]),         # size
 
649
                        fields[16] == 'y',        # executable
 
650
                        fields[17],               # packed_stat or revision_id
 
651
                    ),
 
652
                    ])
 
653
            return fields_to_entry_2_parents
 
654
        else:
 
655
            def fields_to_entry_n_parents(fields, _int=int):
 
656
                path_name_file_id_key = (fields[0], fields[1], fields[2])
 
657
                trees = [(fields[cur],                # minikind
 
658
                          fields[cur+1],              # fingerprint
 
659
                          _int(fields[cur+2]),        # size
 
660
                          fields[cur+3] == 'y',       # executable
 
661
                          fields[cur+4],              # stat or revision_id
 
662
                         ) for cur in xrange(3, len(fields)-1, 5)]
 
663
                return path_name_file_id_key, trees
 
664
            return fields_to_entry_n_parents
 
665
 
 
666
    def get_parent_ids(self):
 
667
        """Return a list of the parent tree ids for the directory state."""
 
668
        self._read_header_if_needed()
 
669
        return list(self._parents)
 
670
 
 
671
    def _get_block_entry_index(self, dirname, basename, tree_index):
 
672
        """Get the coordinates for a path in the state structure.
 
673
 
 
674
        :param dirname: The utf8 dirname to lookup.
 
675
        :param basename: The utf8 basename to lookup.
 
676
        :param tree_index: The index of the tree for which this lookup should
 
677
            be attempted.
 
678
        :return: A tuple describing where the path is located, or should be
 
679
            inserted. The tuple contains four fields: the block index, the row
 
680
            index, anda two booleans are True when the directory is present, and
 
681
            when the entire path is present.  There is no guarantee that either
 
682
            coordinate is currently reachable unless the found field for it is
 
683
            True. For instance, a directory not present in the searched tree
 
684
            may be returned with a value one greater than the current highest
 
685
            block offset. The directory present field will always be True when
 
686
            the path present field is True. The directory present field does
 
687
            NOT indicate that the directory is present in the searched tree,
 
688
            rather it indicates that there are at least some files in some
 
689
            tree present there.
 
690
        """
 
691
        self._read_dirblocks_if_needed()
 
692
        key = dirname, basename, ''
 
693
        block_index, present = self._find_block_index_from_key(key)
 
694
        if not present:
 
695
            # no such directory - return the dir index and 0 for the row.
 
696
            return block_index, 0, False, False
 
697
        block = self._dirblocks[block_index][1] # access the entries only
 
698
        entry_index, present = self._find_entry_index(key, block)
 
699
        # linear search through present entries at this path to find the one
 
700
        # requested.
 
701
        while entry_index < len(block) and block[entry_index][0][1] == basename:
 
702
            if block[entry_index][1][tree_index][0] not in \
 
703
                       ('a', 'r'): # absent, relocated
 
704
                return block_index, entry_index, True, True
 
705
            entry_index += 1
 
706
        return block_index, entry_index, True, False
 
707
 
 
708
    def _get_entry(self, tree_index, fileid_utf8=None, path_utf8=None):
 
709
        """Get the dirstate entry for path in tree tree_index
 
710
 
 
711
        If either file_id or path is supplied, it is used as the key to lookup.
 
712
        If both are supplied, the fastest lookup is used, and an error is
 
713
        raised if they do not both point at the same row.
 
714
        
 
715
        :param tree_index: The index of the tree we wish to locate this path
 
716
            in. If the path is present in that tree, the entry containing its
 
717
            details is returned, otherwise (None, None) is returned
 
718
        :param fileid_utf8: A utf8 file_id to look up.
 
719
        :param path_utf8: An utf8 path to be looked up.
 
720
        :return: The dirstate entry tuple for path, or (None, None)
 
721
        """
 
722
        self._read_dirblocks_if_needed()
 
723
        if path_utf8 is not None:
 
724
            assert path_utf8.__class__ == str, 'path_utf8 is not a str: %s %s' % (type(path_utf8), path_utf8)
 
725
            # path lookups are faster
 
726
            dirname, basename = os.path.split(path_utf8)
 
727
            block_index, entry_index, dir_present, file_present = \
 
728
                self._get_block_entry_index(dirname, basename, tree_index)
 
729
            if not file_present:
 
730
                return None, None
 
731
            entry = self._dirblocks[block_index][1][entry_index]
 
732
            assert entry[0][2] and entry[1][tree_index][0] not in ('a', 'r'), 'unversioned entry?!?!'
 
733
            if fileid_utf8:
 
734
                if entry[0][2] != fileid_utf8:
 
735
                    raise BzrError('integrity error ? : mismatching tree_index, file_id and path')
 
736
            return entry
 
737
        else:
 
738
            for entry in self._iter_entries():
 
739
                if entry[0][2] == fileid_utf8:
 
740
                    if entry[1][tree_index][0] == 'r': # relocated
 
741
                        # look up the real location directly by path
 
742
                        return self._get_entry(tree_index,
 
743
                            fileid_utf8=fileid_utf8,
 
744
                            path_utf8=entry[1][tree_index][1])
 
745
                    if entry[1][tree_index][0] == 'a': # absent
 
746
                        # not in the tree at all.
 
747
                        return None, None
 
748
                    return entry
 
749
            return None, None
 
750
 
 
751
    @staticmethod
 
752
    def initialize(path):
 
753
        """Create a new dirstate on path.
 
754
 
 
755
        The new dirstate will be an empty tree - that is it has no parents,
 
756
        and only a root node - which has id ROOT_ID.
 
757
 
 
758
        The object will be write locked when returned to the caller,
 
759
        unless there was an exception in the writing, in which case it
 
760
        will be unlocked.
 
761
 
 
762
        :param path: The name of the file for the dirstate.
 
763
        :return: A DirState object.
 
764
        """
 
765
        # This constructs a new DirState object on a path, sets the _state_file
 
766
        # to a new empty file for that path. It then calls _set_data() with our
 
767
        # stock empty dirstate information - a root with ROOT_ID, no children,
 
768
        # and no parents. Finally it calls save() to ensure that this data will
 
769
        # persist.
 
770
        result = DirState(path)
 
771
        # root dir and root dir contents with no children.
 
772
        empty_tree_dirblocks = [('', []), ('', [])]
 
773
        # a new root directory, with a NULLSTAT.
 
774
        empty_tree_dirblocks[0][1].append(
 
775
            (('', '', bzrlib.inventory.ROOT_ID), [
 
776
                ('d', '', 0, False, DirState.NULLSTAT),
 
777
            ]))
 
778
        result.lock_write()
 
779
        try:
 
780
            result._set_data([], empty_tree_dirblocks)
 
781
            result.save()
 
782
        except:
 
783
            result.unlock()
 
784
            raise
 
785
        return result
 
786
 
 
787
    def _inv_entry_to_details(self, inv_entry):
 
788
        """Convert an inventory entry (from a revision tree) to state details.
 
789
 
 
790
        :param inv_entry: An inventory entry whose sha1 and link targets can be
 
791
            relied upon, and which has a revision set.
 
792
        :return: A details tuple - the details for a single tree at a path +
 
793
            id.
 
794
        """
 
795
        kind = inv_entry.kind
 
796
        minikind = DirState._kind_to_minikind[kind]
 
797
        tree_data = inv_entry.revision
 
798
        assert len(tree_data) > 0, 'empty revision for the inv_entry.'
 
799
        if kind == 'directory':
 
800
            fingerprint = ''
 
801
            size = 0
 
802
            executable = False
 
803
        elif kind == 'symlink':
 
804
            fingerprint = inv_entry.symlink_target or ''
 
805
            size = 0
 
806
            executable = False
 
807
        elif kind == 'file':
 
808
            fingerprint = inv_entry.text_sha1 or ''
 
809
            size = inv_entry.text_size or 0
 
810
            executable = inv_entry.executable
 
811
        else:
 
812
            raise Exception
 
813
        return (minikind, fingerprint, size, executable, tree_data)
 
814
 
 
815
    def _iter_entries(self):
 
816
        """Iterate over all the entries in the dirstate.
 
817
 
 
818
        Each yelt item is an entry in the standard format described in the
 
819
        docstring of bzrlib.dirstate.
 
820
        """
 
821
        self._read_dirblocks_if_needed()
 
822
        for directory in self._dirblocks:
 
823
            for entry in directory[1]:
 
824
                yield entry
 
825
 
 
826
    def _get_id_index(self):
 
827
        """Get an id index of self._dirblocks."""
 
828
        id_index = {}
 
829
        for key, tree_details in self._iter_entries():
 
830
            id_index.setdefault(key[2], set()).add(key)
 
831
        return id_index
 
832
 
 
833
    def _get_output_lines(self, lines):
 
834
        """format lines for final output.
 
835
 
 
836
        :param lines: A sequece of lines containing the parents list and the
 
837
            path lines.
 
838
        """
 
839
        output_lines = ['#bazaar dirstate flat format 2\n']
 
840
        lines.append('') # a final newline
 
841
        inventory_text = '\0\n\0'.join(lines)
 
842
        output_lines.append('adler32: %s\n' % (zlib.adler32(inventory_text),))
 
843
        # -3, 1 for num parents, 1 for ghosts, 1 for final newline
 
844
        num_entries = len(lines)-3
 
845
        output_lines.append('num_entries: %s\n' % (num_entries,))
 
846
        output_lines.append(inventory_text)
 
847
        return output_lines
 
848
 
 
849
    def _make_deleted_row(self, fileid_utf8, parents):
 
850
        """Return a deleted for for fileid_utf8."""
 
851
        return ('/', 'RECYCLED.BIN', 'file', fileid_utf8, 0, DirState.NULLSTAT,
 
852
            ''), parents
 
853
 
 
854
    def _num_present_parents(self):
 
855
        """The number of parent entries in each record row."""
 
856
        return len(self._parents) - len(self._ghosts)
 
857
 
 
858
    @staticmethod
 
859
    def on_file(path):
 
860
        """Construct a DirState on the file at path path.
 
861
 
 
862
        :return: An unlocked DirState object, associated with the given path.
 
863
        """
 
864
        result = DirState(path)
 
865
        return result
 
866
 
 
867
    def _read_dirblocks_if_needed(self):
 
868
        """Read in all the dirblocks from the file if they are not in memory.
 
869
        
 
870
        This populates self._dirblocks, and sets self._dirblock_state to
 
871
        IN_MEMORY_UNMODIFIED. It is not currently ready for incremental block
 
872
        loading.
 
873
        """
 
874
        self._read_header_if_needed()
 
875
        if self._dirblock_state == DirState.NOT_IN_MEMORY:
 
876
            # the _state_file pointer will be positioned at the start of the 
 
877
            # dirblocks.
 
878
            text = self._state_file.read()
 
879
            # TODO: check the adler checksums. adler_measured = zlib.adler32(text)
 
880
 
 
881
            fields = text.split('\0')
 
882
            # Remove the last blank entry
 
883
            trailing = fields.pop()
 
884
            assert trailing == ''
 
885
            # consider turning fields into a tuple.
 
886
 
 
887
            # skip the first field which is the trailing null from the header.
 
888
            cur = 1
 
889
            # Each line now has an extra '\n' field which is not used
 
890
            # so we just skip over it
 
891
            # entry size:
 
892
            #  3 fields for the key
 
893
            #  + number of fields per tree_data (5) * tree count
 
894
            #  + newline
 
895
            num_present_parents = self._num_present_parents()
 
896
            tree_count = 1 + num_present_parents
 
897
            entry_size = self._fields_per_row()
 
898
            expected_field_count = entry_size * self._num_entries
 
899
            if len(fields) - cur > expected_field_count:
 
900
                fields = fields[:expected_field_count + cur]
 
901
                trace.mutter('Unexpectedly long dirstate field count!')
 
902
                print "XXX: incorrectly truncated dirstate file bug triggered."
 
903
            field_count = len(fields)
 
904
            # this checks our adjustment, and also catches file too short.
 
905
            assert field_count - cur == expected_field_count, \
 
906
                'field count incorrect %s != %s, entry_size=%s, '\
 
907
                'num_entries=%s fields=%r' % (
 
908
                    field_count - cur, expected_field_count, entry_size,
 
909
                    self._num_entries, fields)
 
910
 
 
911
            if num_present_parents == 1:
 
912
                # Bind external functions to local names
 
913
                _int = int
 
914
                # We access all fields in order, so we can just iterate over
 
915
                # them. Grab an straight iterator over the fields. (We use an
 
916
                # iterator because we don't want to do a lot of additions, nor
 
917
                # do we want to do a lot of slicing)
 
918
                next = iter(fields).next
 
919
                # Move the iterator to the current position
 
920
                for x in xrange(cur):
 
921
                    next()
 
922
                # The two blocks here are deliberate: the root block and the
 
923
                # contents-of-root block.
 
924
                self._dirblocks = [('', []), ('', [])]
 
925
                current_block = self._dirblocks[0][1]
 
926
                current_dirname = ''
 
927
                append_entry = current_block.append
 
928
                for count in xrange(self._num_entries):
 
929
                    dirname = next()
 
930
                    name = next()
 
931
                    file_id = next()
 
932
                    if dirname != current_dirname:
 
933
                        # new block - different dirname
 
934
                        current_block = []
 
935
                        current_dirname = dirname
 
936
                        self._dirblocks.append((current_dirname, current_block))
 
937
                        append_entry = current_block.append
 
938
                    # we know current_dirname == dirname, so re-use it to avoid
 
939
                    # creating new strings
 
940
                    entry = ((current_dirname, name, file_id),
 
941
                             [(# Current Tree
 
942
                                 next(),                # minikind
 
943
                                 next(),                # fingerprint
 
944
                                 _int(next()),          # size
 
945
                                 next() == 'y',         # executable
 
946
                                 next(),                # packed_stat or revision_id
 
947
                             ),
 
948
                             ( # Parent 1
 
949
                                 next(),                # minikind
 
950
                                 next(),                # fingerprint
 
951
                                 _int(next()),          # size
 
952
                                 next() == 'y',         # executable
 
953
                                 next(),                # packed_stat or revision_id
 
954
                             ),
 
955
                             ])
 
956
                    trailing = next()
 
957
                    assert trailing == '\n'
 
958
                    # append the entry to the current block
 
959
                    append_entry(entry)
 
960
                self._split_root_dirblock_into_contents()
 
961
            else:
 
962
                fields_to_entry = self._get_fields_to_entry()
 
963
                entries = [fields_to_entry(fields[pos:pos+entry_size])
 
964
                           for pos in xrange(cur, field_count, entry_size)]
 
965
                self._entries_to_current_state(entries)
 
966
            self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
967
 
 
968
    def _read_header(self):
 
969
        """This reads in the metadata header, and the parent ids.
 
970
 
 
971
        After reading in, the file should be positioned at the null
 
972
        just before the start of the first record in the file.
 
973
 
 
974
        :return: (expected adler checksum, number of entries, parent list)
 
975
        """
 
976
        self._read_prelude()
 
977
        parent_line = self._state_file.readline()
 
978
        info = parent_line.split('\0')
 
979
        num_parents = int(info[0])
 
980
        assert num_parents == len(info)-2, 'incorrect parent info line'
 
981
        self._parents = info[1:-1]
 
982
 
 
983
        ghost_line = self._state_file.readline()
 
984
        info = ghost_line.split('\0')
 
985
        num_ghosts = int(info[1])
 
986
        assert num_ghosts == len(info)-3, 'incorrect ghost info line'
 
987
        self._ghosts = info[2:-1]
 
988
        self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
989
 
 
990
    def _read_header_if_needed(self):
 
991
        """Read the header of the dirstate file if needed."""
 
992
        # inline this as it will be called a lot
 
993
        if not self._lock_token:
 
994
            raise errors.ObjectNotLocked(self)
 
995
        if self._header_state == DirState.NOT_IN_MEMORY:
 
996
            self._read_header()
 
997
 
 
998
    def _read_prelude(self):
 
999
        """Read in the prelude header of the dirstate file
 
1000
 
 
1001
        This only reads in the stuff that is not connected to the adler
 
1002
        checksum. The position will be correct to read in the rest of
 
1003
        the file and check the checksum after this point.
 
1004
        The next entry in the file should be the number of parents,
 
1005
        and their ids. Followed by a newline.
 
1006
        """
 
1007
        header = self._state_file.readline()
 
1008
        assert header == '#bazaar dirstate flat format 2\n', \
 
1009
            'invalid header line: %r' % (header,)
 
1010
        adler_line = self._state_file.readline()
 
1011
        assert adler_line.startswith('adler32: '), 'missing adler32 checksum'
 
1012
        self.adler_expected = int(adler_line[len('adler32: '):-1])
 
1013
        num_entries_line = self._state_file.readline()
 
1014
        assert num_entries_line.startswith('num_entries: '), 'missing num_entries line'
 
1015
        self._num_entries = int(num_entries_line[len('num_entries: '):-1])
 
1016
    
 
1017
    def save(self):
 
1018
        """Save any pending changes created during this session.
 
1019
        
 
1020
        We reuse the existing file, because that prevents race conditions with
 
1021
        file creation, and we expect to be using oslocks on it in the near 
 
1022
        future to prevent concurrent modification and reads - because dirstates
 
1023
        incremental data aggretation is not compatible with reading a modified
 
1024
        file, and replacing a file in use by another process is impossible on 
 
1025
        windows.
 
1026
 
 
1027
        A dirstate in read only mode should be smart enough though to validate
 
1028
        that the file has not changed, and otherwise discard its cache and
 
1029
        start over, to allow for fine grained read lock duration, so 'status'
 
1030
        wont block 'commit' - for example.
 
1031
        """
 
1032
        if (self._header_state == DirState.IN_MEMORY_MODIFIED or
 
1033
            self._dirblock_state == DirState.IN_MEMORY_MODIFIED):
 
1034
            self._state_file.seek(0)
 
1035
            self._state_file.writelines(self.get_lines())
 
1036
            self._state_file.truncate()
 
1037
            self._state_file.flush()
 
1038
            self._header_state = DirState.IN_MEMORY_UNMODIFIED
 
1039
            self._dirblock_state = DirState.IN_MEMORY_UNMODIFIED
 
1040
 
 
1041
    def _set_data(self, parent_ids, dirblocks):
 
1042
        """Set the full dirstate data in memory.
 
1043
 
 
1044
        This is an internal function used to completely replace the objects
 
1045
        in memory state. It puts the dirstate into state 'full-dirty'.
 
1046
 
 
1047
        :param parent_ids: A list of parent tree revision ids.
 
1048
        :param dirblocks: A list containing one tuple for each directory in the
 
1049
            tree. Each tuple contains the directory path and a list of entries 
 
1050
            found in that directory.
 
1051
        """
 
1052
        # our memory copy is now authoritative.
 
1053
        self._dirblocks = dirblocks
 
1054
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1055
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1056
        self._parents = list(parent_ids)
 
1057
 
 
1058
    def set_path_id(self, path, new_id):
 
1059
        """Change the id of path to new_id in the current working tree.
 
1060
 
 
1061
        :param path: The path inside the tree to set - '' is the root, 'foo'
 
1062
            is the path foo in the root.
 
1063
        :param new_id: The new id to assign to the path. This must be a utf8
 
1064
            file id (not unicode, and not None).
 
1065
        """
 
1066
        # TODO: start warning here.
 
1067
        assert new_id.__class__ == str
 
1068
        self._read_dirblocks_if_needed()
 
1069
        if len(path):
 
1070
            import pdb;pdb.set_trace()
 
1071
            # logic not written
 
1072
            raise NotImplementedError(self.set_path_id)
 
1073
        # TODO: check new id is unique
 
1074
        entry = self._get_entry(0, path_utf8=path)
 
1075
        # mark the old path absent, and insert a new root path
 
1076
        present_parents = len(entry[1]) - 1
 
1077
        self._make_absent(entry)
 
1078
        id_index = self._get_id_index()
 
1079
        self.update_minimal(('', '', new_id), 'directory', present_parents,
 
1080
            path_utf8='', id_index=id_index, packed_stat=entry[1][0][4])
 
1081
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1082
 
 
1083
    def set_parent_trees(self, trees, ghosts):
 
1084
        """Set the parent trees for the dirstate.
 
1085
 
 
1086
        :param trees: A list of revision_id, tree tuples. tree must be provided
 
1087
            even if the revision_id refers to a ghost: supply an empty tree in 
 
1088
            this case.
 
1089
        :param ghosts: A list of the revision_ids that are ghosts at the time
 
1090
            of setting.
 
1091
        """ 
 
1092
        # TODO: generate a list of parent indexes to preserve to save 
 
1093
        # processing specific parent trees. In the common case one tree will
 
1094
        # be preserved - the left most parent.
 
1095
        # TODO: if the parent tree is a dirstate, we might want to walk them
 
1096
        # all by path in parallel for 'optimal' common-case performance.
 
1097
        # generate new root row.
 
1098
        self._read_dirblocks_if_needed()
 
1099
        # TODO future sketch: Examine the existing parents to generate a change
 
1100
        # map and then walk the new parent trees only, mapping them into the
 
1101
        # dirstate. Walk the dirstate at the same time to remove unreferenced
 
1102
        # entries.
 
1103
        # for now: 
 
1104
        # sketch: loop over all entries in the dirstate, cherry picking 
 
1105
        # entries from the parent trees, if they are not ghost trees.
 
1106
        # after we finish walking the dirstate, all entries not in the dirstate
 
1107
        # are deletes, so we want to append them to the end as per the design
 
1108
        # discussions. So do a set difference on ids with the parents to
 
1109
        # get deletes, and add them to the end.
 
1110
        # During the update process we need to answer the following questions:
 
1111
        # - find other keys containing a fileid in order to create cross-path
 
1112
        #   links. We dont't trivially use the inventory from other trees
 
1113
        #   because this leads to either double touching, or to accessing
 
1114
        #   missing keys,
 
1115
        # - find other keys containing a path 
 
1116
        # We accumulate each entry via this dictionary, including the root 
 
1117
        by_path = {}
 
1118
        id_index = {}
 
1119
        # we could do parallel iterators, but because file id data may be
 
1120
        # scattered throughout, we dont save on index overhead: we have to look
 
1121
        # at everything anyway. We can probably save cycles by reusing parent
 
1122
        # data and doing an incremental update when adding an additional
 
1123
        # parent, but for now the common cases are adding a new parent (merge),
 
1124
        # and replacing completely (commit), and commit is more common: so
 
1125
        # optimise merge later.
 
1126
        
 
1127
        # ---- start generation of full tree mapping data
 
1128
        # what trees should we use?
 
1129
        parent_trees = [tree for rev_id, tree in trees if rev_id not in ghosts]
 
1130
        # how many trees do we end up with 
 
1131
        parent_count = len(parent_trees)
 
1132
 
 
1133
        # one: the current tree
 
1134
        for entry in self._iter_entries():
 
1135
            # skip entries not in the current tree
 
1136
            if entry[1][0][0] in ('a', 'r'): # absent, relocated
 
1137
                continue
 
1138
            by_path[entry[0]] = [entry[1][0]] + \
 
1139
                [DirState.NULL_PARENT_DETAILS] * parent_count
 
1140
            id_index[entry[0][2]] = set([entry[0]])
 
1141
        
 
1142
        # now the parent trees:
 
1143
        for tree_index, tree in enumerate(parent_trees):
 
1144
            # the index is off by one, adjust it.
 
1145
            tree_index = tree_index + 1
 
1146
            # when we add new locations for a fileid we need these ranges for
 
1147
            # any fileid in this tree as we set the by_path[id] to:
 
1148
            # already_processed_tree_details + new_details + new_location_suffix
 
1149
            # the suffix is from tree_index+1:parent_count+1.
 
1150
            new_location_suffix = [DirState.NULL_PARENT_DETAILS] * (parent_count - tree_index)
 
1151
            # now stitch in all the entries from this tree
 
1152
            for path, entry in tree.inventory.iter_entries_by_dir():
 
1153
                # here we process each trees details for each item in the tree.
 
1154
                # we first update any existing entries for the id at other paths,
 
1155
                # then we either create or update the entry for the id at the
 
1156
                # right path, and finally we add (if needed) a mapping from
 
1157
                # file_id to this path. We do it in this order to allow us to
 
1158
                # avoid checking all known paths for the id when generating a
 
1159
                # new entry at this path: by adding the id->path mapping last,
 
1160
                # all the mappings are valid and have correct relocation
 
1161
                # records where needed. 
 
1162
                file_id = entry.file_id
 
1163
                path_utf8 = path.encode('utf8')
 
1164
                dirname, basename = os.path.split(path_utf8)
 
1165
                new_entry_key = (dirname, basename, file_id)
 
1166
                # tree index consistency: All other paths for this id in this tree
 
1167
                # index must point to the correct path.
 
1168
                for entry_key in id_index.setdefault(file_id, set()):
 
1169
                    # TODO:PROFILING: It might be faster to just update
 
1170
                    # rather than checking if we need to, and then overwrite
 
1171
                    # the one we are located at.
 
1172
                    if entry_key != new_entry_key:
 
1173
                        # this file id is at a different path in one of the
 
1174
                        # other trees, so put absent pointers there
 
1175
                        # This is the vertical axis in the matrix, all pointing
 
1176
                        # tot he real path.
 
1177
                        by_path[entry_key][tree_index] = ('r', path_utf8, 0, False, '')
 
1178
                # by path consistency: Insert into an existing path record (trivial), or 
 
1179
                # add a new one with relocation pointers for the other tree indexes.
 
1180
                if new_entry_key in id_index[file_id]:
 
1181
                    # there is already an entry where this data belongs, just insert it.
 
1182
                    by_path[new_entry_key][tree_index] = \
 
1183
                        self._inv_entry_to_details(entry)
 
1184
                else:
 
1185
                    # add relocated entries to the horizontal axis - this row
 
1186
                    # mapping from path,id. We need to look up the correct path
 
1187
                    # for the indexes from 0 to tree_index -1
 
1188
                    new_details = []
 
1189
                    for lookup_index in xrange(tree_index):
 
1190
                        # boundary case: this is the first occurence of file_id
 
1191
                        # so there are no id_indexs, possibly take this out of
 
1192
                        # the loop?
 
1193
                        if not len(id_index[file_id]):
 
1194
                            new_details.append(DirState.NULL_PARENT_DETAILS)
 
1195
                        else:
 
1196
                            # grab any one entry, use it to find the right path.
 
1197
                            # TODO: optimise this to reduce memory use in highly 
 
1198
                            # fragmented situations by reusing the relocation
 
1199
                            # records.
 
1200
                            a_key = iter(id_index[file_id]).next()
 
1201
                            if by_path[a_key][lookup_index][0] in ('r', 'a'):
 
1202
                                # its a pointer or missing statement, use it as is.
 
1203
                                new_details.append(by_path[a_key][lookup_index])
 
1204
                            else:
 
1205
                                # we have the right key, make a pointer to it.
 
1206
                                real_path = ('/'.join(a_key[0:2])).strip('/')
 
1207
                                new_details.append(('r', real_path, 0, False, ''))
 
1208
                    new_details.append(self._inv_entry_to_details(entry))
 
1209
                    new_details.extend(new_location_suffix)
 
1210
                    by_path[new_entry_key] = new_details
 
1211
                    id_index[file_id].add(new_entry_key)
 
1212
        # --- end generation of full tree mappings
 
1213
 
 
1214
        # sort and output all the entries
 
1215
        new_entries = sorted(by_path.items())
 
1216
        self._entries_to_current_state(new_entries)
 
1217
        self._parents = [rev_id for rev_id, tree in trees]
 
1218
        self._ghosts = list(ghosts)
 
1219
        self._header_state = DirState.IN_MEMORY_MODIFIED
 
1220
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1221
 
 
1222
    def set_state_from_inventory(self, new_inv):
 
1223
        """Set new_inv as the current state. 
 
1224
 
 
1225
        This API is called by tree transform, and will usually occur with
 
1226
        existing parent trees.
 
1227
 
 
1228
        :param new_inv: The inventory object to set current state from.
 
1229
        """
 
1230
        self._read_dirblocks_if_needed()
 
1231
        # sketch:
 
1232
        #  generate a byid index of the dirstate
 
1233
        id_index = self._get_id_index()
 
1234
 
 
1235
        num_present_parents = len(self._parents) - len(self._ghosts)
 
1236
        # incremental algorithm:
 
1237
        # two iterators: current data and new data, both in dirblock order. 
 
1238
        new_iterator = new_inv.iter_entries_by_dir()
 
1239
        # we will be modifying the dirstate, so we need a stable iterator. In
 
1240
        # future we might write one, for now we just clone the state into a
 
1241
        # list - which is a shallow copy, so each 
 
1242
        old_iterator = iter(list(self._iter_entries()))
 
1243
        # both must have roots so this is safe:
 
1244
        current_new = new_iterator.next()
 
1245
        current_old = old_iterator.next()
 
1246
        def advance(iterator):
 
1247
            try:
 
1248
                return iterator.next()
 
1249
            except StopIteration:
 
1250
                return None
 
1251
        while current_new or current_old:
 
1252
            # skip entries in old that are not really there
 
1253
            if current_old and current_old[1][0][0] in ('r', 'a'):
 
1254
                # relocated or absent
 
1255
                current_old = advance(old_iterator)
 
1256
                continue
 
1257
            if current_new:
 
1258
                # convert new into dirblock style
 
1259
                new_path_utf8 = current_new[0].encode('utf8')
 
1260
                new_dirname, new_basename = os.path.split(new_path_utf8)
 
1261
                new_id = current_new[1].file_id
 
1262
                new_entry_key = (new_dirname, new_basename, new_id)
 
1263
            else:
 
1264
                # for safety disable variables
 
1265
                new_path_utf8 = new_dirname = new_basename = new_id = new_entry_key = None
 
1266
            # 5 cases, we dont have a value that is strictly greater than everything, so
 
1267
            # we make both end conditions explicit
 
1268
            if not current_old:
 
1269
                # old is finished: insert current_new into the state.
 
1270
                self.update_minimal(new_entry_key, current_new[1].kind,
 
1271
                    num_present_parents, executable=current_new[1].executable,
 
1272
                    id_index=id_index, path_utf8=new_path_utf8)
 
1273
                current_new = advance(new_iterator)
 
1274
            elif not current_new:
 
1275
                # new is finished
 
1276
                self._make_absent(current_old, id_index)
 
1277
                current_old = advance(old_iterator)
 
1278
            elif new_entry_key == current_old[0]:
 
1279
                # same -  common case
 
1280
                # TODO: update the record if anything significant has changed.
 
1281
                # the minimal required trigger is if the execute bit or cached
 
1282
                # kind has changed.
 
1283
                kind = DirState._minikind_to_kind[current_old[1][0][0]]
 
1284
                if (current_old[1][0][3] != current_new[1].executable or
 
1285
                    kind != current_new[1].kind):
 
1286
                    self.update_minimal(current_old[0], current_new[1].kind,
 
1287
                        num_present_parents,
 
1288
                        executable=current_new[1].executable,
 
1289
                        id_index=id_index, path_utf8=new_path_utf8)
 
1290
                # both sides are dealt with, move on
 
1291
                current_old = advance(old_iterator)
 
1292
                current_new = advance(new_iterator)
 
1293
            elif new_entry_key < current_old[0]:
 
1294
                # new comes before:
 
1295
                # add a entry for this and advance new
 
1296
                self.update_minimal(new_entry_key, current_new[1].kind,
 
1297
                    num_present_parents, executable=current_new[1].executable,
 
1298
                    id_index=id_index, path_utf8=new_path_utf8)
 
1299
                current_new = advance(new_iterator)
 
1300
            else:
 
1301
                # old comes before:
 
1302
                self._make_absent(current_old, id_index)
 
1303
                current_old = advance(old_iterator)
 
1304
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1305
 
 
1306
    def _make_absent(self, current_old, id_index=None):
 
1307
        """Mark current_old - an entry - as absent for tree 0.
 
1308
 
 
1309
        :param id_index: An index from fileid_utf8 to sets of keys, used by
 
1310
            some functions. If provided it will be updated if needed.
 
1311
        :return: True if this was the last details entry for they entry key:
 
1312
            that is, if the underlying block has had the entry removed, thus
 
1313
            shrinking in legnth.
 
1314
        """
 
1315
        # build up paths that this id will be left at after the change is made,
 
1316
        # so we can update their cross references in tree 0
 
1317
        all_remaining_keys = set()
 
1318
        # Dont check the working tree, because its going.
 
1319
        for details in current_old[1][1:]:
 
1320
            if details[0] not in ('a', 'r'): # absent, relocated
 
1321
                all_remaining_keys.add(current_old[0])
 
1322
            elif details[0] == 'r': # relocated
 
1323
                # record the key for the real path.
 
1324
                all_remaining_keys.add(tuple(os.path.split(details[1])) + (current_old[0][2],))
 
1325
            # absent rows are not present at any path.
 
1326
        last_reference = current_old[0] not in all_remaining_keys
 
1327
        if last_reference:
 
1328
            # the current row consists entire of the current item (being marked
 
1329
            # absent), and relocated or absent entries for the other trees:
 
1330
            # Remove it, its meaningless.
 
1331
            block = self._find_block(current_old[0])
 
1332
            entry_index, present = self._find_entry_index(current_old[0], block[1])
 
1333
            assert present
 
1334
            block[1].pop(entry_index)
 
1335
            # if we have an id_index in use, remove this key from it for this id.
 
1336
            if id_index is not None:
 
1337
                id_index[current_old[0][2]].remove(current_old[0])
 
1338
        # update all remaining keys for this id to record it as absent. The
 
1339
        # existing details may either be the record we are making as deleted
 
1340
        # (if there were other trees with the id present at this path), or may
 
1341
        # be relocations.
 
1342
        for update_key in all_remaining_keys:
 
1343
            update_block_index, present = \
 
1344
                self._find_block_index_from_key(update_key)
 
1345
            assert present
 
1346
            update_entry_index, present = \
 
1347
                self._find_entry_index(update_key, self._dirblocks[update_block_index][1])
 
1348
            assert present
 
1349
            update_tree_details = self._dirblocks[update_block_index][1][update_entry_index][1]
 
1350
            # it must not be absent at the moment
 
1351
            assert update_tree_details[0][0] != 'a' # absent
 
1352
            update_tree_details[0] = DirState.NULL_PARENT_DETAILS
 
1353
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1354
        return last_reference
 
1355
 
 
1356
    def update_minimal(self, key, kind, num_present_parents, executable=False,
 
1357
        fingerprint='', packed_stat=None, size=0, id_index=None,
 
1358
        path_utf8=None):
 
1359
        """Update an entry to the state in tree 0."""
 
1360
        block = self._find_block(key)[1]
 
1361
        if packed_stat is None:
 
1362
            packed_stat = DirState.NULLSTAT
 
1363
        entry_index, present = self._find_entry_index(key, block)
 
1364
        minikind = DirState._kind_to_minikind[kind]
 
1365
        new_details = (minikind, fingerprint, size, executable, packed_stat)
 
1366
        assert id_index is not None, 'need an id index to do updates for now !'
 
1367
        if not present:
 
1368
            # new entry, synthesis cross reference here,
 
1369
            existing_keys = id_index.setdefault(key[2], set())
 
1370
            if not existing_keys:
 
1371
                # not currently in the state, simplest case
 
1372
                new_entry = key, [new_details] + self._empty_parent_info()
 
1373
            else:
 
1374
                # present at one or more existing other paths.
 
1375
                # grab one of them and use it to generate parent
 
1376
                # relocation/absent entries.
 
1377
                new_entry = key, [new_details]
 
1378
                for other_key in existing_keys:
 
1379
                    # change the record at other to be a pointer to this new
 
1380
                    # record. The loop looks similar to the change to
 
1381
                    # relocations when updating an existing record but its not:
 
1382
                    # the test for existing kinds is different: this can be
 
1383
                    # factored out to a helper though.
 
1384
                    other_block_index, present = self._find_block_index_from_key(other_key)
 
1385
                    assert present
 
1386
                    other_entry_index, present = self._find_entry_index(other_key, self._dirblocks[other_block_index][1])
 
1387
                    assert present
 
1388
                    assert path_utf8 is not None
 
1389
                    self._dirblocks[other_block_index][1][other_entry_index][1][0] = \
 
1390
                        ('r', path_utf8, 0, False, '')
 
1391
 
 
1392
                for lookup_index in xrange(1, num_present_parents + 1):
 
1393
                    # grab any one entry, use it to find the right path.
 
1394
                    # TODO: optimise this to reduce memory use in highly 
 
1395
                    # fragmented situations by reusing the relocation
 
1396
                    # records.
 
1397
                    update_block_index, present = \
 
1398
                        self._find_block_index_from_key(other_key)
 
1399
                    assert present
 
1400
                    update_entry_index, present = \
 
1401
                        self._find_entry_index(other_key, self._dirblocks[update_block_index][1])
 
1402
                    assert present
 
1403
                    update_details = self._dirblocks[update_block_index][1][update_entry_index][1][lookup_index]
 
1404
                    if update_details[0] in ('r', 'a'): # relocated, absent
 
1405
                        # its a pointer or absent in lookup_index's tree, use
 
1406
                        # it as is.
 
1407
                        new_entry[1].append(update_details)
 
1408
                    else:
 
1409
                        # we have the right key, make a pointer to it.
 
1410
                        pointer_path = os.path.join(*other_key[0:2])
 
1411
                        new_entry[1].append(('r', pointer_path, 0, False, ''))
 
1412
            block.insert(entry_index, new_entry)
 
1413
            existing_keys.add(key)
 
1414
        else:
 
1415
            # Does the new state matter? 
 
1416
            block[entry_index][1][0] = new_details
 
1417
            # parents cannot be affected by what we do.
 
1418
            # other occurences of this id can be found 
 
1419
            # from the id index.
 
1420
            # ---
 
1421
            # tree index consistency: All other paths for this id in this tree
 
1422
            # index must point to the correct path. We have to loop here because
 
1423
            # we may have passed entries in the state with this file id already
 
1424
            # that were absent - where parent entries are - and they need to be
 
1425
            # converted to relocated.
 
1426
            assert path_utf8 is not None
 
1427
            for entry_key in id_index.setdefault(key[2], set()):
 
1428
                # TODO:PROFILING: It might be faster to just update
 
1429
                # rather than checking if we need to, and then overwrite
 
1430
                # the one we are located at.
 
1431
                if entry_key != key:
 
1432
                    # this file id is at a different path in one of the
 
1433
                    # other trees, so put absent pointers there
 
1434
                    # This is the vertical axis in the matrix, all pointing
 
1435
                    # to the real path.
 
1436
                    block_index, present = self._find_block_index_from_key(entry_key)
 
1437
                    assert present
 
1438
                    entry_index, present = self._find_entry_index(entry_key, self._dirblocks[block_index][1])
 
1439
                    assert present
 
1440
                    self._dirblocks[block_index][1][entry_index][1][0] = \
 
1441
                        ('r', path_utf8, 0, False, '')
 
1442
        # add a containing dirblock if needed.
 
1443
        if new_details[0] == 'd':
 
1444
            subdir_key = (os.path.join(*key[0:2]), '', '')
 
1445
            block_index, present = self._find_block_index_from_key(subdir_key)
 
1446
            if not present:
 
1447
                self._dirblocks.insert(block_index, (subdir_key[0], []))
 
1448
 
 
1449
        self._dirblock_state = DirState.IN_MEMORY_MODIFIED
 
1450
 
 
1451
 
 
1452
    def _wipe_state(self):
 
1453
        """Forget all state information about the dirstate."""
 
1454
        self._header_state = DirState.NOT_IN_MEMORY
 
1455
        self._dirblock_state = DirState.NOT_IN_MEMORY
 
1456
        self._parents = []
 
1457
        self._ghosts = []
 
1458
        self._dirblocks = []
 
1459
 
 
1460
    def lock_read(self):
 
1461
        """Acquire a read lock on the dirstate"""
 
1462
        if self._lock_token is not None:
 
1463
            raise errors.LockContention(self._lock_token)
 
1464
        self._lock_token = lock.ReadLock(self._filename)
 
1465
        self._state_file = self._lock_token.f
 
1466
        self._wipe_state()
 
1467
 
 
1468
    def lock_write(self):
 
1469
        """Acquire a write lock on the dirstate"""
 
1470
        if self._lock_token is not None:
 
1471
            raise errors.LockContention(self._lock_token)
 
1472
        self._lock_token = lock.WriteLock(self._filename)
 
1473
        self._state_file = self._lock_token.f
 
1474
        self._wipe_state()
 
1475
 
 
1476
    def unlock(self):
 
1477
        """Drop any locks held on the dirstate"""
 
1478
        if self._lock_token is None:
 
1479
            raise errors.LockNotHeld(self)
 
1480
        self._state_file = None
 
1481
        self._lock_token.unlock()
 
1482
        self._lock_token = None
 
1483
 
 
1484
    def _requires_lock(self):
 
1485
        """Checks that a lock is currently held by someone on the dirstate"""
 
1486
        if not self._lock_token:
 
1487
            raise errors.ObjectNotLocked(self)
 
1488
 
 
1489
def pack_stat(st, _encode=base64.encodestring, _pack=struct.pack):
 
1490
    """Convert stat values into a packed representation."""
 
1491
    # jam 20060614 it isn't really worth removing more entries if we
 
1492
    # are going to leave it in packed form.
 
1493
    # With only st_mtime and st_mode filesize is 5.5M and read time is 275ms
 
1494
    # With all entries filesize is 5.9M and read time is mabye 280ms
 
1495
    # well within the noise margin
 
1496
 
 
1497
    # base64.encode always adds a final newline, so strip it off
 
1498
    return _encode(_pack('>llllll'
 
1499
        , st.st_size, st.st_mtime, st.st_ctime
 
1500
        , st.st_dev, st.st_ino, st.st_mode))[:-1]
 
1501