~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

  • Committer: John Arbash Meinel
  • Date: 2013-05-19 14:29:37 UTC
  • mfrom: (6437.63.9 2.5)
  • mto: (6437.63.10 2.5)
  • mto: This revision was merged to the branch mainline in revision 6575.
  • Revision ID: john@arbash-meinel.com-20130519142937-21ykz2n2y2f22za9
Merge in the actual 2.5 branch. It seems I failed before

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2007-2012 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
"""WorkingTree4 format and implementation.
18
18
 
22
22
WorkingTree.open(dir).
23
23
"""
24
24
 
 
25
from __future__ import absolute_import
 
26
 
25
27
from cStringIO import StringIO
26
28
import os
27
29
import sys
28
30
 
29
31
from bzrlib.lazy_import import lazy_import
30
32
lazy_import(globals(), """
31
 
from bisect import bisect_left
32
 
import collections
33
 
from copy import deepcopy
34
33
import errno
35
 
import itertools
36
 
import operator
37
34
import stat
38
 
from time import time
39
 
import warnings
40
35
 
41
 
import bzrlib
42
36
from bzrlib import (
43
37
    bzrdir,
44
38
    cache_utf8,
 
39
    config,
45
40
    conflicts as _mod_conflicts,
46
 
    delta,
 
41
    debug,
47
42
    dirstate,
48
43
    errors,
 
44
    filters as _mod_filters,
49
45
    generate_ids,
50
 
    globbing,
51
 
    hashcache,
52
 
    ignores,
53
 
    merge,
54
46
    osutils,
 
47
    revision as _mod_revision,
55
48
    revisiontree,
56
 
    textui,
 
49
    trace,
57
50
    transform,
58
 
    urlutils,
59
 
    xml5,
60
 
    xml6,
 
51
    views,
61
52
    )
62
 
import bzrlib.branch
63
 
from bzrlib.transport import get_transport
64
 
import bzrlib.ui
65
53
""")
66
54
 
67
 
from bzrlib import symbol_versioning
68
55
from bzrlib.decorators import needs_read_lock, needs_write_lock
69
 
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, entry_factory
70
 
from bzrlib.lockable_files import LockableFiles, TransportLock
 
56
from bzrlib.inventory import Inventory, ROOT_ID, entry_factory
 
57
from bzrlib.lock import LogicalLockResult
 
58
from bzrlib.lockable_files import LockableFiles
71
59
from bzrlib.lockdir import LockDir
72
 
import bzrlib.mutabletree
73
 
from bzrlib.mutabletree import needs_tree_write_lock
 
60
from bzrlib.mutabletree import (
 
61
    MutableTree,
 
62
    needs_tree_write_lock,
 
63
    )
74
64
from bzrlib.osutils import (
75
65
    file_kind,
76
66
    isdir,
77
 
    normpath,
78
67
    pathjoin,
79
 
    rand_chars,
80
68
    realpath,
81
69
    safe_unicode,
82
 
    splitpath,
83
70
    )
84
 
from bzrlib.trace import mutter, note
85
71
from bzrlib.transport.local import LocalTransport
86
 
from bzrlib.tree import InterTree
87
 
from bzrlib.progress import DummyProgress, ProgressPhase
88
 
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
89
 
from bzrlib.rio import RioReader, rio_file, Stanza
90
 
from bzrlib.symbol_versioning import (deprecated_passed,
91
 
        deprecated_method,
92
 
        deprecated_function,
93
 
        DEPRECATED_PARAMETER,
94
 
        )
95
 
from bzrlib.tree import Tree
96
 
from bzrlib.workingtree import WorkingTree, WorkingTree3, WorkingTreeFormat3
97
 
 
98
 
 
99
 
# This is the Windows equivalent of ENOTDIR
100
 
# It is defined in pywin32.winerror, but we don't want a strong dependency for
101
 
# just an error code.
102
 
ERROR_PATH_NOT_FOUND = 3
103
 
ERROR_DIRECTORY = 267
104
 
 
105
 
 
106
 
class WorkingTree4(WorkingTree3):
107
 
    """This is the Format 4 working tree.
108
 
 
109
 
    This differs from WorkingTree3 by:
110
 
     - Having a consolidated internal dirstate, stored in a
111
 
       randomly-accessible sorted file on disk.
112
 
     - Not having a regular inventory attribute.  One can be synthesized 
113
 
       on demand but this is expensive and should be avoided.
114
 
 
115
 
    This is new in bzr 0.15.
116
 
    """
 
72
from bzrlib.tree import (
 
73
    InterTree,
 
74
    InventoryTree,
 
75
    )
 
76
from bzrlib.workingtree import (
 
77
    InventoryWorkingTree,
 
78
    WorkingTree,
 
79
    WorkingTreeFormatMetaDir,
 
80
    )
 
81
 
 
82
 
 
83
class DirStateWorkingTree(InventoryWorkingTree):
117
84
 
118
85
    def __init__(self, basedir,
119
86
                 branch,
129
96
        """
130
97
        self._format = _format
131
98
        self.bzrdir = _bzrdir
132
 
        from bzrlib.trace import note, mutter
133
 
        assert isinstance(basedir, basestring), \
134
 
            "base directory %r is not a string" % basedir
135
99
        basedir = safe_unicode(basedir)
136
 
        mutter("opening working tree %r", basedir)
 
100
        trace.mutter("opening working tree %r", basedir)
137
101
        self._branch = branch
138
 
        assert isinstance(self.branch, bzrlib.branch.Branch), \
139
 
            "branch %r is not a Branch" % self.branch
140
102
        self.basedir = realpath(basedir)
141
103
        # if branch is at our basedir and is a format 6 or less
142
104
        # assume all other formats have their own control files.
143
 
        assert isinstance(_control_files, LockableFiles), \
144
 
            "_control_files must be a LockableFiles, not %r" % _control_files
145
105
        self._control_files = _control_files
 
106
        self._transport = self._control_files._transport
146
107
        self._dirty = None
147
108
        #-------------
148
109
        # during a read or write lock these objects are set, and are
150
111
        self._dirstate = None
151
112
        self._inventory = None
152
113
        #-------------
 
114
        self._setup_directory_is_tree_reference()
 
115
        self._detect_case_handling()
 
116
        self._rules_searcher = None
 
117
        self.views = self._make_views()
 
118
        #--- allow tests to select the dirstate iter_changes implementation
 
119
        self._iter_changes = dirstate._process_entry
153
120
 
154
121
    @needs_tree_write_lock
155
122
    def _add(self, files, ids, kinds):
157
124
        state = self.current_dirstate()
158
125
        for f, file_id, kind in zip(files, ids, kinds):
159
126
            f = f.strip('/')
160
 
            assert '//' not in f
161
 
            assert '..' not in f
162
127
            if self.path2id(f):
163
128
                # special case tree root handling.
164
129
                if f == '' and self.path2id(f) == ROOT_ID:
172
137
            state.add(f, file_id, kind, None, '')
173
138
        self._make_dirty(reset_inventory=True)
174
139
 
 
140
    def _get_check_refs(self):
 
141
        """Return the references needed to perform a check of this tree."""
 
142
        return [('trees', self.last_revision())]
 
143
 
175
144
    def _make_dirty(self, reset_inventory):
176
145
        """Make the tree state dirty.
177
146
 
185
154
    @needs_tree_write_lock
186
155
    def add_reference(self, sub_tree):
187
156
        # use standard implementation, which calls back to self._add
188
 
        # 
 
157
        #
189
158
        # So we don't store the reference_revision in the working dirstate,
190
 
        # it's just recorded at the moment of commit. 
 
159
        # it's just recorded at the moment of commit.
191
160
        self._add_reference(sub_tree)
192
161
 
193
162
    def break_lock(self):
229
198
 
230
199
    def _comparison_data(self, entry, path):
231
200
        kind, executable, stat_value = \
232
 
            WorkingTree3._comparison_data(self, entry, path)
 
201
            WorkingTree._comparison_data(self, entry, path)
233
202
        # it looks like a plain directory, but it's really a reference -- see
234
203
        # also kind()
235
 
        if (self._repo_supports_tree_reference and
236
 
            kind == 'directory' and
237
 
            self._directory_is_tree_reference(path)):
 
204
        if (self._repo_supports_tree_reference and kind == 'directory'
 
205
            and entry is not None and entry.kind == 'tree-reference'):
238
206
            kind = 'tree-reference'
239
207
        return kind, executable, stat_value
240
208
 
242
210
    def commit(self, message=None, revprops=None, *args, **kwargs):
243
211
        # mark the tree as dirty post commit - commit
244
212
        # can change the current versioned list by doing deletes.
245
 
        result = WorkingTree3.commit(self, message, revprops, *args, **kwargs)
 
213
        result = WorkingTree.commit(self, message, revprops, *args, **kwargs)
246
214
        self._make_dirty(reset_inventory=True)
247
215
        return result
248
216
 
266
234
            return self._dirstate
267
235
        local_path = self.bzrdir.get_workingtree_transport(None
268
236
            ).local_abspath('dirstate')
269
 
        self._dirstate = dirstate.DirState.on_file(local_path)
 
237
        self._dirstate = dirstate.DirState.on_file(local_path,
 
238
            self._sha1_provider(), self._worth_saving_limit())
270
239
        return self._dirstate
271
240
 
272
 
    def _directory_is_tree_reference(self, relpath):
273
 
        # as a special case, if a directory contains control files then 
274
 
        # it's a tree reference, except that the root of the tree is not
275
 
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
276
 
        # TODO: We could ask all the control formats whether they
277
 
        # recognize this directory, but at the moment there's no cheap api
278
 
        # to do that.  Since we probably can only nest bzr checkouts and
279
 
        # they always use this name it's ok for now.  -- mbp 20060306
280
 
        #
281
 
        # FIXME: There is an unhandled case here of a subdirectory
282
 
        # containing .bzr but not a branch; that will probably blow up
283
 
        # when you try to commit it.  It might happen if there is a
284
 
        # checkout in a subdirectory.  This can be avoided by not adding
285
 
        # it.  mbp 20070306
 
241
    def _sha1_provider(self):
 
242
        """A function that returns a SHA1Provider suitable for this tree.
 
243
 
 
244
        :return: None if content filtering is not supported by this tree.
 
245
          Otherwise, a SHA1Provider is returned that sha's the canonical
 
246
          form of files, i.e. after read filters are applied.
 
247
        """
 
248
        if self.supports_content_filtering():
 
249
            return ContentFilterAwareSHA1Provider(self)
 
250
        else:
 
251
            return None
 
252
 
 
253
    def _worth_saving_limit(self):
 
254
        """How many hash changes are ok before we must save the dirstate.
 
255
 
 
256
        :return: an integer. -1 means never save.
 
257
        """
 
258
        # FIXME: We want a WorkingTreeStack here -- vila 20110812
 
259
        conf = config.BranchStack(self.branch)
 
260
        return conf.get('bzr.workingtree.worth_saving_limit')
286
261
 
287
262
    def filter_unversioned_files(self, paths):
288
263
        """Filter out paths that are versioned.
321
296
 
322
297
    def _generate_inventory(self):
323
298
        """Create and set self.inventory from the dirstate object.
324
 
        
 
299
 
325
300
        This is relatively expensive: we have to walk the entire dirstate.
326
301
        Ideally we would not, and can deprecate this function.
327
302
        """
331
306
        state._read_dirblocks_if_needed()
332
307
        root_key, current_entry = self._get_entry(path='')
333
308
        current_id = root_key[2]
334
 
        assert current_entry[0][0] == 'd' # directory
 
309
        if not (current_entry[0][0] == 'd'): # directory
 
310
            raise AssertionError(current_entry)
335
311
        inv = Inventory(root_id=current_id)
336
312
        # Turn some things into local variables
337
313
        minikind_to_kind = dirstate.DirState._minikind_to_kind
370
346
                    # add this entry to the parent map.
371
347
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
372
348
                elif kind == 'tree-reference':
373
 
                    assert self._repo_supports_tree_reference, \
374
 
                        "repository of %r " \
375
 
                        "doesn't support tree references " \
376
 
                        "required by entry %r" \
377
 
                        % (self, name)
 
349
                    if not self._repo_supports_tree_reference:
 
350
                        raise errors.UnsupportedOperation(
 
351
                            self._generate_inventory,
 
352
                            self.branch.repository)
378
353
                    inv_entry.reference_revision = link_or_sha1 or None
379
354
                elif kind != 'symlink':
380
355
                    raise AssertionError("unknown kind %r" % kind)
381
356
                # These checks cost us around 40ms on a 55k entry tree
382
 
                assert file_id not in inv_byid, ('file_id %s already in'
383
 
                    ' inventory as %s' % (file_id, inv_byid[file_id]))
384
 
                assert name_unicode not in parent_ie.children
 
357
                if file_id in inv_byid:
 
358
                    raise AssertionError('file_id %s already in'
 
359
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
 
360
                if name_unicode in parent_ie.children:
 
361
                    raise AssertionError('name %r already in parent'
 
362
                        % (name_unicode,))
385
363
                inv_byid[file_id] = inv_entry
386
364
                parent_ie.children[name_unicode] = inv_entry
387
365
        self._inventory = inv
392
370
        If either file_id or path is supplied, it is used as the key to lookup.
393
371
        If both are supplied, the fastest lookup is used, and an error is
394
372
        raised if they do not both point at the same row.
395
 
        
 
373
 
396
374
        :param file_id: An optional unicode file_id to be looked up.
397
375
        :param path: An optional unicode path to be looked up.
398
376
        :return: The dirstate row tuple for path/file_id, or (None, None)
407
385
    def get_file_sha1(self, file_id, path=None, stat_value=None):
408
386
        # check file id is valid unconditionally.
409
387
        entry = self._get_entry(file_id=file_id, path=path)
410
 
        assert entry[0] is not None, 'what error should this raise'
 
388
        if entry[0] is None:
 
389
            raise errors.NoSuchId(self, file_id)
411
390
        if path is None:
412
391
            path = pathjoin(entry[0][0], entry[0][1]).decode('utf8')
413
392
 
414
393
        file_abspath = self.abspath(path)
415
394
        state = self.current_dirstate()
416
 
        link_or_sha1 = state.update_entry(entry, file_abspath,
417
 
                                          stat_value=stat_value)
 
395
        if stat_value is None:
 
396
            try:
 
397
                stat_value = osutils.lstat(file_abspath)
 
398
            except OSError, e:
 
399
                if e.errno == errno.ENOENT:
 
400
                    return None
 
401
                else:
 
402
                    raise
 
403
        link_or_sha1 = dirstate.update_entry(state, entry, file_abspath,
 
404
            stat_value=stat_value)
418
405
        if entry[1][0][0] == 'f':
419
 
            return link_or_sha1
 
406
            if link_or_sha1 is None:
 
407
                file_obj, statvalue = self.get_file_with_stat(file_id, path)
 
408
                try:
 
409
                    sha1 = osutils.sha_file(file_obj)
 
410
                finally:
 
411
                    file_obj.close()
 
412
                self._observed_sha1(file_id, path, (sha1, statvalue))
 
413
                return sha1
 
414
            else:
 
415
                return link_or_sha1
420
416
        return None
421
417
 
422
418
    def _get_inventory(self):
423
419
        """Get the inventory for the tree. This is only valid within a lock."""
 
420
        if 'evil' in debug.debug_flags:
 
421
            trace.mutter_callsite(2,
 
422
                "accessing .inventory forces a size of tree translation.")
424
423
        if self._inventory is not None:
425
424
            return self._inventory
426
425
        self._must_be_locked()
433
432
    @needs_read_lock
434
433
    def get_parent_ids(self):
435
434
        """See Tree.get_parent_ids.
436
 
        
 
435
 
437
436
        This implementation requests the ids list from the dirstate file.
438
437
        """
439
438
        return self.current_dirstate().get_parent_ids()
455
454
 
456
455
    def has_id(self, file_id):
457
456
        state = self.current_dirstate()
458
 
        file_id = osutils.safe_file_id(file_id)
459
457
        row, parents = self._get_entry(file_id=file_id)
460
458
        if row is None:
461
459
            return False
462
460
        return osutils.lexists(pathjoin(
463
461
                    self.basedir, row[0].decode('utf8'), row[1].decode('utf8')))
464
462
 
 
463
    def has_or_had_id(self, file_id):
 
464
        state = self.current_dirstate()
 
465
        row, parents = self._get_entry(file_id=file_id)
 
466
        return row is not None
 
467
 
465
468
    @needs_read_lock
466
469
    def id2path(self, file_id):
467
 
        file_id = osutils.safe_file_id(file_id)
 
470
        "Convert a file-id to a path."
468
471
        state = self.current_dirstate()
469
472
        entry = self._get_entry(file_id=file_id)
470
473
        if entry == (None, None):
472
475
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
473
476
        return path_utf8.decode('utf8')
474
477
 
475
 
    if not osutils.supports_executable():
476
 
        @needs_read_lock
477
 
        def is_executable(self, file_id, path=None):
478
 
            file_id = osutils.safe_file_id(file_id)
 
478
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
 
479
        entry = self._get_entry(path=path)
 
480
        if entry == (None, None):
 
481
            return False # Missing entries are not executable
 
482
        return entry[1][0][3] # Executable?
 
483
 
 
484
    def is_executable(self, file_id, path=None):
 
485
        """Test if a file is executable or not.
 
486
 
 
487
        Note: The caller is expected to take a read-lock before calling this.
 
488
        """
 
489
        if not self._supports_executable():
479
490
            entry = self._get_entry(file_id=file_id, path=path)
480
491
            if entry == (None, None):
481
492
                return False
482
493
            return entry[1][0][3]
483
 
    else:
484
 
        @needs_read_lock
485
 
        def is_executable(self, file_id, path=None):
 
494
        else:
 
495
            self._must_be_locked()
486
496
            if not path:
487
 
                file_id = osutils.safe_file_id(file_id)
488
497
                path = self.id2path(file_id)
489
 
            mode = os.lstat(self.abspath(path)).st_mode
 
498
            mode = osutils.lstat(self.abspath(path)).st_mode
490
499
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
491
500
 
 
501
    def all_file_ids(self):
 
502
        """See Tree.iter_all_file_ids"""
 
503
        self._must_be_locked()
 
504
        result = set()
 
505
        for key, tree_details in self.current_dirstate()._iter_entries():
 
506
            if tree_details[0][0] in ('a', 'r'): # relocated
 
507
                continue
 
508
            result.add(key[2])
 
509
        return result
 
510
 
492
511
    @needs_read_lock
493
512
    def __iter__(self):
494
513
        """Iterate through file_ids for this tree.
507
526
        return iter(result)
508
527
 
509
528
    def iter_references(self):
 
529
        if not self._repo_supports_tree_reference:
 
530
            # When the repo doesn't support references, we will have nothing to
 
531
            # return
 
532
            return
510
533
        for key, tree_details in self.current_dirstate()._iter_entries():
511
534
            if tree_details[0][0] in ('a', 'r'): # absent, relocated
512
535
                # not relevant to the working tree
514
537
            if not key[1]:
515
538
                # the root is not a reference.
516
539
                continue
517
 
            path = pathjoin(self.basedir, key[0].decode('utf8'), key[1].decode('utf8'))
 
540
            relpath = pathjoin(key[0].decode('utf8'), key[1].decode('utf8'))
518
541
            try:
519
 
                if self._kind(path) == 'tree-reference':
520
 
                    yield path, key[2]
 
542
                if self._kind(relpath) == 'tree-reference':
 
543
                    yield relpath, key[2]
521
544
            except errors.NoSuchFile:
522
545
                # path is missing on disk.
523
546
                continue
524
547
 
525
 
    @needs_read_lock
 
548
    def _observed_sha1(self, file_id, path, (sha1, statvalue)):
 
549
        """See MutableTree._observed_sha1."""
 
550
        state = self.current_dirstate()
 
551
        entry = self._get_entry(file_id=file_id, path=path)
 
552
        state._observed_sha1(entry, sha1, statvalue)
 
553
 
526
554
    def kind(self, file_id):
527
555
        """Return the kind of a file.
528
556
 
529
557
        This is always the actual kind that's on disk, regardless of what it
530
558
        was added as.
 
559
 
 
560
        Note: The caller is expected to take a read-lock before calling this.
531
561
        """
532
562
        relpath = self.id2path(file_id)
533
 
        assert relpath != None, \
534
 
            "path for id {%s} is None!" % file_id
 
563
        if relpath is None:
 
564
            raise AssertionError(
 
565
                "path for id {%s} is None!" % file_id)
535
566
        return self._kind(relpath)
536
567
 
537
568
    def _kind(self, relpath):
538
569
        abspath = self.abspath(relpath)
539
570
        kind = file_kind(abspath)
540
 
        if (self._repo_supports_tree_reference and
541
 
            kind == 'directory' and
542
 
            self._directory_is_tree_reference(relpath)):
543
 
            kind = 'tree-reference'
 
571
        if (self._repo_supports_tree_reference and kind == 'directory'):
 
572
            entry = self._get_entry(path=relpath)
 
573
            if entry[1] is not None:
 
574
                if entry[1][0][0] == 't':
 
575
                    kind = 'tree-reference'
544
576
        return kind
545
577
 
546
578
    @needs_read_lock
550
582
        if parent_ids:
551
583
            return parent_ids[0]
552
584
        else:
553
 
            return None
 
585
            return _mod_revision.NULL_REVISION
554
586
 
555
587
    def lock_read(self):
556
 
        """See Branch.lock_read, and WorkingTree.unlock."""
 
588
        """See Branch.lock_read, and WorkingTree.unlock.
 
589
 
 
590
        :return: A bzrlib.lock.LogicalLockResult.
 
591
        """
557
592
        self.branch.lock_read()
558
593
        try:
559
594
            self._control_files.lock_read()
572
607
        except:
573
608
            self.branch.unlock()
574
609
            raise
 
610
        return LogicalLockResult(self.unlock)
575
611
 
576
612
    def _lock_self_write(self):
577
613
        """This should be called after the branch is locked."""
592
628
        except:
593
629
            self.branch.unlock()
594
630
            raise
 
631
        return LogicalLockResult(self.unlock)
595
632
 
596
633
    def lock_tree_write(self):
597
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
 
634
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
 
635
 
 
636
        :return: A bzrlib.lock.LogicalLockResult.
 
637
        """
598
638
        self.branch.lock_read()
599
 
        self._lock_self_write()
 
639
        return self._lock_self_write()
600
640
 
601
641
    def lock_write(self):
602
 
        """See MutableTree.lock_write, and WorkingTree.unlock."""
 
642
        """See MutableTree.lock_write, and WorkingTree.unlock.
 
643
 
 
644
        :return: A bzrlib.lock.LogicalLockResult.
 
645
        """
603
646
        self.branch.lock_write()
604
 
        self._lock_self_write()
 
647
        return self._lock_self_write()
605
648
 
606
649
    @needs_tree_write_lock
607
650
    def move(self, from_paths, to_dir, after=False):
609
652
        result = []
610
653
        if not from_paths:
611
654
            return result
612
 
 
613
655
        state = self.current_dirstate()
614
 
 
615
 
        assert not isinstance(from_paths, basestring)
 
656
        if isinstance(from_paths, basestring):
 
657
            raise ValueError()
616
658
        to_dir_utf8 = to_dir.encode('utf8')
617
659
        to_entry_dirname, to_basename = os.path.split(to_dir_utf8)
618
660
        id_index = state._get_id_index()
640
682
        if self._inventory is not None:
641
683
            update_inventory = True
642
684
            inv = self.inventory
 
685
            to_dir_id = to_entry[0][2]
643
686
            to_dir_ie = inv[to_dir_id]
644
 
            to_dir_id = to_entry[0][2]
645
687
        else:
646
688
            update_inventory = False
647
689
 
670
712
            new_entry = to_block[1][added_entry_index]
671
713
            rollbacks.append(lambda:state._make_absent(new_entry))
672
714
 
673
 
        # create rename entries and tuples
674
715
        for from_rel in from_paths:
675
716
            # from_rel is 'pathinroot/foo/bar'
676
717
            from_rel_utf8 = from_rel.encode('utf8')
679
720
            from_entry = self._get_entry(path=from_rel)
680
721
            if from_entry == (None, None):
681
722
                raise errors.BzrMoveFailedError(from_rel,to_dir,
682
 
                    errors.NotVersionedError(path=str(from_rel)))
 
723
                    errors.NotVersionedError(path=from_rel))
683
724
 
684
725
            from_id = from_entry[0][2]
685
726
            to_rel = pathjoin(to_dir, from_tail)
712
753
                if from_missing: # implicitly just update our path mapping
713
754
                    move_file = False
714
755
                elif not after:
715
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
716
 
                        extra="(Use --after to update the Bazaar id)")
 
756
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
717
757
 
718
758
            rollbacks = []
719
759
            def rollback_rename():
774
814
 
775
815
                if minikind == 'd':
776
816
                    def update_dirblock(from_dir, to_key, to_dir_utf8):
777
 
                        """all entries in this block need updating.
778
 
 
779
 
                        TODO: This is pretty ugly, and doesn't support
780
 
                        reverting, but it works.
781
 
                        """
782
 
                        assert from_dir != '', "renaming root not supported"
 
817
                        """Recursively update all entries in this dirblock."""
 
818
                        if from_dir == '':
 
819
                            raise AssertionError("renaming root not supported")
783
820
                        from_key = (from_dir, '')
784
821
                        from_block_idx, present = \
785
822
                            state._find_block_index_from_key(from_key)
795
832
                        to_block_index = state._ensure_block(
796
833
                            to_block_index, to_entry_index, to_dir_utf8)
797
834
                        to_block = state._dirblocks[to_block_index]
798
 
                        for entry in from_block[1]:
799
 
                            assert entry[0][0] == from_dir
 
835
 
 
836
                        # Grab a copy since move_one may update the list.
 
837
                        for entry in from_block[1][:]:
 
838
                            if not (entry[0][0] == from_dir):
 
839
                                raise AssertionError()
800
840
                            cur_details = entry[1][0]
801
841
                            to_key = (to_dir_utf8, entry[0][1], entry[0][2])
802
842
                            from_path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
803
843
                            to_path_utf8 = osutils.pathjoin(to_dir_utf8, entry[0][1])
804
844
                            minikind = cur_details[0]
 
845
                            if minikind in 'ar':
 
846
                                # Deleted children of a renamed directory
 
847
                                # Do not need to be updated.
 
848
                                # Children that have been renamed out of this
 
849
                                # directory should also not be updated
 
850
                                continue
805
851
                            move_one(entry, from_path_utf8=from_path_utf8,
806
852
                                     minikind=minikind,
807
853
                                     executable=cur_details[3],
821
867
                rollback_rename()
822
868
                raise
823
869
            result.append((from_rel, to_rel))
824
 
            state._dirblock_state = dirstate.DirState.IN_MEMORY_MODIFIED
 
870
            state._mark_modified()
825
871
            self._make_dirty(reset_inventory=False)
826
872
 
827
873
        return result
855
901
        for tree in trees:
856
902
            if not (isinstance(tree, DirStateRevisionTree) and tree._revision_id in
857
903
                parents):
858
 
                return super(WorkingTree4, self).paths2ids(paths, trees, require_versioned)
 
904
                return super(DirStateWorkingTree, self).paths2ids(paths,
 
905
                    trees, require_versioned)
859
906
        search_indexes = [0] + [1 + parents.index(tree._revision_id) for tree in trees]
860
907
        # -- make all paths utf8 --
861
908
        paths_utf8 = set()
919
966
                    all_versioned = False
920
967
                    break
921
968
            if not all_versioned:
922
 
                raise errors.PathsNotVersionedError(paths)
 
969
                raise errors.PathsNotVersionedError(
 
970
                    [p.decode('utf-8') for p in paths])
923
971
        # -- remove redundancy in supplied paths to prevent over-scanning --
924
 
        search_paths = set()
925
 
        for path in paths:
926
 
            other_paths = paths.difference(set([path]))
927
 
            if not osutils.is_inside_any(other_paths, path):
928
 
                # this is a top level path, we must check it.
929
 
                search_paths.add(path)
930
 
        # sketch: 
 
972
        search_paths = osutils.minimum_path_selection(paths)
 
973
        # sketch:
931
974
        # for all search_indexs in each path at or under each element of
932
975
        # search_paths, if the detail is relocated: add the id, and add the
933
976
        # relocated path as one to search if its not searched already. If the
979
1022
            found_dir_names = set(dir_name_id[:2] for dir_name_id in found)
980
1023
            for dir_name in split_paths:
981
1024
                if dir_name not in found_dir_names:
982
 
                    raise errors.PathsNotVersionedError(paths)
 
1025
                    raise errors.PathsNotVersionedError(
 
1026
                        [p.decode('utf-8') for p in paths])
983
1027
 
984
1028
        for dir_name_id, trees_info in found.iteritems():
985
1029
            for index in search_indexes:
989
1033
 
990
1034
    def read_working_inventory(self):
991
1035
        """Read the working inventory.
992
 
        
 
1036
 
993
1037
        This is a meaningless operation for dirstate, but we obey it anyhow.
994
1038
        """
995
1039
        return self.inventory
1000
1044
 
1001
1045
        WorkingTree4 supplies revision_trees for any basis tree.
1002
1046
        """
1003
 
        revision_id = osutils.safe_revision_id(revision_id)
1004
1047
        dirstate = self.current_dirstate()
1005
1048
        parent_ids = dirstate.get_parent_ids()
1006
1049
        if revision_id not in parent_ids:
1013
1056
    @needs_tree_write_lock
1014
1057
    def set_last_revision(self, new_revision):
1015
1058
        """Change the last revision in the working tree."""
1016
 
        new_revision = osutils.safe_revision_id(new_revision)
1017
1059
        parents = self.get_parent_ids()
1018
 
        if new_revision in (NULL_REVISION, None):
1019
 
            assert len(parents) < 2, (
1020
 
                "setting the last parent to none with a pending merge is "
1021
 
                "unsupported.")
 
1060
        if new_revision in (_mod_revision.NULL_REVISION, None):
 
1061
            if len(parents) >= 2:
 
1062
                raise AssertionError(
 
1063
                    "setting the last parent to none with a pending merge is "
 
1064
                    "unsupported.")
1022
1065
            self.set_parent_ids([])
1023
1066
        else:
1024
1067
            self.set_parent_ids([new_revision] + parents[1:],
1027
1070
    @needs_tree_write_lock
1028
1071
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1029
1072
        """Set the parent ids to revision_ids.
1030
 
        
 
1073
 
1031
1074
        See also set_parent_trees. This api will try to retrieve the tree data
1032
1075
        for each element of revision_ids from the trees repository. If you have
1033
1076
        tree data already available, it is more efficient to use
1037
1080
        :param revision_ids: The revision_ids to set as the parent ids of this
1038
1081
            working tree. Any of these may be ghosts.
1039
1082
        """
1040
 
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1041
1083
        trees = []
1042
1084
        for revision_id in revision_ids:
1043
1085
            try:
1049
1091
            except (errors.NoSuchRevision, errors.RevisionNotPresent):
1050
1092
                revtree = None
1051
1093
            trees.append((revision_id, revtree))
1052
 
        self.current_dirstate()._validate()
1053
1094
        self.set_parent_trees(trees,
1054
1095
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1055
 
        self.current_dirstate()._validate()
1056
1096
 
1057
1097
    @needs_tree_write_lock
1058
1098
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1063
1103
            parent tree - i.e. a ghost.
1064
1104
        """
1065
1105
        dirstate = self.current_dirstate()
1066
 
        dirstate._validate()
1067
1106
        if len(parents_list) > 0:
1068
1107
            if not allow_leftmost_as_ghost and parents_list[0][1] is None:
1069
1108
                raise errors.GhostRevisionUnusableHere(parents_list[0][0])
1070
1109
        real_trees = []
1071
1110
        ghosts = []
 
1111
 
 
1112
        parent_ids = [rev_id for rev_id, tree in parents_list]
 
1113
        graph = self.branch.repository.get_graph()
 
1114
        heads = graph.heads(parent_ids)
 
1115
        accepted_revisions = set()
 
1116
 
1072
1117
        # convert absent trees to the null tree, which we convert back to
1073
1118
        # missing on access.
1074
1119
        for rev_id, tree in parents_list:
1075
 
            rev_id = osutils.safe_revision_id(rev_id)
 
1120
            if len(accepted_revisions) > 0:
 
1121
                # we always accept the first tree
 
1122
                if rev_id in accepted_revisions or rev_id not in heads:
 
1123
                    # We have already included either this tree, or its
 
1124
                    # descendent, so we skip it.
 
1125
                    continue
 
1126
            _mod_revision.check_not_reserved_id(rev_id)
1076
1127
            if tree is not None:
1077
1128
                real_trees.append((rev_id, tree))
1078
1129
            else:
1079
1130
                real_trees.append((rev_id,
1080
 
                    self.branch.repository.revision_tree(None)))
 
1131
                    self.branch.repository.revision_tree(
 
1132
                        _mod_revision.NULL_REVISION)))
1081
1133
                ghosts.append(rev_id)
1082
 
        dirstate._validate()
1083
 
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
1084
 
        dirstate._validate()
 
1134
            accepted_revisions.add(rev_id)
 
1135
        updated = False
 
1136
        if (len(real_trees) == 1
 
1137
            and not ghosts
 
1138
            and self.branch.repository._format.fast_deltas
 
1139
            and isinstance(real_trees[0][1],
 
1140
                revisiontree.InventoryRevisionTree)
 
1141
            and self.get_parent_ids()):
 
1142
            rev_id, rev_tree = real_trees[0]
 
1143
            basis_id = self.get_parent_ids()[0]
 
1144
            # There are times when basis_tree won't be in
 
1145
            # self.branch.repository, (switch, for example)
 
1146
            try:
 
1147
                basis_tree = self.branch.repository.revision_tree(basis_id)
 
1148
            except errors.NoSuchRevision:
 
1149
                # Fall back to the set_parent_trees(), since we can't use
 
1150
                # _make_delta if we can't get the RevisionTree
 
1151
                pass
 
1152
            else:
 
1153
                delta = rev_tree.inventory._make_delta(basis_tree.inventory)
 
1154
                dirstate.update_basis_by_delta(delta, rev_id)
 
1155
                updated = True
 
1156
        if not updated:
 
1157
            dirstate.set_parent_trees(real_trees, ghosts=ghosts)
1085
1158
        self._make_dirty(reset_inventory=False)
1086
 
        dirstate._validate()
1087
1159
 
1088
1160
    def _set_root_id(self, file_id):
1089
1161
        """See WorkingTree.set_root_id."""
1092
1164
        if state._dirblock_state == dirstate.DirState.IN_MEMORY_MODIFIED:
1093
1165
            self._make_dirty(reset_inventory=True)
1094
1166
 
 
1167
    def _sha_from_stat(self, path, stat_result):
 
1168
        """Get a sha digest from the tree's stat cache.
 
1169
 
 
1170
        The default implementation assumes no stat cache is present.
 
1171
 
 
1172
        :param path: The path.
 
1173
        :param stat_result: The stat result being looked up.
 
1174
        """
 
1175
        return self.current_dirstate().sha1_from_stat(path, stat_result)
 
1176
 
1095
1177
    @needs_read_lock
1096
1178
    def supports_tree_reference(self):
1097
1179
        return self._repo_supports_tree_reference
1099
1181
    def unlock(self):
1100
1182
        """Unlock in format 4 trees needs to write the entire dirstate."""
1101
1183
        if self._control_files._lock_count == 1:
 
1184
            # do non-implementation specific cleanup
 
1185
            self._cleanup()
 
1186
 
1102
1187
            # eventually we should do signature checking during read locks for
1103
1188
            # dirstate updates.
1104
1189
            if self._control_files._lock_mode == 'w':
1134
1219
            return
1135
1220
        state = self.current_dirstate()
1136
1221
        state._read_dirblocks_if_needed()
1137
 
        ids_to_unversion = set()
1138
 
        for file_id in file_ids:
1139
 
            ids_to_unversion.add(osutils.safe_file_id(file_id))
 
1222
        ids_to_unversion = set(file_ids)
1140
1223
        paths_to_unversion = set()
1141
1224
        # sketch:
1142
1225
        # check if the root is to be unversioned, if so, assert for now.
1169
1252
                # just forget the whole block.
1170
1253
                entry_index = 0
1171
1254
                while entry_index < len(block[1]):
1172
 
                    # Mark this file id as having been removed
1173
1255
                    entry = block[1][entry_index]
1174
 
                    ids_to_unversion.discard(entry[0][2])
1175
 
                    if (entry[1][0][0] == 'a'
1176
 
                        or not state._make_absent(entry)):
 
1256
                    if entry[1][0][0] in 'ar':
 
1257
                        # don't remove absent or renamed entries
1177
1258
                        entry_index += 1
 
1259
                    else:
 
1260
                        # Mark this file id as having been removed
 
1261
                        ids_to_unversion.discard(entry[0][2])
 
1262
                        if not state._make_absent(entry):
 
1263
                            # The block has not shrunk.
 
1264
                            entry_index += 1
1178
1265
                # go to the next block. (At the moment we dont delete empty
1179
1266
                # dirblocks)
1180
1267
                block_index += 1
1201
1288
        # have to change the legacy inventory too.
1202
1289
        if self._inventory is not None:
1203
1290
            for file_id in file_ids:
1204
 
                self._inventory.remove_recursive_id(file_id)
 
1291
                if self._inventory.has_id(file_id):
 
1292
                    self._inventory.remove_recursive_id(file_id)
 
1293
 
 
1294
    @needs_tree_write_lock
 
1295
    def rename_one(self, from_rel, to_rel, after=False):
 
1296
        """See WorkingTree.rename_one"""
 
1297
        self.flush()
 
1298
        super(DirStateWorkingTree, self).rename_one(from_rel, to_rel, after)
 
1299
 
 
1300
    @needs_tree_write_lock
 
1301
    def apply_inventory_delta(self, changes):
 
1302
        """See MutableTree.apply_inventory_delta"""
 
1303
        state = self.current_dirstate()
 
1304
        state.update_by_delta(changes)
 
1305
        self._make_dirty(reset_inventory=True)
 
1306
 
 
1307
    def update_basis_by_delta(self, new_revid, delta):
 
1308
        """See MutableTree.update_basis_by_delta."""
 
1309
        if self.last_revision() == new_revid:
 
1310
            raise AssertionError()
 
1311
        self.current_dirstate().update_basis_by_delta(delta, new_revid)
1205
1312
 
1206
1313
    @needs_read_lock
1207
1314
    def _validate(self):
1210
1317
    @needs_tree_write_lock
1211
1318
    def _write_inventory(self, inv):
1212
1319
        """Write inventory as the current inventory."""
1213
 
        assert not self._dirty, "attempting to write an inventory when the dirstate is dirty will cause data loss"
1214
 
        self.current_dirstate().set_state_from_inventory(inv)
1215
 
        self._make_dirty(reset_inventory=False)
1216
 
        if self._inventory is not None:
 
1320
        if self._dirty:
 
1321
            raise AssertionError("attempting to write an inventory when the "
 
1322
                "dirstate is dirty will lose pending changes")
 
1323
        had_inventory = self._inventory is not None
 
1324
        # Setting self._inventory = None forces the dirstate to regenerate the
 
1325
        # working inventory. We do this because self.inventory may be inv, or
 
1326
        # may have been modified, and either case would prevent a clean delta
 
1327
        # being created.
 
1328
        self._inventory = None
 
1329
        # generate a delta,
 
1330
        delta = inv._make_delta(self.inventory)
 
1331
        # and apply it.
 
1332
        self.apply_inventory_delta(delta)
 
1333
        if had_inventory:
1217
1334
            self._inventory = inv
1218
1335
        self.flush()
1219
1336
 
1220
 
 
1221
 
class WorkingTreeFormat4(WorkingTreeFormat3):
1222
 
    """The first consolidated dirstate working tree format.
1223
 
 
1224
 
    This format:
1225
 
        - exists within a metadir controlling .bzr
1226
 
        - includes an explicit version marker for the workingtree control
1227
 
          files, separate from the BzrDir format
1228
 
        - modifies the hash cache format
1229
 
        - is new in bzr 0.15
1230
 
        - uses a LockDir to guard access to it.
1231
 
    """
1232
 
 
1233
 
    upgrade_recommended = False
1234
 
 
1235
 
    def get_format_string(self):
1236
 
        """See WorkingTreeFormat.get_format_string()."""
1237
 
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
1238
 
 
1239
 
    def get_format_description(self):
1240
 
        """See WorkingTreeFormat.get_format_description()."""
1241
 
        return "Working tree format 4"
1242
 
 
1243
 
    def initialize(self, a_bzrdir, revision_id=None):
 
1337
    @needs_tree_write_lock
 
1338
    def reset_state(self, revision_ids=None):
 
1339
        """Reset the state of the working tree.
 
1340
 
 
1341
        This does a hard-reset to a last-known-good state. This is a way to
 
1342
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
 
1343
        """
 
1344
        if revision_ids is None:
 
1345
            revision_ids = self.get_parent_ids()
 
1346
        if not revision_ids:
 
1347
            base_tree = self.branch.repository.revision_tree(
 
1348
                _mod_revision.NULL_REVISION)
 
1349
            trees = []
 
1350
        else:
 
1351
            trees = zip(revision_ids,
 
1352
                        self.branch.repository.revision_trees(revision_ids))
 
1353
            base_tree = trees[0][1]
 
1354
        state = self.current_dirstate()
 
1355
        # We don't support ghosts yet
 
1356
        state.set_state_from_scratch(base_tree.inventory, trees, [])
 
1357
 
 
1358
 
 
1359
class ContentFilterAwareSHA1Provider(dirstate.SHA1Provider):
 
1360
 
 
1361
    def __init__(self, tree):
 
1362
        self.tree = tree
 
1363
 
 
1364
    def sha1(self, abspath):
 
1365
        """See dirstate.SHA1Provider.sha1()."""
 
1366
        filters = self.tree._content_filter_stack(
 
1367
            self.tree.relpath(osutils.safe_unicode(abspath)))
 
1368
        return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
 
1369
 
 
1370
    def stat_and_sha1(self, abspath):
 
1371
        """See dirstate.SHA1Provider.stat_and_sha1()."""
 
1372
        filters = self.tree._content_filter_stack(
 
1373
            self.tree.relpath(osutils.safe_unicode(abspath)))
 
1374
        file_obj = file(abspath, 'rb', 65000)
 
1375
        try:
 
1376
            statvalue = os.fstat(file_obj.fileno())
 
1377
            if filters:
 
1378
                file_obj = _mod_filters.filtered_input_file(file_obj, filters)
 
1379
            sha1 = osutils.size_sha_file(file_obj)[1]
 
1380
        finally:
 
1381
            file_obj.close()
 
1382
        return statvalue, sha1
 
1383
 
 
1384
 
 
1385
class ContentFilteringDirStateWorkingTree(DirStateWorkingTree):
 
1386
    """Dirstate working tree that supports content filtering.
 
1387
 
 
1388
    The dirstate holds the hash and size of the canonical form of the file, 
 
1389
    and most methods must return that.
 
1390
    """
 
1391
 
 
1392
    def _file_content_summary(self, path, stat_result):
 
1393
        # This is to support the somewhat obsolete path_content_summary method
 
1394
        # with content filtering: see
 
1395
        # <https://bugs.launchpad.net/bzr/+bug/415508>.
 
1396
        #
 
1397
        # If the dirstate cache is up to date and knows the hash and size,
 
1398
        # return that.
 
1399
        # Otherwise if there are no content filters, return the on-disk size
 
1400
        # and leave the hash blank.
 
1401
        # Otherwise, read and filter the on-disk file and use its size and
 
1402
        # hash.
 
1403
        #
 
1404
        # The dirstate doesn't store the size of the canonical form so we
 
1405
        # can't trust it for content-filtered trees.  We just return None.
 
1406
        dirstate_sha1 = self._dirstate.sha1_from_stat(path, stat_result)
 
1407
        executable = self._is_executable_from_path_and_stat(path, stat_result)
 
1408
        return ('file', None, executable, dirstate_sha1)
 
1409
 
 
1410
 
 
1411
class WorkingTree4(DirStateWorkingTree):
 
1412
    """This is the Format 4 working tree.
 
1413
 
 
1414
    This differs from WorkingTree by:
 
1415
     - Having a consolidated internal dirstate, stored in a
 
1416
       randomly-accessible sorted file on disk.
 
1417
     - Not having a regular inventory attribute.  One can be synthesized
 
1418
       on demand but this is expensive and should be avoided.
 
1419
 
 
1420
    This is new in bzr 0.15.
 
1421
    """
 
1422
 
 
1423
 
 
1424
class WorkingTree5(ContentFilteringDirStateWorkingTree):
 
1425
    """This is the Format 5 working tree.
 
1426
 
 
1427
    This differs from WorkingTree4 by:
 
1428
     - Supporting content filtering.
 
1429
 
 
1430
    This is new in bzr 1.11.
 
1431
    """
 
1432
 
 
1433
 
 
1434
class WorkingTree6(ContentFilteringDirStateWorkingTree):
 
1435
    """This is the Format 6 working tree.
 
1436
 
 
1437
    This differs from WorkingTree5 by:
 
1438
     - Supporting a current view that may mask the set of files in a tree
 
1439
       impacted by most user operations.
 
1440
 
 
1441
    This is new in bzr 1.14.
 
1442
    """
 
1443
 
 
1444
    def _make_views(self):
 
1445
        return views.PathBasedViews(self)
 
1446
 
 
1447
 
 
1448
class DirStateWorkingTreeFormat(WorkingTreeFormatMetaDir):
 
1449
 
 
1450
    missing_parent_conflicts = True
 
1451
 
 
1452
    supports_versioned_directories = True
 
1453
 
 
1454
    _lock_class = LockDir
 
1455
    _lock_file_name = 'lock'
 
1456
 
 
1457
    def _open_control_files(self, a_bzrdir):
 
1458
        transport = a_bzrdir.get_workingtree_transport(None)
 
1459
        return LockableFiles(transport, self._lock_file_name,
 
1460
                             self._lock_class)
 
1461
 
 
1462
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
1463
                   accelerator_tree=None, hardlink=False):
1244
1464
        """See WorkingTreeFormat.initialize().
1245
1465
 
1246
1466
        :param revision_id: allows creating a working tree at a different
1247
 
        revision than the branch is at.
 
1467
            revision than the branch is at.
 
1468
        :param accelerator_tree: A tree which can be used for retrieving file
 
1469
            contents more quickly than the revision tree, i.e. a workingtree.
 
1470
            The revision tree will be used for cases where accelerator_tree's
 
1471
            content is different.
 
1472
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1473
            where possible.
1248
1474
 
1249
 
        These trees get an initial random root id.
 
1475
        These trees get an initial random root id, if their repository supports
 
1476
        rich root data, TREE_ROOT otherwise.
1250
1477
        """
1251
 
        revision_id = osutils.safe_revision_id(revision_id)
1252
1478
        if not isinstance(a_bzrdir.transport, LocalTransport):
1253
1479
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1254
1480
        transport = a_bzrdir.get_workingtree_transport(self)
1255
1481
        control_files = self._open_control_files(a_bzrdir)
1256
1482
        control_files.create_lock()
1257
1483
        control_files.lock_write()
1258
 
        control_files.put_utf8('format', self.get_format_string())
1259
 
        branch = a_bzrdir.open_branch()
 
1484
        transport.put_bytes('format', self.as_string(),
 
1485
            mode=a_bzrdir._get_file_mode())
 
1486
        if from_branch is not None:
 
1487
            branch = from_branch
 
1488
        else:
 
1489
            branch = a_bzrdir.open_branch()
1260
1490
        if revision_id is None:
1261
1491
            revision_id = branch.last_revision()
1262
1492
        local_path = transport.local_abspath('dirstate')
1264
1494
        state = dirstate.DirState.initialize(local_path)
1265
1495
        state.unlock()
1266
1496
        del state
1267
 
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
 
1497
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
1268
1498
                         branch,
1269
1499
                         _format=self,
1270
1500
                         _bzrdir=a_bzrdir,
1271
1501
                         _control_files=control_files)
1272
1502
        wt._new_tree()
1273
1503
        wt.lock_tree_write()
1274
 
        wt.current_dirstate()._validate()
1275
1504
        try:
1276
 
            if revision_id in (None, NULL_REVISION):
1277
 
                wt._set_root_id(generate_ids.gen_root_id())
 
1505
            self._init_custom_control_files(wt)
 
1506
            if revision_id in (None, _mod_revision.NULL_REVISION):
 
1507
                if branch.repository.supports_rich_root():
 
1508
                    wt._set_root_id(generate_ids.gen_root_id())
 
1509
                else:
 
1510
                    wt._set_root_id(ROOT_ID)
1278
1511
                wt.flush()
1279
 
                wt.current_dirstate()._validate()
1280
 
            wt.set_last_revision(revision_id)
1281
 
            wt.flush()
1282
 
            basis = wt.basis_tree()
 
1512
            basis = None
 
1513
            # frequently, we will get here due to branching.  The accelerator
 
1514
            # tree will be the tree from the branch, so the desired basis
 
1515
            # tree will often be a parent of the accelerator tree.
 
1516
            if accelerator_tree is not None:
 
1517
                try:
 
1518
                    basis = accelerator_tree.revision_tree(revision_id)
 
1519
                except errors.NoSuchRevision:
 
1520
                    pass
 
1521
            if basis is None:
 
1522
                basis = branch.repository.revision_tree(revision_id)
 
1523
            if revision_id == _mod_revision.NULL_REVISION:
 
1524
                parents_list = []
 
1525
            else:
 
1526
                parents_list = [(revision_id, basis)]
1283
1527
            basis.lock_read()
1284
 
            # if the basis has a root id we have to use that; otherwise we use
1285
 
            # a new random one
1286
 
            basis_root_id = basis.get_root_id()
1287
 
            if basis_root_id is not None:
1288
 
                wt._set_root_id(basis_root_id)
 
1528
            try:
 
1529
                wt.set_parent_trees(parents_list, allow_leftmost_as_ghost=True)
1289
1530
                wt.flush()
1290
 
            transform.build_tree(basis, wt)
1291
 
            basis.unlock()
 
1531
                # if the basis has a root id we have to use that; otherwise we
 
1532
                # use a new random one
 
1533
                basis_root_id = basis.get_root_id()
 
1534
                if basis_root_id is not None:
 
1535
                    wt._set_root_id(basis_root_id)
 
1536
                    wt.flush()
 
1537
                if wt.supports_content_filtering():
 
1538
                    # The original tree may not have the same content filters
 
1539
                    # applied so we can't safely build the inventory delta from
 
1540
                    # the source tree.
 
1541
                    delta_from_tree = False
 
1542
                else:
 
1543
                    delta_from_tree = True
 
1544
                # delta_from_tree is safe even for DirStateRevisionTrees,
 
1545
                # because wt4.apply_inventory_delta does not mutate the input
 
1546
                # inventory entries.
 
1547
                transform.build_tree(basis, wt, accelerator_tree,
 
1548
                                     hardlink=hardlink,
 
1549
                                     delta_from_tree=delta_from_tree)
 
1550
                for hook in MutableTree.hooks['post_build_tree']:
 
1551
                    hook(wt)
 
1552
            finally:
 
1553
                basis.unlock()
1292
1554
        finally:
1293
1555
            control_files.unlock()
1294
1556
            wt.unlock()
1295
1557
        return wt
1296
1558
 
 
1559
    def _init_custom_control_files(self, wt):
 
1560
        """Subclasses with custom control files should override this method.
 
1561
 
 
1562
        The working tree and control files are locked for writing when this
 
1563
        method is called.
 
1564
 
 
1565
        :param wt: the WorkingTree object
 
1566
        """
 
1567
 
 
1568
    def open(self, a_bzrdir, _found=False):
 
1569
        """Return the WorkingTree object for a_bzrdir
 
1570
 
 
1571
        _found is a private parameter, do not use it. It is used to indicate
 
1572
               if format probing has already been done.
 
1573
        """
 
1574
        if not _found:
 
1575
            # we are being called directly and must probe.
 
1576
            raise NotImplementedError
 
1577
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
1578
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
1579
        wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
1580
        return wt
 
1581
 
1297
1582
    def _open(self, a_bzrdir, control_files):
1298
1583
        """Open the tree itself.
1299
1584
 
1300
1585
        :param a_bzrdir: the dir for the tree.
1301
1586
        :param control_files: the control files for the tree.
1302
1587
        """
1303
 
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
 
1588
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
1304
1589
                           branch=a_bzrdir.open_branch(),
1305
1590
                           _format=self,
1306
1591
                           _bzrdir=a_bzrdir,
1307
1592
                           _control_files=control_files)
1308
1593
 
1309
1594
    def __get_matchingbzrdir(self):
 
1595
        return self._get_matchingbzrdir()
 
1596
 
 
1597
    def _get_matchingbzrdir(self):
 
1598
        """Overrideable method to get a bzrdir for testing."""
1310
1599
        # please test against something that will let us do tree references
1311
1600
        return bzrdir.format_registry.make_bzrdir(
1312
1601
            'dirstate-with-subtree')
1314
1603
    _matchingbzrdir = property(__get_matchingbzrdir)
1315
1604
 
1316
1605
 
1317
 
class DirStateRevisionTree(Tree):
1318
 
    """A revision tree pulling the inventory from a dirstate."""
 
1606
class WorkingTreeFormat4(DirStateWorkingTreeFormat):
 
1607
    """The first consolidated dirstate working tree format.
 
1608
 
 
1609
    This format:
 
1610
        - exists within a metadir controlling .bzr
 
1611
        - includes an explicit version marker for the workingtree control
 
1612
          files, separate from the ControlDir format
 
1613
        - modifies the hash cache format
 
1614
        - is new in bzr 0.15
 
1615
        - uses a LockDir to guard access to it.
 
1616
    """
 
1617
 
 
1618
    upgrade_recommended = False
 
1619
 
 
1620
    _tree_class = WorkingTree4
 
1621
 
 
1622
    @classmethod
 
1623
    def get_format_string(cls):
 
1624
        """See WorkingTreeFormat.get_format_string()."""
 
1625
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
 
1626
 
 
1627
    def get_format_description(self):
 
1628
        """See WorkingTreeFormat.get_format_description()."""
 
1629
        return "Working tree format 4"
 
1630
 
 
1631
 
 
1632
class WorkingTreeFormat5(DirStateWorkingTreeFormat):
 
1633
    """WorkingTree format supporting content filtering.
 
1634
    """
 
1635
 
 
1636
    upgrade_recommended = False
 
1637
 
 
1638
    _tree_class = WorkingTree5
 
1639
 
 
1640
    @classmethod
 
1641
    def get_format_string(cls):
 
1642
        """See WorkingTreeFormat.get_format_string()."""
 
1643
        return "Bazaar Working Tree Format 5 (bzr 1.11)\n"
 
1644
 
 
1645
    def get_format_description(self):
 
1646
        """See WorkingTreeFormat.get_format_description()."""
 
1647
        return "Working tree format 5"
 
1648
 
 
1649
    def supports_content_filtering(self):
 
1650
        return True
 
1651
 
 
1652
 
 
1653
class WorkingTreeFormat6(DirStateWorkingTreeFormat):
 
1654
    """WorkingTree format supporting views.
 
1655
    """
 
1656
 
 
1657
    upgrade_recommended = False
 
1658
 
 
1659
    _tree_class = WorkingTree6
 
1660
 
 
1661
    @classmethod
 
1662
    def get_format_string(cls):
 
1663
        """See WorkingTreeFormat.get_format_string()."""
 
1664
        return "Bazaar Working Tree Format 6 (bzr 1.14)\n"
 
1665
 
 
1666
    def get_format_description(self):
 
1667
        """See WorkingTreeFormat.get_format_description()."""
 
1668
        return "Working tree format 6"
 
1669
 
 
1670
    def _init_custom_control_files(self, wt):
 
1671
        """Subclasses with custom control files should override this method."""
 
1672
        wt._transport.put_bytes('views', '', mode=wt.bzrdir._get_file_mode())
 
1673
 
 
1674
    def supports_content_filtering(self):
 
1675
        return True
 
1676
 
 
1677
    def supports_views(self):
 
1678
        return True
 
1679
 
 
1680
    def _get_matchingbzrdir(self):
 
1681
        """Overrideable method to get a bzrdir for testing."""
 
1682
        # We use 'development-subtree' instead of '2a', because we have a
 
1683
        # few tests that want to test tree references
 
1684
        return bzrdir.format_registry.make_bzrdir('development-subtree')
 
1685
 
 
1686
 
 
1687
class DirStateRevisionTree(InventoryTree):
 
1688
    """A revision tree pulling the inventory from a dirstate.
 
1689
    
 
1690
    Note that this is one of the historical (ie revision) trees cached in the
 
1691
    dirstate for easy access, not the workingtree.
 
1692
    """
1319
1693
 
1320
1694
    def __init__(self, dirstate, revision_id, repository):
1321
1695
        self._dirstate = dirstate
1322
 
        self._revision_id = osutils.safe_revision_id(revision_id)
 
1696
        self._revision_id = revision_id
1323
1697
        self._repository = repository
1324
1698
        self._inventory = None
1325
1699
        self._locked = 0
1326
1700
        self._dirstate_locked = False
 
1701
        self._repo_supports_tree_reference = getattr(
 
1702
            repository._format, "supports_tree_reference",
 
1703
            False)
1327
1704
 
1328
1705
    def __repr__(self):
1329
1706
        return "<%s of %s in %s>" % \
1330
1707
            (self.__class__.__name__, self._revision_id, self._dirstate)
1331
1708
 
1332
 
    def annotate_iter(self, file_id):
 
1709
    def annotate_iter(self, file_id,
 
1710
                      default_revision=_mod_revision.CURRENT_REVISION):
1333
1711
        """See Tree.annotate_iter"""
1334
 
        w = self._repository.weave_store.get_weave(file_id,
1335
 
                           self._repository.get_transaction())
1336
 
        return w.annotate_iter(self.inventory[file_id].revision)
 
1712
        text_key = (file_id, self.get_file_revision(file_id))
 
1713
        annotations = self._repository.texts.annotate(text_key)
 
1714
        return [(key[-1], line) for (key, line) in annotations]
1337
1715
 
1338
1716
    def _comparison_data(self, entry, path):
1339
1717
        """See Tree._comparison_data."""
1357
1735
    def get_root_id(self):
1358
1736
        return self.path2id('')
1359
1737
 
 
1738
    def id2path(self, file_id):
 
1739
        "Convert a file-id to a path."
 
1740
        entry = self._get_entry(file_id=file_id)
 
1741
        if entry == (None, None):
 
1742
            raise errors.NoSuchId(tree=self, file_id=file_id)
 
1743
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
 
1744
        return path_utf8.decode('utf8')
 
1745
 
 
1746
    def iter_references(self):
 
1747
        if not self._repo_supports_tree_reference:
 
1748
            # When the repo doesn't support references, we will have nothing to
 
1749
            # return
 
1750
            return iter([])
 
1751
        # Otherwise, fall back to the default implementation
 
1752
        return super(DirStateRevisionTree, self).iter_references()
 
1753
 
1360
1754
    def _get_parent_index(self):
1361
1755
        """Return the index in the dirstate referenced by this tree."""
1362
1756
        return self._dirstate.get_parent_ids().index(self._revision_id) + 1
1367
1761
        If either file_id or path is supplied, it is used as the key to lookup.
1368
1762
        If both are supplied, the fastest lookup is used, and an error is
1369
1763
        raised if they do not both point at the same row.
1370
 
        
 
1764
 
1371
1765
        :param file_id: An optional unicode file_id to be looked up.
1372
1766
        :param path: An optional unicode path to be looked up.
1373
1767
        :return: The dirstate row tuple for path/file_id, or (None, None)
1374
1768
        """
1375
1769
        if file_id is None and path is None:
1376
1770
            raise errors.BzrError('must supply file_id or path')
1377
 
        file_id = osutils.safe_file_id(file_id)
1378
1771
        if path is not None:
1379
1772
            path = path.encode('utf8')
1380
1773
        parent_index = self._get_parent_index()
1388
1781
 
1389
1782
        This is relatively expensive: we have to walk the entire dirstate.
1390
1783
        """
1391
 
        assert self._locked, 'cannot generate inventory of an unlocked '\
1392
 
            'dirstate revision tree'
 
1784
        if not self._locked:
 
1785
            raise AssertionError(
 
1786
                'cannot generate inventory of an unlocked '
 
1787
                'dirstate revision tree')
1393
1788
        # separate call for profiling - makes it clear where the costs are.
1394
1789
        self._dirstate._read_dirblocks_if_needed()
1395
 
        assert self._revision_id in self._dirstate.get_parent_ids(), \
1396
 
            'parent %s has disappeared from %s' % (
1397
 
            self._revision_id, self._dirstate.get_parent_ids())
 
1790
        if self._revision_id not in self._dirstate.get_parent_ids():
 
1791
            raise AssertionError(
 
1792
                'parent %s has disappeared from %s' % (
 
1793
                self._revision_id, self._dirstate.get_parent_ids()))
1398
1794
        parent_index = self._dirstate.get_parent_ids().index(self._revision_id) + 1
1399
1795
        # This is identical now to the WorkingTree _generate_inventory except
1400
1796
        # for the tree index use.
1401
1797
        root_key, current_entry = self._dirstate._get_entry(parent_index, path_utf8='')
1402
1798
        current_id = root_key[2]
1403
 
        assert current_entry[parent_index][0] == 'd'
 
1799
        if current_entry[parent_index][0] != 'd':
 
1800
            raise AssertionError()
1404
1801
        inv = Inventory(root_id=current_id, revision_id=self._revision_id)
1405
1802
        inv.root.revision = current_entry[parent_index][4]
1406
1803
        # Turn some things into local variables
1437
1834
                elif kind == 'directory':
1438
1835
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
1439
1836
                elif kind == 'symlink':
1440
 
                    inv_entry.executable = False
1441
 
                    inv_entry.text_size = None
1442
1837
                    inv_entry.symlink_target = utf8_decode(fingerprint)[0]
1443
1838
                elif kind == 'tree-reference':
1444
1839
                    inv_entry.reference_revision = fingerprint or None
1446
1841
                    raise AssertionError("cannot convert entry %r into an InventoryEntry"
1447
1842
                            % entry)
1448
1843
                # These checks cost us around 40ms on a 55k entry tree
1449
 
                assert file_id not in inv_byid
1450
 
                assert name_unicode not in parent_ie.children
 
1844
                if file_id in inv_byid:
 
1845
                    raise AssertionError('file_id %s already in'
 
1846
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
 
1847
                if name_unicode in parent_ie.children:
 
1848
                    raise AssertionError('name %r already in parent'
 
1849
                        % (name_unicode,))
1451
1850
                inv_byid[file_id] = inv_entry
1452
1851
                parent_ie.children[name_unicode] = inv_entry
1453
1852
        self._inventory = inv
1460
1859
        # Make sure the file exists
1461
1860
        entry = self._get_entry(file_id, path=path)
1462
1861
        if entry == (None, None): # do we raise?
1463
 
            return None
 
1862
            raise errors.NoSuchId(self, file_id)
1464
1863
        parent_index = self._get_parent_index()
1465
1864
        last_changed_revision = entry[1][parent_index][4]
1466
 
        return self._repository.get_revision(last_changed_revision).timestamp
 
1865
        try:
 
1866
            rev = self._repository.get_revision(last_changed_revision)
 
1867
        except errors.NoSuchRevision:
 
1868
            raise errors.FileTimestampUnavailable(self.id2path(file_id))
 
1869
        return rev.timestamp
1467
1870
 
1468
1871
    def get_file_sha1(self, file_id, path=None, stat_value=None):
1469
1872
        entry = self._get_entry(file_id=file_id, path=path)
1473
1876
            return parent_details[1]
1474
1877
        return None
1475
1878
 
1476
 
    def get_file(self, file_id):
 
1879
    @needs_read_lock
 
1880
    def get_file_revision(self, file_id):
 
1881
        return self.inventory[file_id].revision
 
1882
 
 
1883
    def get_file(self, file_id, path=None):
1477
1884
        return StringIO(self.get_file_text(file_id))
1478
1885
 
1479
 
    def get_file_lines(self, file_id):
1480
 
        ie = self.inventory[file_id]
1481
 
        return self._repository.weave_store.get_weave(file_id,
1482
 
                self._repository.get_transaction()).get_lines(ie.revision)
1483
 
 
1484
1886
    def get_file_size(self, file_id):
 
1887
        """See Tree.get_file_size"""
1485
1888
        return self.inventory[file_id].text_size
1486
1889
 
1487
 
    def get_file_text(self, file_id):
1488
 
        return ''.join(self.get_file_lines(file_id))
 
1890
    def get_file_text(self, file_id, path=None):
 
1891
        content = None
 
1892
        for _, content_iter in self.iter_files_bytes([(file_id, None)]):
 
1893
            if content is not None:
 
1894
                raise AssertionError('iter_files_bytes returned'
 
1895
                    ' too many entries')
 
1896
            # For each entry returned by iter_files_bytes, we must consume the
 
1897
            # content_iter before we step the files iterator.
 
1898
            content = ''.join(content_iter)
 
1899
        if content is None:
 
1900
            raise AssertionError('iter_files_bytes did not return'
 
1901
                ' the requested data')
 
1902
        return content
1489
1903
 
1490
1904
    def get_reference_revision(self, file_id, path=None):
1491
1905
        return self.inventory[file_id].reference_revision
1492
1906
 
1493
 
    def get_symlink_target(self, file_id):
 
1907
    def iter_files_bytes(self, desired_files):
 
1908
        """See Tree.iter_files_bytes.
 
1909
 
 
1910
        This version is implemented on top of Repository.iter_files_bytes"""
 
1911
        parent_index = self._get_parent_index()
 
1912
        repo_desired_files = []
 
1913
        for file_id, identifier in desired_files:
 
1914
            entry = self._get_entry(file_id)
 
1915
            if entry == (None, None):
 
1916
                raise errors.NoSuchId(self, file_id)
 
1917
            repo_desired_files.append((file_id, entry[1][parent_index][4],
 
1918
                                       identifier))
 
1919
        return self._repository.iter_files_bytes(repo_desired_files)
 
1920
 
 
1921
    def get_symlink_target(self, file_id, path=None):
1494
1922
        entry = self._get_entry(file_id=file_id)
1495
1923
        parent_index = self._get_parent_index()
1496
1924
        if entry[1][parent_index][0] != 'l':
1497
1925
            return None
1498
1926
        else:
1499
 
            # At present, none of the tree implementations supports non-ascii
1500
 
            # symlink targets. So we will just assume that the dirstate path is
1501
 
            # correct.
1502
 
            return entry[1][parent_index][1]
 
1927
            target = entry[1][parent_index][1]
 
1928
            target = target.decode('utf8')
 
1929
            return target
1503
1930
 
1504
1931
    def get_revision_id(self):
1505
1932
        """Return the revision id for this tree."""
1523
1950
        return bool(self.path2id(filename))
1524
1951
 
1525
1952
    def kind(self, file_id):
1526
 
        return self.inventory[file_id].kind
 
1953
        entry = self._get_entry(file_id=file_id)[1]
 
1954
        if entry is None:
 
1955
            raise errors.NoSuchId(tree=self, file_id=file_id)
 
1956
        parent_index = self._get_parent_index()
 
1957
        return dirstate.DirState._minikind_to_kind[entry[parent_index][0]]
 
1958
 
 
1959
    def stored_kind(self, file_id):
 
1960
        """See Tree.stored_kind"""
 
1961
        return self.kind(file_id)
 
1962
 
 
1963
    def path_content_summary(self, path):
 
1964
        """See Tree.path_content_summary."""
 
1965
        id = self.inventory.path2id(path)
 
1966
        if id is None:
 
1967
            return ('missing', None, None, None)
 
1968
        entry = self._inventory[id]
 
1969
        kind = entry.kind
 
1970
        if kind == 'file':
 
1971
            return (kind, entry.text_size, entry.executable, entry.text_sha1)
 
1972
        elif kind == 'symlink':
 
1973
            return (kind, None, None, entry.symlink_target)
 
1974
        else:
 
1975
            return (kind, None, None, None)
1527
1976
 
1528
1977
    def is_executable(self, file_id, path=None):
1529
1978
        ie = self.inventory[file_id]
1530
1979
        if ie.kind != "file":
1531
 
            return None
 
1980
            return False
1532
1981
        return ie.executable
1533
1982
 
1534
 
    def list_files(self, include_root=False):
 
1983
    def is_locked(self):
 
1984
        return self._locked
 
1985
 
 
1986
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1535
1987
        # We use a standard implementation, because DirStateRevisionTree is
1536
1988
        # dealing with one of the parents of the current state
1537
1989
        inv = self._get_inventory()
1538
 
        entries = inv.iter_entries()
1539
 
        if self.inventory.root is not None and not include_root:
 
1990
        if from_dir is None:
 
1991
            from_dir_id = None
 
1992
        else:
 
1993
            from_dir_id = inv.path2id(from_dir)
 
1994
            if from_dir_id is None:
 
1995
                # Directory not versioned
 
1996
                return
 
1997
        entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
 
1998
        if inv.root is not None and not include_root and from_dir is None:
1540
1999
            entries.next()
1541
2000
        for path, entry in entries:
1542
2001
            yield path, 'V', entry.kind, entry.file_id, entry
1543
2002
 
1544
2003
    def lock_read(self):
1545
 
        """Lock the tree for a set of operations."""
 
2004
        """Lock the tree for a set of operations.
 
2005
 
 
2006
        :return: A bzrlib.lock.LogicalLockResult.
 
2007
        """
1546
2008
        if not self._locked:
1547
2009
            self._repository.lock_read()
1548
2010
            if self._dirstate._lock_token is None:
1549
2011
                self._dirstate.lock_read()
1550
2012
                self._dirstate_locked = True
1551
2013
        self._locked += 1
 
2014
        return LogicalLockResult(self.unlock)
1552
2015
 
1553
2016
    def _must_be_locked(self):
1554
2017
        if not self._locked:
1575
2038
                self._dirstate_locked = False
1576
2039
            self._repository.unlock()
1577
2040
 
 
2041
    @needs_read_lock
 
2042
    def supports_tree_reference(self):
 
2043
        return self._repo_supports_tree_reference
 
2044
 
1578
2045
    def walkdirs(self, prefix=""):
1579
2046
        # TODO: jam 20070215 This is the lazy way by using the RevisionTree
1580
 
        # implementation based on an inventory.  
 
2047
        # implementation based on an inventory.
1581
2048
        # This should be cleaned up to use the much faster Dirstate code
1582
2049
        # So for now, we just build up the parent inventory, and extract
1583
2050
        # it the same way RevisionTree does.
1612
2079
 
1613
2080
class InterDirStateTree(InterTree):
1614
2081
    """Fast path optimiser for changes_from with dirstate trees.
1615
 
    
1616
 
    This is used only when both trees are in the dirstate working file, and 
1617
 
    the source is any parent within the dirstate, and the destination is 
 
2082
 
 
2083
    This is used only when both trees are in the dirstate working file, and
 
2084
    the source is any parent within the dirstate, and the destination is
1618
2085
    the current working tree of the same dirstate.
1619
2086
    """
1620
2087
    # this could be generalized to allow comparisons between any trees in the
1629
2096
    def make_source_parent_tree(source, target):
1630
2097
        """Change the source tree into a parent of the target."""
1631
2098
        revid = source.commit('record tree')
1632
 
        target.branch.repository.fetch(source.branch.repository, revid)
 
2099
        target.branch.fetch(source.branch, revid)
1633
2100
        target.set_parent_ids([revid])
1634
2101
        return target.basis_tree(), target
1635
2102
 
 
2103
    @classmethod
 
2104
    def make_source_parent_tree_python_dirstate(klass, test_case, source, target):
 
2105
        result = klass.make_source_parent_tree(source, target)
 
2106
        result[1]._iter_changes = dirstate.ProcessEntryPython
 
2107
        return result
 
2108
 
 
2109
    @classmethod
 
2110
    def make_source_parent_tree_compiled_dirstate(klass, test_case, source,
 
2111
                                                  target):
 
2112
        from bzrlib.tests.test__dirstate_helpers import \
 
2113
            compiled_dirstate_helpers_feature
 
2114
        test_case.requireFeature(compiled_dirstate_helpers_feature)
 
2115
        from bzrlib._dirstate_helpers_pyx import ProcessEntryC
 
2116
        result = klass.make_source_parent_tree(source, target)
 
2117
        result[1]._iter_changes = ProcessEntryC
 
2118
        return result
 
2119
 
1636
2120
    _matching_from_tree_format = WorkingTreeFormat4()
1637
2121
    _matching_to_tree_format = WorkingTreeFormat4()
1638
 
    _test_mutable_trees_to_test_trees = make_source_parent_tree
1639
 
 
1640
 
    def _iter_changes(self, include_unchanged=False,
 
2122
 
 
2123
    @classmethod
 
2124
    def _test_mutable_trees_to_test_trees(klass, test_case, source, target):
 
2125
        # This method shouldn't be called, because we have python and C
 
2126
        # specific flavours.
 
2127
        raise NotImplementedError
 
2128
 
 
2129
    def iter_changes(self, include_unchanged=False,
1641
2130
                      specific_files=None, pb=None, extra_trees=[],
1642
2131
                      require_versioned=True, want_unversioned=False):
1643
2132
        """Return the changes from source to target.
1644
2133
 
1645
 
        :return: An iterator that yields tuples. See InterTree._iter_changes
 
2134
        :return: An iterator that yields tuples. See InterTree.iter_changes
1646
2135
            for details.
1647
2136
        :param specific_files: An optional list of file paths to restrict the
1648
2137
            comparison to. When mapping filenames to ids, all matches in all
1659
2148
            output. An unversioned file is defined as one with (False, False)
1660
2149
            for the versioned pair.
1661
2150
        """
1662
 
        utf8_decode_or_none = cache_utf8._utf8_decode_with_None
1663
 
        _minikind_to_kind = dirstate.DirState._minikind_to_kind
1664
 
        # NB: show_status depends on being able to pass in non-versioned files
1665
 
        # and report them as unknown
1666
2151
        # TODO: handle extra trees in the dirstate.
1667
 
        # TODO: handle comparisons as an empty tree as a different special
1668
 
        # case? mbp 20070226
1669
 
        if extra_trees or (self.source._revision_id == NULL_REVISION):
 
2152
        if (extra_trees or specific_files == []):
1670
2153
            # we can't fast-path these cases (yet)
1671
 
            for f in super(InterDirStateTree, self)._iter_changes(
 
2154
            return super(InterDirStateTree, self).iter_changes(
1672
2155
                include_unchanged, specific_files, pb, extra_trees,
1673
 
                require_versioned, want_unversioned=want_unversioned):
1674
 
                yield f
1675
 
            return
 
2156
                require_versioned, want_unversioned=want_unversioned)
1676
2157
        parent_ids = self.target.get_parent_ids()
1677
 
        assert (self.source._revision_id in parent_ids), \
1678
 
                "revision {%s} is not stored in {%s}, but %s " \
1679
 
                "can only be used for trees stored in the dirstate" \
1680
 
                % (self.source._revision_id, self.target, self._iter_changes)
 
2158
        if not (self.source._revision_id in parent_ids
 
2159
                or self.source._revision_id == _mod_revision.NULL_REVISION):
 
2160
            raise AssertionError(
 
2161
                "revision {%s} is not stored in {%s}, but %s "
 
2162
                "can only be used for trees stored in the dirstate"
 
2163
                % (self.source._revision_id, self.target, self.iter_changes))
1681
2164
        target_index = 0
1682
 
        if self.source._revision_id == NULL_REVISION:
 
2165
        if self.source._revision_id == _mod_revision.NULL_REVISION:
1683
2166
            source_index = None
1684
2167
            indices = (target_index,)
1685
2168
        else:
1686
 
            assert (self.source._revision_id in parent_ids), \
1687
 
                "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
1688
 
                self.source._revision_id, parent_ids)
 
2169
            if not (self.source._revision_id in parent_ids):
 
2170
                raise AssertionError(
 
2171
                    "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
 
2172
                    self.source._revision_id, parent_ids))
1689
2173
            source_index = 1 + parent_ids.index(self.source._revision_id)
1690
 
            indices = (source_index,target_index)
 
2174
            indices = (source_index, target_index)
1691
2175
        # -- make all specific_files utf8 --
1692
2176
        if specific_files:
1693
2177
            specific_files_utf8 = set()
1694
2178
            for path in specific_files:
 
2179
                # Note, if there are many specific files, using cache_utf8
 
2180
                # would be good here.
1695
2181
                specific_files_utf8.add(path.encode('utf8'))
1696
2182
            specific_files = specific_files_utf8
1697
2183
        else:
1698
2184
            specific_files = set([''])
1699
2185
        # -- specific_files is now a utf8 path set --
 
2186
 
1700
2187
        # -- get the state object and prepare it.
1701
2188
        state = self.target.current_dirstate()
1702
2189
        state._read_dirblocks_if_needed()
1703
 
        def _entries_for_path(path):
1704
 
            """Return a list with all the entries that match path for all ids.
1705
 
            """
1706
 
            dirname, basename = os.path.split(path)
1707
 
            key = (dirname, basename, '')
1708
 
            block_index, present = state._find_block_index_from_key(key)
1709
 
            if not present:
1710
 
                # the block which should contain path is absent.
1711
 
                return []
1712
 
            result = []
1713
 
            block = state._dirblocks[block_index][1]
1714
 
            entry_index, _ = state._find_entry_index(key, block)
1715
 
            # we may need to look at multiple entries at this path: walk while the specific_files match.
1716
 
            while (entry_index < len(block) and
1717
 
                block[entry_index][0][0:2] == key[0:2]):
1718
 
                result.append(block[entry_index])
1719
 
                entry_index += 1
1720
 
            return result
1721
2190
        if require_versioned:
1722
2191
            # -- check all supplied paths are versioned in a search tree. --
1723
 
            all_versioned = True
 
2192
            not_versioned = []
1724
2193
            for path in specific_files:
1725
 
                path_entries = _entries_for_path(path)
 
2194
                path_entries = state._entries_for_path(path)
1726
2195
                if not path_entries:
1727
2196
                    # this specified path is not present at all: error
1728
 
                    all_versioned = False
1729
 
                    break
 
2197
                    not_versioned.append(path.decode('utf-8'))
 
2198
                    continue
1730
2199
                found_versioned = False
1731
2200
                # for each id at this path
1732
2201
                for entry in path_entries:
1739
2208
                if not found_versioned:
1740
2209
                    # none of the indexes was not 'absent' at all ids for this
1741
2210
                    # path.
1742
 
                    all_versioned = False
1743
 
                    break
1744
 
            if not all_versioned:
1745
 
                raise errors.PathsNotVersionedError(specific_files)
 
2211
                    not_versioned.append(path.decode('utf-8'))
 
2212
            if len(not_versioned) > 0:
 
2213
                raise errors.PathsNotVersionedError(not_versioned)
1746
2214
        # -- remove redundancy in supplied specific_files to prevent over-scanning --
1747
 
        search_specific_files = set()
1748
 
        for path in specific_files:
1749
 
            other_specific_files = specific_files.difference(set([path]))
1750
 
            if not osutils.is_inside_any(other_specific_files, path):
1751
 
                # this is a top level path, we must check it.
1752
 
                search_specific_files.add(path)
1753
 
        # sketch: 
1754
 
        # compare source_index and target_index at or under each element of search_specific_files.
1755
 
        # follow the following comparison table. Note that we only want to do diff operations when
1756
 
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
1757
 
        # for the target.
1758
 
        # cases:
1759
 
        # 
1760
 
        # Source | Target | disk | action
1761
 
        #   r    | fdlt   |      | add source to search, add id path move and perform
1762
 
        #        |        |      | diff check on source-target
1763
 
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
1764
 
        #        |        |      | ???
1765
 
        #   r    |  a     |      | add source to search
1766
 
        #   r    |  a     |  a   | 
1767
 
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
1768
 
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
1769
 
        #   a    | fdlt   |      | add new id
1770
 
        #   a    | fdlt   |  a   | dangling locally added file, skip
1771
 
        #   a    |  a     |      | not present in either tree, skip
1772
 
        #   a    |  a     |  a   | not present in any tree, skip
1773
 
        #   a    |  r     |      | not present in either tree at this path, skip as it
1774
 
        #        |        |      | may not be selected by the users list of paths.
1775
 
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
1776
 
        #        |        |      | may not be selected by the users list of paths.
1777
 
        #  fdlt  | fdlt   |      | content in both: diff them
1778
 
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
1779
 
        #  fdlt  |  a     |      | unversioned: output deleted id for now
1780
 
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
1781
 
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
1782
 
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1783
 
        #        |        |      | this id at the other path.
1784
 
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
1785
 
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1786
 
        #        |        |      | this id at the other path.
1787
 
 
1788
 
        # for all search_indexs in each path at or under each element of
1789
 
        # search_specific_files, if the detail is relocated: add the id, and add the
1790
 
        # relocated path as one to search if its not searched already. If the
1791
 
        # detail is not relocated, add the id.
1792
 
        searched_specific_files = set()
1793
 
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
1794
 
        # Using a list so that we can access the values and change them in
1795
 
        # nested scope. Each one is [path, file_id, entry]
1796
 
        last_source_parent = [None, None, None]
1797
 
        last_target_parent = [None, None, None]
 
2215
        search_specific_files = osutils.minimum_path_selection(specific_files)
1798
2216
 
1799
2217
        use_filesystem_for_exec = (sys.platform != 'win32')
1800
 
 
1801
 
        def _process_entry(entry, path_info):
1802
 
            """Compare an entry and real disk to generate delta information.
1803
 
 
1804
 
            :param path_info: top_relpath, basename, kind, lstat, abspath for
1805
 
                the path of entry. If None, then the path is considered absent.
1806
 
                (Perhaps we should pass in a concrete entry for this ?)
1807
 
                Basename is returned as a utf8 string because we expect this
1808
 
                tuple will be ignored, and don't want to take the time to
1809
 
                decode.
1810
 
            """
1811
 
            if source_index is None:
1812
 
                source_details = NULL_PARENT_DETAILS
1813
 
            else:
1814
 
                source_details = entry[1][source_index]
1815
 
            target_details = entry[1][target_index]
1816
 
            target_minikind = target_details[0]
1817
 
            if path_info is not None and target_minikind in 'fdlt':
1818
 
                assert target_index == 0
1819
 
                link_or_sha1 = state.update_entry(entry, abspath=path_info[4],
1820
 
                                                  stat_value=path_info[3])
1821
 
                # The entry may have been modified by update_entry
1822
 
                target_details = entry[1][target_index]
1823
 
                target_minikind = target_details[0]
1824
 
            else:
1825
 
                link_or_sha1 = None
1826
 
            source_minikind = source_details[0]
1827
 
            if source_minikind in 'fdltr' and target_minikind in 'fdlt':
1828
 
                # claimed content in both: diff
1829
 
                #   r    | fdlt   |      | add source to search, add id path move and perform
1830
 
                #        |        |      | diff check on source-target
1831
 
                #   r    | fdlt   |  a   | dangling file that was present in the basis.
1832
 
                #        |        |      | ???
1833
 
                if source_minikind in 'r':
1834
 
                    # add the source to the search path to find any children it
1835
 
                    # has.  TODO ? : only add if it is a container ?
1836
 
                    if not osutils.is_inside_any(searched_specific_files,
1837
 
                                                 source_details[1]):
1838
 
                        search_specific_files.add(source_details[1])
1839
 
                    # generate the old path; this is needed for stating later
1840
 
                    # as well.
1841
 
                    old_path = source_details[1]
1842
 
                    old_dirname, old_basename = os.path.split(old_path)
1843
 
                    path = pathjoin(entry[0][0], entry[0][1])
1844
 
                    old_entry = state._get_entry(source_index,
1845
 
                                                 path_utf8=old_path)
1846
 
                    # update the source details variable to be the real
1847
 
                    # location.
1848
 
                    source_details = old_entry[1][source_index]
1849
 
                    source_minikind = source_details[0]
1850
 
                else:
1851
 
                    old_dirname = entry[0][0]
1852
 
                    old_basename = entry[0][1]
1853
 
                    old_path = path = pathjoin(old_dirname, old_basename)
1854
 
                if path_info is None:
1855
 
                    # the file is missing on disk, show as removed.
1856
 
                    content_change = True
1857
 
                    target_kind = None
1858
 
                    target_exec = False
1859
 
                else:
1860
 
                    # source and target are both versioned and disk file is present.
1861
 
                    target_kind = path_info[2]
1862
 
                    if target_kind == 'directory':
1863
 
                        if source_minikind != 'd':
1864
 
                            content_change = True
1865
 
                        else:
1866
 
                            # directories have no fingerprint
1867
 
                            content_change = False
1868
 
                        target_exec = False
1869
 
                    elif target_kind == 'file':
1870
 
                        if source_minikind != 'f':
1871
 
                            content_change = True
1872
 
                        else:
1873
 
                            # We could check the size, but we already have the
1874
 
                            # sha1 hash.
1875
 
                            content_change = (link_or_sha1 != source_details[1])
1876
 
                        # Target details is updated at update_entry time
1877
 
                        if use_filesystem_for_exec:
1878
 
                            # We don't need S_ISREG here, because we are sure
1879
 
                            # we are dealing with a file.
1880
 
                            target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
1881
 
                        else:
1882
 
                            target_exec = target_details[3]
1883
 
                    elif target_kind == 'symlink':
1884
 
                        if source_minikind != 'l':
1885
 
                            content_change = True
1886
 
                        else:
1887
 
                            content_change = (link_or_sha1 != source_details[1])
1888
 
                        target_exec = False
1889
 
                    elif target_kind == 'tree-reference':
1890
 
                        if source_minikind != 't':
1891
 
                            content_change = True
1892
 
                        else:
1893
 
                            content_change = False
1894
 
                        target_exec = False
1895
 
                    else:
1896
 
                        raise Exception, "unknown kind %s" % path_info[2]
1897
 
                # parent id is the entry for the path in the target tree
1898
 
                if old_dirname == last_source_parent[0]:
1899
 
                    source_parent_id = last_source_parent[1]
1900
 
                else:
1901
 
                    source_parent_entry = state._get_entry(source_index,
1902
 
                                                           path_utf8=old_dirname)
1903
 
                    source_parent_id = source_parent_entry[0][2]
1904
 
                    if source_parent_id == entry[0][2]:
1905
 
                        # This is the root, so the parent is None
1906
 
                        source_parent_id = None
1907
 
                    else:
1908
 
                        last_source_parent[0] = old_dirname
1909
 
                        last_source_parent[1] = source_parent_id
1910
 
                        last_source_parent[2] = source_parent_entry
1911
 
                new_dirname = entry[0][0]
1912
 
                if new_dirname == last_target_parent[0]:
1913
 
                    target_parent_id = last_target_parent[1]
1914
 
                else:
1915
 
                    # TODO: We don't always need to do the lookup, because the
1916
 
                    #       parent entry will be the same as the source entry.
1917
 
                    target_parent_entry = state._get_entry(target_index,
1918
 
                                                           path_utf8=new_dirname)
1919
 
                    target_parent_id = target_parent_entry[0][2]
1920
 
                    if target_parent_id == entry[0][2]:
1921
 
                        # This is the root, so the parent is None
1922
 
                        target_parent_id = None
1923
 
                    else:
1924
 
                        last_target_parent[0] = new_dirname
1925
 
                        last_target_parent[1] = target_parent_id
1926
 
                        last_target_parent[2] = target_parent_entry
1927
 
 
1928
 
                source_exec = source_details[3]
1929
 
                return ((entry[0][2], (old_path, path), content_change,
1930
 
                        (True, True),
1931
 
                        (source_parent_id, target_parent_id),
1932
 
                        (old_basename, entry[0][1]),
1933
 
                        (_minikind_to_kind[source_minikind], target_kind),
1934
 
                        (source_exec, target_exec)),)
1935
 
            elif source_minikind in 'a' and target_minikind in 'fdlt':
1936
 
                # looks like a new file
1937
 
                if path_info is not None:
1938
 
                    path = pathjoin(entry[0][0], entry[0][1])
1939
 
                    # parent id is the entry for the path in the target tree
1940
 
                    # TODO: these are the same for an entire directory: cache em.
1941
 
                    parent_id = state._get_entry(target_index,
1942
 
                                                 path_utf8=entry[0][0])[0][2]
1943
 
                    if parent_id == entry[0][2]:
1944
 
                        parent_id = None
1945
 
                    if use_filesystem_for_exec:
1946
 
                        # We need S_ISREG here, because we aren't sure if this
1947
 
                        # is a file or not.
1948
 
                        target_exec = bool(
1949
 
                            stat.S_ISREG(path_info[3].st_mode)
1950
 
                            and stat.S_IEXEC & path_info[3].st_mode)
1951
 
                    else:
1952
 
                        target_exec = target_details[3]
1953
 
                    return ((entry[0][2], (None, path), True,
1954
 
                            (False, True),
1955
 
                            (None, parent_id),
1956
 
                            (None, entry[0][1]),
1957
 
                            (None, path_info[2]),
1958
 
                            (None, target_exec)),)
1959
 
                else:
1960
 
                    # but its not on disk: we deliberately treat this as just
1961
 
                    # never-present. (Why ?! - RBC 20070224)
1962
 
                    pass
1963
 
            elif source_minikind in 'fdlt' and target_minikind in 'a':
1964
 
                # unversioned, possibly, or possibly not deleted: we dont care.
1965
 
                # if its still on disk, *and* theres no other entry at this
1966
 
                # path [we dont know this in this routine at the moment -
1967
 
                # perhaps we should change this - then it would be an unknown.
1968
 
                old_path = pathjoin(entry[0][0], entry[0][1])
1969
 
                # parent id is the entry for the path in the target tree
1970
 
                parent_id = state._get_entry(source_index, path_utf8=entry[0][0])[0][2]
1971
 
                if parent_id == entry[0][2]:
1972
 
                    parent_id = None
1973
 
                return ((entry[0][2], (old_path, None), True,
1974
 
                        (True, False),
1975
 
                        (parent_id, None),
1976
 
                        (entry[0][1], None),
1977
 
                        (_minikind_to_kind[source_minikind], None),
1978
 
                        (source_details[3], None)),)
1979
 
            elif source_minikind in 'fdlt' and target_minikind in 'r':
1980
 
                # a rename; could be a true rename, or a rename inherited from
1981
 
                # a renamed parent. TODO: handle this efficiently. Its not
1982
 
                # common case to rename dirs though, so a correct but slow
1983
 
                # implementation will do.
1984
 
                if not osutils.is_inside_any(searched_specific_files, target_details[1]):
1985
 
                    search_specific_files.add(target_details[1])
1986
 
            elif source_minikind in 'ra' and target_minikind in 'ra':
1987
 
                # neither of the selected trees contain this file,
1988
 
                # so skip over it. This is not currently directly tested, but
1989
 
                # is indirectly via test_too_much.TestCommands.test_conflicts.
1990
 
                pass
1991
 
            else:
1992
 
                raise AssertionError("don't know how to compare "
1993
 
                    "source_minikind=%r, target_minikind=%r"
1994
 
                    % (source_minikind, target_minikind))
1995
 
                ## import pdb;pdb.set_trace()
1996
 
            return ()
1997
 
 
1998
 
        while search_specific_files:
1999
 
            # TODO: the pending list should be lexically sorted?  the
2000
 
            # interface doesn't require it.
2001
 
            current_root = search_specific_files.pop()
2002
 
            current_root_unicode = current_root.decode('utf8')
2003
 
            searched_specific_files.add(current_root)
2004
 
            # process the entries for this containing directory: the rest will be
2005
 
            # found by their parents recursively.
2006
 
            root_entries = _entries_for_path(current_root)
2007
 
            root_abspath = self.target.abspath(current_root_unicode)
2008
 
            try:
2009
 
                root_stat = os.lstat(root_abspath)
2010
 
            except OSError, e:
2011
 
                if e.errno == errno.ENOENT:
2012
 
                    # the path does not exist: let _process_entry know that.
2013
 
                    root_dir_info = None
2014
 
                else:
2015
 
                    # some other random error: hand it up.
2016
 
                    raise
2017
 
            else:
2018
 
                root_dir_info = ('', current_root,
2019
 
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
2020
 
                    root_abspath)
2021
 
                if root_dir_info[2] == 'directory':
2022
 
                    if self.target._directory_is_tree_reference(
2023
 
                        current_root.decode('utf8')):
2024
 
                        root_dir_info = root_dir_info[:2] + \
2025
 
                            ('tree-reference',) + root_dir_info[3:]
2026
 
 
2027
 
            if not root_entries and not root_dir_info:
2028
 
                # this specified path is not present at all, skip it.
2029
 
                continue
2030
 
            path_handled = False
2031
 
            for entry in root_entries:
2032
 
                for result in _process_entry(entry, root_dir_info):
2033
 
                    # this check should probably be outside the loop: one
2034
 
                    # 'iterate two trees' api, and then _iter_changes filters
2035
 
                    # unchanged pairs. - RBC 20070226
2036
 
                    path_handled = True
2037
 
                    if (include_unchanged
2038
 
                        or result[2]                    # content change
2039
 
                        or result[3][0] != result[3][1] # versioned status
2040
 
                        or result[4][0] != result[4][1] # parent id
2041
 
                        or result[5][0] != result[5][1] # name
2042
 
                        or result[6][0] != result[6][1] # kind
2043
 
                        or result[7][0] != result[7][1] # executable
2044
 
                        ):
2045
 
                        yield (result[0],
2046
 
                               (utf8_decode_or_none(result[1][0]),
2047
 
                                utf8_decode_or_none(result[1][1])),
2048
 
                               result[2],
2049
 
                               result[3],
2050
 
                               result[4],
2051
 
                               (utf8_decode_or_none(result[5][0]),
2052
 
                                utf8_decode_or_none(result[5][1])),
2053
 
                               result[6],
2054
 
                               result[7],
2055
 
                              )
2056
 
            if want_unversioned and not path_handled and root_dir_info:
2057
 
                new_executable = bool(
2058
 
                    stat.S_ISREG(root_dir_info[3].st_mode)
2059
 
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
2060
 
                yield (None,
2061
 
                       (None, current_root_unicode),
2062
 
                       True,
2063
 
                       (False, False),
2064
 
                       (None, None),
2065
 
                       (None, splitpath(current_root_unicode)[-1]),
2066
 
                       (None, root_dir_info[2]),
2067
 
                       (None, new_executable)
2068
 
                      )
2069
 
            initial_key = (current_root, '', '')
2070
 
            block_index, _ = state._find_block_index_from_key(initial_key)
2071
 
            if block_index == 0:
2072
 
                # we have processed the total root already, but because the
2073
 
                # initial key matched it we should skip it here.
2074
 
                block_index +=1
2075
 
            if root_dir_info and root_dir_info[2] == 'tree-reference':
2076
 
                current_dir_info = None
2077
 
            else:
2078
 
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
2079
 
                try:
2080
 
                    current_dir_info = dir_iterator.next()
2081
 
                except OSError, e:
2082
 
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
2083
 
                    # python 2.5 has e.errno == EINVAL,
2084
 
                    #            and e.winerror == ERROR_DIRECTORY
2085
 
                    e_winerror = getattr(e, 'winerror', None)
2086
 
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
2087
 
                    # there may be directories in the inventory even though
2088
 
                    # this path is not a file on disk: so mark it as end of
2089
 
                    # iterator
2090
 
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
2091
 
                        current_dir_info = None
2092
 
                    elif (sys.platform == 'win32'
2093
 
                          and (e.errno in win_errors
2094
 
                               or e_winerror in win_errors)):
2095
 
                        current_dir_info = None
2096
 
                    else:
2097
 
                        raise
2098
 
                else:
2099
 
                    if current_dir_info[0][0] == '':
2100
 
                        # remove .bzr from iteration
2101
 
                        bzr_index = bisect_left(current_dir_info[1], ('.bzr',))
2102
 
                        assert current_dir_info[1][bzr_index][0] == '.bzr'
2103
 
                        del current_dir_info[1][bzr_index]
2104
 
            # walk until both the directory listing and the versioned metadata
2105
 
            # are exhausted. 
2106
 
            if (block_index < len(state._dirblocks) and
2107
 
                osutils.is_inside(current_root, state._dirblocks[block_index][0])):
2108
 
                current_block = state._dirblocks[block_index]
2109
 
            else:
2110
 
                current_block = None
2111
 
            while (current_dir_info is not None or
2112
 
                   current_block is not None):
2113
 
                if (current_dir_info and current_block
2114
 
                    and current_dir_info[0][0] != current_block[0]):
2115
 
                    if current_dir_info[0][0] < current_block[0] :
2116
 
                        # filesystem data refers to paths not covered by the dirblock.
2117
 
                        # this has two possibilities:
2118
 
                        # A) it is versioned but empty, so there is no block for it
2119
 
                        # B) it is not versioned.
2120
 
                        # in either case it was processed by the containing directories walk:
2121
 
                        # if it is root/foo, when we walked root we emitted it,
2122
 
                        # or if we ere given root/foo to walk specifically, we
2123
 
                        # emitted it when checking the walk-root entries
2124
 
                        # advance the iterator and loop - we dont need to emit it.
2125
 
                        try:
2126
 
                            current_dir_info = dir_iterator.next()
2127
 
                        except StopIteration:
2128
 
                            current_dir_info = None
2129
 
                    else:
2130
 
                        # We have a dirblock entry for this location, but there
2131
 
                        # is no filesystem path for this. This is most likely
2132
 
                        # because a directory was removed from the disk.
2133
 
                        # We don't have to report the missing directory,
2134
 
                        # because that should have already been handled, but we
2135
 
                        # need to handle all of the files that are contained
2136
 
                        # within.
2137
 
                        for current_entry in current_block[1]:
2138
 
                            # entry referring to file not present on disk.
2139
 
                            # advance the entry only, after processing.
2140
 
                            for result in _process_entry(current_entry, None):
2141
 
                                # this check should probably be outside the loop: one
2142
 
                                # 'iterate two trees' api, and then _iter_changes filters
2143
 
                                # unchanged pairs. - RBC 20070226
2144
 
                                if (include_unchanged
2145
 
                                    or result[2]                    # content change
2146
 
                                    or result[3][0] != result[3][1] # versioned status
2147
 
                                    or result[4][0] != result[4][1] # parent id
2148
 
                                    or result[5][0] != result[5][1] # name
2149
 
                                    or result[6][0] != result[6][1] # kind
2150
 
                                    or result[7][0] != result[7][1] # executable
2151
 
                                    ):
2152
 
                                    yield (result[0],
2153
 
                                           (utf8_decode_or_none(result[1][0]),
2154
 
                                            utf8_decode_or_none(result[1][1])),
2155
 
                                           result[2],
2156
 
                                           result[3],
2157
 
                                           result[4],
2158
 
                                           (utf8_decode_or_none(result[5][0]),
2159
 
                                            utf8_decode_or_none(result[5][1])),
2160
 
                                           result[6],
2161
 
                                           result[7],
2162
 
                                          )
2163
 
                        block_index +=1
2164
 
                        if (block_index < len(state._dirblocks) and
2165
 
                            osutils.is_inside(current_root,
2166
 
                                              state._dirblocks[block_index][0])):
2167
 
                            current_block = state._dirblocks[block_index]
2168
 
                        else:
2169
 
                            current_block = None
2170
 
                    continue
2171
 
                entry_index = 0
2172
 
                if current_block and entry_index < len(current_block[1]):
2173
 
                    current_entry = current_block[1][entry_index]
2174
 
                else:
2175
 
                    current_entry = None
2176
 
                advance_entry = True
2177
 
                path_index = 0
2178
 
                if current_dir_info and path_index < len(current_dir_info[1]):
2179
 
                    current_path_info = current_dir_info[1][path_index]
2180
 
                    if current_path_info[2] == 'directory':
2181
 
                        if self.target._directory_is_tree_reference(
2182
 
                            current_path_info[0].decode('utf8')):
2183
 
                            current_path_info = current_path_info[:2] + \
2184
 
                                ('tree-reference',) + current_path_info[3:]
2185
 
                else:
2186
 
                    current_path_info = None
2187
 
                advance_path = True
2188
 
                path_handled = False
2189
 
                while (current_entry is not None or
2190
 
                    current_path_info is not None):
2191
 
                    if current_entry is None:
2192
 
                        # the check for path_handled when the path is adnvaced
2193
 
                        # will yield this path if needed.
2194
 
                        pass
2195
 
                    elif current_path_info is None:
2196
 
                        # no path is fine: the per entry code will handle it.
2197
 
                        for result in _process_entry(current_entry, current_path_info):
2198
 
                            # this check should probably be outside the loop: one
2199
 
                            # 'iterate two trees' api, and then _iter_changes filters
2200
 
                            # unchanged pairs. - RBC 20070226
2201
 
                            if (include_unchanged
2202
 
                                or result[2]                    # content change
2203
 
                                or result[3][0] != result[3][1] # versioned status
2204
 
                                or result[4][0] != result[4][1] # parent id
2205
 
                                or result[5][0] != result[5][1] # name
2206
 
                                or result[6][0] != result[6][1] # kind
2207
 
                                or result[7][0] != result[7][1] # executable
2208
 
                                ):
2209
 
                                yield (result[0],
2210
 
                                       (utf8_decode_or_none(result[1][0]),
2211
 
                                        utf8_decode_or_none(result[1][1])),
2212
 
                                       result[2],
2213
 
                                       result[3],
2214
 
                                       result[4],
2215
 
                                       (utf8_decode_or_none(result[5][0]),
2216
 
                                        utf8_decode_or_none(result[5][1])),
2217
 
                                       result[6],
2218
 
                                       result[7],
2219
 
                                      )
2220
 
                    elif current_entry[0][1] != current_path_info[1]:
2221
 
                        if current_path_info[1] < current_entry[0][1]:
2222
 
                            # extra file on disk: pass for now, but only
2223
 
                            # increment the path, not the entry
2224
 
                            advance_entry = False
2225
 
                        else:
2226
 
                            # entry referring to file not present on disk.
2227
 
                            # advance the entry only, after processing.
2228
 
                            for result in _process_entry(current_entry, None):
2229
 
                                # this check should probably be outside the loop: one
2230
 
                                # 'iterate two trees' api, and then _iter_changes filters
2231
 
                                # unchanged pairs. - RBC 20070226
2232
 
                                path_handled = True
2233
 
                                if (include_unchanged
2234
 
                                    or result[2]                    # content change
2235
 
                                    or result[3][0] != result[3][1] # versioned status
2236
 
                                    or result[4][0] != result[4][1] # parent id
2237
 
                                    or result[5][0] != result[5][1] # name
2238
 
                                    or result[6][0] != result[6][1] # kind
2239
 
                                    or result[7][0] != result[7][1] # executable
2240
 
                                    ):
2241
 
                                    yield (result[0],
2242
 
                                           (utf8_decode_or_none(result[1][0]),
2243
 
                                            utf8_decode_or_none(result[1][1])),
2244
 
                                           result[2],
2245
 
                                           result[3],
2246
 
                                           result[4],
2247
 
                                           (utf8_decode_or_none(result[5][0]),
2248
 
                                            utf8_decode_or_none(result[5][1])),
2249
 
                                           result[6],
2250
 
                                           result[7],
2251
 
                                          )
2252
 
                            advance_path = False
2253
 
                    else:
2254
 
                        for result in _process_entry(current_entry, current_path_info):
2255
 
                            # this check should probably be outside the loop: one
2256
 
                            # 'iterate two trees' api, and then _iter_changes filters
2257
 
                            # unchanged pairs. - RBC 20070226
2258
 
                            path_handled = True
2259
 
                            if (include_unchanged
2260
 
                                or result[2]                    # content change
2261
 
                                or result[3][0] != result[3][1] # versioned status
2262
 
                                or result[4][0] != result[4][1] # parent id
2263
 
                                or result[5][0] != result[5][1] # name
2264
 
                                or result[6][0] != result[6][1] # kind
2265
 
                                or result[7][0] != result[7][1] # executable
2266
 
                                ):
2267
 
                                yield (result[0],
2268
 
                                       (utf8_decode_or_none(result[1][0]),
2269
 
                                        utf8_decode_or_none(result[1][1])),
2270
 
                                       result[2],
2271
 
                                       result[3],
2272
 
                                       result[4],
2273
 
                                       (utf8_decode_or_none(result[5][0]),
2274
 
                                        utf8_decode_or_none(result[5][1])),
2275
 
                                       result[6],
2276
 
                                       result[7],
2277
 
                                      )
2278
 
                    if advance_entry and current_entry is not None:
2279
 
                        entry_index += 1
2280
 
                        if entry_index < len(current_block[1]):
2281
 
                            current_entry = current_block[1][entry_index]
2282
 
                        else:
2283
 
                            current_entry = None
2284
 
                    else:
2285
 
                        advance_entry = True # reset the advance flaga
2286
 
                    if advance_path and current_path_info is not None:
2287
 
                        if not path_handled:
2288
 
                            # unversioned in all regards
2289
 
                            if want_unversioned:
2290
 
                                new_executable = bool(
2291
 
                                    stat.S_ISREG(current_path_info[3].st_mode)
2292
 
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
2293
 
                                if want_unversioned:
2294
 
                                    yield (None,
2295
 
                                        (None, utf8_decode_or_none(current_path_info[0])),
2296
 
                                        True,
2297
 
                                        (False, False),
2298
 
                                        (None, None),
2299
 
                                        (None, utf8_decode_or_none(current_path_info[1])),
2300
 
                                        (None, current_path_info[2]),
2301
 
                                        (None, new_executable))
2302
 
                            # dont descend into this unversioned path if it is
2303
 
                            # a dir
2304
 
                            if current_path_info[2] in ('directory'):
2305
 
                                del current_dir_info[1][path_index]
2306
 
                                path_index -= 1
2307
 
                        # dont descend the disk iterator into any tree 
2308
 
                        # paths.
2309
 
                        if current_path_info[2] == 'tree-reference':
2310
 
                            del current_dir_info[1][path_index]
2311
 
                            path_index -= 1
2312
 
                        path_index += 1
2313
 
                        if path_index < len(current_dir_info[1]):
2314
 
                            current_path_info = current_dir_info[1][path_index]
2315
 
                            if current_path_info[2] == 'directory':
2316
 
                                if self.target._directory_is_tree_reference(
2317
 
                                    current_path_info[0].decode('utf8')):
2318
 
                                    current_path_info = current_path_info[:2] + \
2319
 
                                        ('tree-reference',) + current_path_info[3:]
2320
 
                        else:
2321
 
                            current_path_info = None
2322
 
                        path_handled = False
2323
 
                    else:
2324
 
                        advance_path = True # reset the advance flagg.
2325
 
                if current_block is not None:
2326
 
                    block_index += 1
2327
 
                    if (block_index < len(state._dirblocks) and
2328
 
                        osutils.is_inside(current_root, state._dirblocks[block_index][0])):
2329
 
                        current_block = state._dirblocks[block_index]
2330
 
                    else:
2331
 
                        current_block = None
2332
 
                if current_dir_info is not None:
2333
 
                    try:
2334
 
                        current_dir_info = dir_iterator.next()
2335
 
                    except StopIteration:
2336
 
                        current_dir_info = None
2337
 
 
 
2218
        iter_changes = self.target._iter_changes(include_unchanged,
 
2219
            use_filesystem_for_exec, search_specific_files, state,
 
2220
            source_index, target_index, want_unversioned, self.target)
 
2221
        return iter_changes.iter_changes()
2338
2222
 
2339
2223
    @staticmethod
2340
2224
    def is_compatible(source, target):
2341
2225
        # the target must be a dirstate working tree
2342
 
        if not isinstance(target, WorkingTree4):
 
2226
        if not isinstance(target, DirStateWorkingTree):
2343
2227
            return False
2344
 
        # the source must be a revtreee or dirstate rev tree.
 
2228
        # the source must be a revtree or dirstate rev tree.
2345
2229
        if not isinstance(source,
2346
2230
            (revisiontree.RevisionTree, DirStateRevisionTree)):
2347
2231
            return False
2348
2232
        # the source revid must be in the target dirstate
2349
 
        if not (source._revision_id == NULL_REVISION or
 
2233
        if not (source._revision_id == _mod_revision.NULL_REVISION or
2350
2234
            source._revision_id in target.get_parent_ids()):
2351
 
            # TODO: what about ghosts? it may well need to 
 
2235
            # TODO: what about ghosts? it may well need to
2352
2236
            # check for them explicitly.
2353
2237
            return False
2354
2238
        return True
2364
2248
 
2365
2249
    def convert(self, tree):
2366
2250
        # lock the control files not the tree, so that we dont get tree
2367
 
        # on-unlock behaviours, and so that noone else diddles with the 
 
2251
        # on-unlock behaviours, and so that noone else diddles with the
2368
2252
        # tree during upgrade.
2369
2253
        tree._control_files.lock_write()
2370
2254
        try:
2396
2280
 
2397
2281
    def update_format(self, tree):
2398
2282
        """Change the format marker."""
2399
 
        tree._control_files.put_utf8('format',
2400
 
            self.target_format.get_format_string())
 
2283
        tree._transport.put_bytes('format',
 
2284
            self.target_format.as_string(),
 
2285
            mode=tree.bzrdir._get_file_mode())
 
2286
 
 
2287
 
 
2288
class Converter4to5(object):
 
2289
    """Perform an in-place upgrade of format 4 to format 5 trees."""
 
2290
 
 
2291
    def __init__(self):
 
2292
        self.target_format = WorkingTreeFormat5()
 
2293
 
 
2294
    def convert(self, tree):
 
2295
        # lock the control files not the tree, so that we don't get tree
 
2296
        # on-unlock behaviours, and so that no-one else diddles with the
 
2297
        # tree during upgrade.
 
2298
        tree._control_files.lock_write()
 
2299
        try:
 
2300
            self.update_format(tree)
 
2301
        finally:
 
2302
            tree._control_files.unlock()
 
2303
 
 
2304
    def update_format(self, tree):
 
2305
        """Change the format marker."""
 
2306
        tree._transport.put_bytes('format',
 
2307
            self.target_format.as_string(),
 
2308
            mode=tree.bzrdir._get_file_mode())
 
2309
 
 
2310
 
 
2311
class Converter4or5to6(object):
 
2312
    """Perform an in-place upgrade of format 4 or 5 to format 6 trees."""
 
2313
 
 
2314
    def __init__(self):
 
2315
        self.target_format = WorkingTreeFormat6()
 
2316
 
 
2317
    def convert(self, tree):
 
2318
        # lock the control files not the tree, so that we don't get tree
 
2319
        # on-unlock behaviours, and so that no-one else diddles with the
 
2320
        # tree during upgrade.
 
2321
        tree._control_files.lock_write()
 
2322
        try:
 
2323
            self.init_custom_control_files(tree)
 
2324
            self.update_format(tree)
 
2325
        finally:
 
2326
            tree._control_files.unlock()
 
2327
 
 
2328
    def init_custom_control_files(self, tree):
 
2329
        """Initialize custom control files."""
 
2330
        tree._transport.put_bytes('views', '',
 
2331
            mode=tree.bzrdir._get_file_mode())
 
2332
 
 
2333
    def update_format(self, tree):
 
2334
        """Change the format marker."""
 
2335
        tree._transport.put_bytes('format',
 
2336
            self.target_format.as_string(),
 
2337
            mode=tree.bzrdir._get_file_mode())