/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""WorkingTree4 format and implementation.
18
18
 
28
28
 
29
29
from bzrlib.lazy_import import lazy_import
30
30
lazy_import(globals(), """
 
31
from bisect import bisect_left
 
32
import collections
 
33
from copy import deepcopy
31
34
import errno
 
35
import itertools
 
36
import operator
32
37
import stat
 
38
from time import time
 
39
import warnings
33
40
 
 
41
import bzrlib
34
42
from bzrlib import (
35
43
    bzrdir,
36
44
    cache_utf8,
37
45
    conflicts as _mod_conflicts,
38
 
    debug,
 
46
    delta,
39
47
    dirstate,
40
48
    errors,
41
 
    filters as _mod_filters,
42
49
    generate_ids,
 
50
    globbing,
 
51
    hashcache,
 
52
    ignores,
 
53
    merge,
43
54
    osutils,
44
 
    revision as _mod_revision,
45
55
    revisiontree,
46
 
    trace,
 
56
    textui,
47
57
    transform,
48
 
    views,
 
58
    urlutils,
 
59
    xml5,
 
60
    xml6,
49
61
    )
 
62
import bzrlib.branch
 
63
from bzrlib.transport import get_transport
 
64
import bzrlib.ui
50
65
""")
51
66
 
 
67
from bzrlib import symbol_versioning
52
68
from bzrlib.decorators import needs_read_lock, needs_write_lock
53
 
from bzrlib.inventory import Inventory, ROOT_ID, entry_factory
54
 
from bzrlib.lock import LogicalLockResult
55
 
from bzrlib.lockable_files import LockableFiles
 
69
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, entry_factory
 
70
from bzrlib.lockable_files import LockableFiles, TransportLock
56
71
from bzrlib.lockdir import LockDir
 
72
import bzrlib.mutabletree
57
73
from bzrlib.mutabletree import needs_tree_write_lock
58
74
from bzrlib.osutils import (
59
75
    file_kind,
60
76
    isdir,
 
77
    normpath,
61
78
    pathjoin,
 
79
    rand_chars,
62
80
    realpath,
63
81
    safe_unicode,
 
82
    splitpath,
64
83
    )
 
84
from bzrlib.trace import mutter, note
65
85
from bzrlib.transport.local import LocalTransport
66
 
from bzrlib.tree import (
67
 
    InterTree,
68
 
    InventoryTree,
69
 
    )
70
 
from bzrlib.workingtree import (
71
 
    InventoryWorkingTree,
72
 
    WorkingTree,
73
 
    WorkingTreeFormat,
74
 
    )
75
 
 
76
 
 
77
 
class DirStateWorkingTree(InventoryWorkingTree):
 
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
    """
78
117
 
79
118
    def __init__(self, basedir,
80
119
                 branch,
90
129
        """
91
130
        self._format = _format
92
131
        self.bzrdir = _bzrdir
 
132
        from bzrlib.trace import note, mutter
 
133
        assert isinstance(basedir, basestring), \
 
134
            "base directory %r is not a string" % basedir
93
135
        basedir = safe_unicode(basedir)
94
 
        trace.mutter("opening working tree %r", basedir)
 
136
        mutter("opening working tree %r", basedir)
95
137
        self._branch = branch
 
138
        assert isinstance(self.branch, bzrlib.branch.Branch), \
 
139
            "branch %r is not a Branch" % self.branch
96
140
        self.basedir = realpath(basedir)
97
141
        # if branch is at our basedir and is a format 6 or less
98
142
        # 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
99
145
        self._control_files = _control_files
100
 
        self._transport = self._control_files._transport
101
146
        self._dirty = None
102
147
        #-------------
103
148
        # during a read or write lock these objects are set, and are
105
150
        self._dirstate = None
106
151
        self._inventory = None
107
152
        #-------------
108
 
        self._setup_directory_is_tree_reference()
109
 
        self._detect_case_handling()
110
 
        self._rules_searcher = None
111
 
        self.views = self._make_views()
112
 
        #--- allow tests to select the dirstate iter_changes implementation
113
 
        self._iter_changes = dirstate._process_entry
114
153
 
115
154
    @needs_tree_write_lock
116
155
    def _add(self, files, ids, kinds):
118
157
        state = self.current_dirstate()
119
158
        for f, file_id, kind in zip(files, ids, kinds):
120
159
            f = f.strip('/')
 
160
            assert '//' not in f
 
161
            assert '..' not in f
121
162
            if self.path2id(f):
122
163
                # special case tree root handling.
123
164
                if f == '' and self.path2id(f) == ROOT_ID:
131
172
            state.add(f, file_id, kind, None, '')
132
173
        self._make_dirty(reset_inventory=True)
133
174
 
134
 
    def _get_check_refs(self):
135
 
        """Return the references needed to perform a check of this tree."""
136
 
        return [('trees', self.last_revision())]
137
 
 
138
175
    def _make_dirty(self, reset_inventory):
139
176
        """Make the tree state dirty.
140
177
 
148
185
    @needs_tree_write_lock
149
186
    def add_reference(self, sub_tree):
150
187
        # use standard implementation, which calls back to self._add
151
 
        #
 
188
        # 
152
189
        # So we don't store the reference_revision in the working dirstate,
153
 
        # it's just recorded at the moment of commit.
 
190
        # it's just recorded at the moment of commit. 
154
191
        self._add_reference(sub_tree)
155
192
 
156
193
    def break_lock(self):
192
229
 
193
230
    def _comparison_data(self, entry, path):
194
231
        kind, executable, stat_value = \
195
 
            WorkingTree._comparison_data(self, entry, path)
 
232
            WorkingTree3._comparison_data(self, entry, path)
196
233
        # it looks like a plain directory, but it's really a reference -- see
197
234
        # also kind()
198
 
        if (self._repo_supports_tree_reference and kind == 'directory'
199
 
            and entry is not None and entry.kind == 'tree-reference'):
 
235
        if (self._repo_supports_tree_reference and
 
236
            kind == 'directory' and
 
237
            self._directory_is_tree_reference(path)):
200
238
            kind = 'tree-reference'
201
239
        return kind, executable, stat_value
202
240
 
204
242
    def commit(self, message=None, revprops=None, *args, **kwargs):
205
243
        # mark the tree as dirty post commit - commit
206
244
        # can change the current versioned list by doing deletes.
207
 
        result = WorkingTree.commit(self, message, revprops, *args, **kwargs)
 
245
        result = WorkingTree3.commit(self, message, revprops, *args, **kwargs)
208
246
        self._make_dirty(reset_inventory=True)
209
247
        return result
210
248
 
228
266
            return self._dirstate
229
267
        local_path = self.bzrdir.get_workingtree_transport(None
230
268
            ).local_abspath('dirstate')
231
 
        self._dirstate = dirstate.DirState.on_file(local_path,
232
 
            self._sha1_provider())
 
269
        self._dirstate = dirstate.DirState.on_file(local_path)
233
270
        return self._dirstate
234
271
 
235
 
    def _sha1_provider(self):
236
 
        """A function that returns a SHA1Provider suitable for this tree.
237
 
 
238
 
        :return: None if content filtering is not supported by this tree.
239
 
          Otherwise, a SHA1Provider is returned that sha's the canonical
240
 
          form of files, i.e. after read filters are applied.
241
 
        """
242
 
        if self.supports_content_filtering():
243
 
            return ContentFilterAwareSHA1Provider(self)
244
 
        else:
245
 
            return None
 
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
246
286
 
247
287
    def filter_unversioned_files(self, paths):
248
288
        """Filter out paths that are versioned.
281
321
 
282
322
    def _generate_inventory(self):
283
323
        """Create and set self.inventory from the dirstate object.
284
 
 
 
324
        
285
325
        This is relatively expensive: we have to walk the entire dirstate.
286
326
        Ideally we would not, and can deprecate this function.
287
327
        """
291
331
        state._read_dirblocks_if_needed()
292
332
        root_key, current_entry = self._get_entry(path='')
293
333
        current_id = root_key[2]
294
 
        if not (current_entry[0][0] == 'd'): # directory
295
 
            raise AssertionError(current_entry)
 
334
        assert current_entry[0][0] == 'd' # directory
296
335
        inv = Inventory(root_id=current_id)
297
336
        # Turn some things into local variables
298
337
        minikind_to_kind = dirstate.DirState._minikind_to_kind
331
370
                    # add this entry to the parent map.
332
371
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
333
372
                elif kind == 'tree-reference':
334
 
                    if not self._repo_supports_tree_reference:
335
 
                        raise errors.UnsupportedOperation(
336
 
                            self._generate_inventory,
337
 
                            self.branch.repository)
 
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)
338
378
                    inv_entry.reference_revision = link_or_sha1 or None
339
379
                elif kind != 'symlink':
340
380
                    raise AssertionError("unknown kind %r" % kind)
341
381
                # These checks cost us around 40ms on a 55k entry tree
342
 
                if file_id in inv_byid:
343
 
                    raise AssertionError('file_id %s already in'
344
 
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
345
 
                if name_unicode in parent_ie.children:
346
 
                    raise AssertionError('name %r already in parent'
347
 
                        % (name_unicode,))
 
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
348
385
                inv_byid[file_id] = inv_entry
349
386
                parent_ie.children[name_unicode] = inv_entry
350
387
        self._inventory = inv
355
392
        If either file_id or path is supplied, it is used as the key to lookup.
356
393
        If both are supplied, the fastest lookup is used, and an error is
357
394
        raised if they do not both point at the same row.
358
 
 
 
395
        
359
396
        :param file_id: An optional unicode file_id to be looked up.
360
397
        :param path: An optional unicode path to be looked up.
361
398
        :return: The dirstate row tuple for path/file_id, or (None, None)
370
407
    def get_file_sha1(self, file_id, path=None, stat_value=None):
371
408
        # check file id is valid unconditionally.
372
409
        entry = self._get_entry(file_id=file_id, path=path)
373
 
        if entry[0] is None:
374
 
            raise errors.NoSuchId(self, file_id)
 
410
        assert entry[0] is not None, 'what error should this raise'
375
411
        if path is None:
376
412
            path = pathjoin(entry[0][0], entry[0][1]).decode('utf8')
377
413
 
378
414
        file_abspath = self.abspath(path)
379
415
        state = self.current_dirstate()
380
 
        if stat_value is None:
381
 
            try:
382
 
                stat_value = osutils.lstat(file_abspath)
383
 
            except OSError, e:
384
 
                if e.errno == errno.ENOENT:
385
 
                    return None
386
 
                else:
387
 
                    raise
388
 
        link_or_sha1 = dirstate.update_entry(state, entry, file_abspath,
389
 
            stat_value=stat_value)
 
416
        link_or_sha1 = state.update_entry(entry, file_abspath,
 
417
                                          stat_value=stat_value)
390
418
        if entry[1][0][0] == 'f':
391
 
            if link_or_sha1 is None:
392
 
                file_obj, statvalue = self.get_file_with_stat(file_id, path)
393
 
                try:
394
 
                    sha1 = osutils.sha_file(file_obj)
395
 
                finally:
396
 
                    file_obj.close()
397
 
                self._observed_sha1(file_id, path, (sha1, statvalue))
398
 
                return sha1
399
 
            else:
400
 
                return link_or_sha1
 
419
            return link_or_sha1
401
420
        return None
402
421
 
403
422
    def _get_inventory(self):
404
423
        """Get the inventory for the tree. This is only valid within a lock."""
405
 
        if 'evil' in debug.debug_flags:
406
 
            trace.mutter_callsite(2,
407
 
                "accessing .inventory forces a size of tree translation.")
408
424
        if self._inventory is not None:
409
425
            return self._inventory
410
426
        self._must_be_locked()
417
433
    @needs_read_lock
418
434
    def get_parent_ids(self):
419
435
        """See Tree.get_parent_ids.
420
 
 
 
436
        
421
437
        This implementation requests the ids list from the dirstate file.
422
438
        """
423
439
        return self.current_dirstate().get_parent_ids()
439
455
 
440
456
    def has_id(self, file_id):
441
457
        state = self.current_dirstate()
 
458
        file_id = osutils.safe_file_id(file_id)
442
459
        row, parents = self._get_entry(file_id=file_id)
443
460
        if row is None:
444
461
            return False
445
462
        return osutils.lexists(pathjoin(
446
463
                    self.basedir, row[0].decode('utf8'), row[1].decode('utf8')))
447
464
 
448
 
    def has_or_had_id(self, file_id):
449
 
        state = self.current_dirstate()
450
 
        row, parents = self._get_entry(file_id=file_id)
451
 
        return row is not None
452
 
 
453
465
    @needs_read_lock
454
466
    def id2path(self, file_id):
455
 
        "Convert a file-id to a path."
 
467
        file_id = osutils.safe_file_id(file_id)
456
468
        state = self.current_dirstate()
457
469
        entry = self._get_entry(file_id=file_id)
458
470
        if entry == (None, None):
460
472
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
461
473
        return path_utf8.decode('utf8')
462
474
 
463
 
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
464
 
        entry = self._get_entry(path=path)
465
 
        if entry == (None, None):
466
 
            return False # Missing entries are not executable
467
 
        return entry[1][0][3] # Executable?
468
 
 
469
475
    if not osutils.supports_executable():
 
476
        @needs_read_lock
470
477
        def is_executable(self, file_id, path=None):
471
 
            """Test if a file is executable or not.
472
 
 
473
 
            Note: The caller is expected to take a read-lock before calling this.
474
 
            """
 
478
            file_id = osutils.safe_file_id(file_id)
475
479
            entry = self._get_entry(file_id=file_id, path=path)
476
480
            if entry == (None, None):
477
481
                return False
478
482
            return entry[1][0][3]
479
 
 
480
 
        _is_executable_from_path_and_stat = \
481
 
            _is_executable_from_path_and_stat_from_basis
482
483
    else:
 
484
        @needs_read_lock
483
485
        def is_executable(self, file_id, path=None):
484
 
            """Test if a file is executable or not.
485
 
 
486
 
            Note: The caller is expected to take a read-lock before calling this.
487
 
            """
488
 
            self._must_be_locked()
489
486
            if not path:
 
487
                file_id = osutils.safe_file_id(file_id)
490
488
                path = self.id2path(file_id)
491
 
            mode = osutils.lstat(self.abspath(path)).st_mode
 
489
            mode = os.lstat(self.abspath(path)).st_mode
492
490
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
493
491
 
494
 
    def all_file_ids(self):
495
 
        """See Tree.iter_all_file_ids"""
496
 
        self._must_be_locked()
497
 
        result = set()
498
 
        for key, tree_details in self.current_dirstate()._iter_entries():
499
 
            if tree_details[0][0] in ('a', 'r'): # relocated
500
 
                continue
501
 
            result.add(key[2])
502
 
        return result
503
 
 
504
492
    @needs_read_lock
505
493
    def __iter__(self):
506
494
        """Iterate through file_ids for this tree.
519
507
        return iter(result)
520
508
 
521
509
    def iter_references(self):
522
 
        if not self._repo_supports_tree_reference:
523
 
            # When the repo doesn't support references, we will have nothing to
524
 
            # return
525
 
            return
526
510
        for key, tree_details in self.current_dirstate()._iter_entries():
527
511
            if tree_details[0][0] in ('a', 'r'): # absent, relocated
528
512
                # not relevant to the working tree
530
514
            if not key[1]:
531
515
                # the root is not a reference.
532
516
                continue
533
 
            relpath = pathjoin(key[0].decode('utf8'), key[1].decode('utf8'))
 
517
            path = pathjoin(self.basedir, key[0].decode('utf8'), key[1].decode('utf8'))
534
518
            try:
535
 
                if self._kind(relpath) == 'tree-reference':
536
 
                    yield relpath, key[2]
 
519
                if self._kind(path) == 'tree-reference':
 
520
                    yield path, key[2]
537
521
            except errors.NoSuchFile:
538
522
                # path is missing on disk.
539
523
                continue
540
524
 
541
 
    def _observed_sha1(self, file_id, path, (sha1, statvalue)):
542
 
        """See MutableTree._observed_sha1."""
543
 
        state = self.current_dirstate()
544
 
        entry = self._get_entry(file_id=file_id, path=path)
545
 
        state._observed_sha1(entry, sha1, statvalue)
546
 
 
 
525
    @needs_read_lock
547
526
    def kind(self, file_id):
548
527
        """Return the kind of a file.
549
528
 
550
529
        This is always the actual kind that's on disk, regardless of what it
551
530
        was added as.
552
 
 
553
 
        Note: The caller is expected to take a read-lock before calling this.
554
531
        """
555
532
        relpath = self.id2path(file_id)
556
 
        if relpath is None:
557
 
            raise AssertionError(
558
 
                "path for id {%s} is None!" % file_id)
 
533
        assert relpath != None, \
 
534
            "path for id {%s} is None!" % file_id
559
535
        return self._kind(relpath)
560
536
 
561
537
    def _kind(self, relpath):
562
538
        abspath = self.abspath(relpath)
563
539
        kind = file_kind(abspath)
564
 
        if (self._repo_supports_tree_reference and kind == 'directory'):
565
 
            entry = self._get_entry(path=relpath)
566
 
            if entry[1] is not None:
567
 
                if entry[1][0][0] == 't':
568
 
                    kind = 'tree-reference'
 
540
        if (self._repo_supports_tree_reference and
 
541
            kind == 'directory' and
 
542
            self._directory_is_tree_reference(relpath)):
 
543
            kind = 'tree-reference'
569
544
        return kind
570
545
 
571
546
    @needs_read_lock
575
550
        if parent_ids:
576
551
            return parent_ids[0]
577
552
        else:
578
 
            return _mod_revision.NULL_REVISION
 
553
            return None
579
554
 
580
555
    def lock_read(self):
581
 
        """See Branch.lock_read, and WorkingTree.unlock.
582
 
 
583
 
        :return: A bzrlib.lock.LogicalLockResult.
584
 
        """
 
556
        """See Branch.lock_read, and WorkingTree.unlock."""
585
557
        self.branch.lock_read()
586
558
        try:
587
559
            self._control_files.lock_read()
600
572
        except:
601
573
            self.branch.unlock()
602
574
            raise
603
 
        return LogicalLockResult(self.unlock)
604
575
 
605
576
    def _lock_self_write(self):
606
577
        """This should be called after the branch is locked."""
621
592
        except:
622
593
            self.branch.unlock()
623
594
            raise
624
 
        return LogicalLockResult(self.unlock)
625
595
 
626
596
    def lock_tree_write(self):
627
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
628
 
 
629
 
        :return: A bzrlib.lock.LogicalLockResult.
630
 
        """
 
597
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
631
598
        self.branch.lock_read()
632
 
        return self._lock_self_write()
 
599
        self._lock_self_write()
633
600
 
634
601
    def lock_write(self):
635
 
        """See MutableTree.lock_write, and WorkingTree.unlock.
636
 
 
637
 
        :return: A bzrlib.lock.LogicalLockResult.
638
 
        """
 
602
        """See MutableTree.lock_write, and WorkingTree.unlock."""
639
603
        self.branch.lock_write()
640
 
        return self._lock_self_write()
 
604
        self._lock_self_write()
641
605
 
642
606
    @needs_tree_write_lock
643
607
    def move(self, from_paths, to_dir, after=False):
645
609
        result = []
646
610
        if not from_paths:
647
611
            return result
 
612
 
648
613
        state = self.current_dirstate()
649
 
        if isinstance(from_paths, basestring):
650
 
            raise ValueError()
 
614
 
 
615
        assert not isinstance(from_paths, basestring)
651
616
        to_dir_utf8 = to_dir.encode('utf8')
652
617
        to_entry_dirname, to_basename = os.path.split(to_dir_utf8)
653
618
        id_index = state._get_id_index()
675
640
        if self._inventory is not None:
676
641
            update_inventory = True
677
642
            inv = self.inventory
 
643
            to_dir_ie = inv[to_dir_id]
678
644
            to_dir_id = to_entry[0][2]
679
 
            to_dir_ie = inv[to_dir_id]
680
645
        else:
681
646
            update_inventory = False
682
647
 
705
670
            new_entry = to_block[1][added_entry_index]
706
671
            rollbacks.append(lambda:state._make_absent(new_entry))
707
672
 
 
673
        # create rename entries and tuples
708
674
        for from_rel in from_paths:
709
675
            # from_rel is 'pathinroot/foo/bar'
710
676
            from_rel_utf8 = from_rel.encode('utf8')
713
679
            from_entry = self._get_entry(path=from_rel)
714
680
            if from_entry == (None, None):
715
681
                raise errors.BzrMoveFailedError(from_rel,to_dir,
716
 
                    errors.NotVersionedError(path=from_rel))
 
682
                    errors.NotVersionedError(path=str(from_rel)))
717
683
 
718
684
            from_id = from_entry[0][2]
719
685
            to_rel = pathjoin(to_dir, from_tail)
746
712
                if from_missing: # implicitly just update our path mapping
747
713
                    move_file = False
748
714
                elif not after:
749
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
 
715
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
 
716
                        extra="(Use --after to update the Bazaar id)")
750
717
 
751
718
            rollbacks = []
752
719
            def rollback_rename():
807
774
 
808
775
                if minikind == 'd':
809
776
                    def update_dirblock(from_dir, to_key, to_dir_utf8):
810
 
                        """Recursively update all entries in this dirblock."""
811
 
                        if from_dir == '':
812
 
                            raise AssertionError("renaming root not supported")
 
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"
813
783
                        from_key = (from_dir, '')
814
784
                        from_block_idx, present = \
815
785
                            state._find_block_index_from_key(from_key)
825
795
                        to_block_index = state._ensure_block(
826
796
                            to_block_index, to_entry_index, to_dir_utf8)
827
797
                        to_block = state._dirblocks[to_block_index]
828
 
 
829
 
                        # Grab a copy since move_one may update the list.
830
 
                        for entry in from_block[1][:]:
831
 
                            if not (entry[0][0] == from_dir):
832
 
                                raise AssertionError()
 
798
                        for entry in from_block[1]:
 
799
                            assert entry[0][0] == from_dir
833
800
                            cur_details = entry[1][0]
834
801
                            to_key = (to_dir_utf8, entry[0][1], entry[0][2])
835
802
                            from_path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
836
803
                            to_path_utf8 = osutils.pathjoin(to_dir_utf8, entry[0][1])
837
804
                            minikind = cur_details[0]
838
 
                            if minikind in 'ar':
839
 
                                # Deleted children of a renamed directory
840
 
                                # Do not need to be updated.
841
 
                                # Children that have been renamed out of this
842
 
                                # directory should also not be updated
843
 
                                continue
844
805
                            move_one(entry, from_path_utf8=from_path_utf8,
845
806
                                     minikind=minikind,
846
807
                                     executable=cur_details[3],
894
855
        for tree in trees:
895
856
            if not (isinstance(tree, DirStateRevisionTree) and tree._revision_id in
896
857
                parents):
897
 
                return super(DirStateWorkingTree, self).paths2ids(paths,
898
 
                    trees, require_versioned)
 
858
                return super(WorkingTree4, self).paths2ids(paths, trees, require_versioned)
899
859
        search_indexes = [0] + [1 + parents.index(tree._revision_id) for tree in trees]
900
860
        # -- make all paths utf8 --
901
861
        paths_utf8 = set()
961
921
            if not all_versioned:
962
922
                raise errors.PathsNotVersionedError(paths)
963
923
        # -- remove redundancy in supplied paths to prevent over-scanning --
964
 
        search_paths = osutils.minimum_path_selection(paths)
965
 
        # sketch:
 
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: 
966
931
        # for all search_indexs in each path at or under each element of
967
932
        # search_paths, if the detail is relocated: add the id, and add the
968
933
        # relocated path as one to search if its not searched already. If the
1024
989
 
1025
990
    def read_working_inventory(self):
1026
991
        """Read the working inventory.
1027
 
 
 
992
        
1028
993
        This is a meaningless operation for dirstate, but we obey it anyhow.
1029
994
        """
1030
995
        return self.inventory
1035
1000
 
1036
1001
        WorkingTree4 supplies revision_trees for any basis tree.
1037
1002
        """
 
1003
        revision_id = osutils.safe_revision_id(revision_id)
1038
1004
        dirstate = self.current_dirstate()
1039
1005
        parent_ids = dirstate.get_parent_ids()
1040
1006
        if revision_id not in parent_ids:
1047
1013
    @needs_tree_write_lock
1048
1014
    def set_last_revision(self, new_revision):
1049
1015
        """Change the last revision in the working tree."""
 
1016
        new_revision = osutils.safe_revision_id(new_revision)
1050
1017
        parents = self.get_parent_ids()
1051
 
        if new_revision in (_mod_revision.NULL_REVISION, None):
1052
 
            if len(parents) >= 2:
1053
 
                raise AssertionError(
1054
 
                    "setting the last parent to none with a pending merge is "
1055
 
                    "unsupported.")
 
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.")
1056
1022
            self.set_parent_ids([])
1057
1023
        else:
1058
1024
            self.set_parent_ids([new_revision] + parents[1:],
1061
1027
    @needs_tree_write_lock
1062
1028
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1063
1029
        """Set the parent ids to revision_ids.
1064
 
 
 
1030
        
1065
1031
        See also set_parent_trees. This api will try to retrieve the tree data
1066
1032
        for each element of revision_ids from the trees repository. If you have
1067
1033
        tree data already available, it is more efficient to use
1071
1037
        :param revision_ids: The revision_ids to set as the parent ids of this
1072
1038
            working tree. Any of these may be ghosts.
1073
1039
        """
 
1040
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1074
1041
        trees = []
1075
1042
        for revision_id in revision_ids:
1076
1043
            try:
1082
1049
            except (errors.NoSuchRevision, errors.RevisionNotPresent):
1083
1050
                revtree = None
1084
1051
            trees.append((revision_id, revtree))
 
1052
        self.current_dirstate()._validate()
1085
1053
        self.set_parent_trees(trees,
1086
1054
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
1055
        self.current_dirstate()._validate()
1087
1056
 
1088
1057
    @needs_tree_write_lock
1089
1058
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1094
1063
            parent tree - i.e. a ghost.
1095
1064
        """
1096
1065
        dirstate = self.current_dirstate()
 
1066
        dirstate._validate()
1097
1067
        if len(parents_list) > 0:
1098
1068
            if not allow_leftmost_as_ghost and parents_list[0][1] is None:
1099
1069
                raise errors.GhostRevisionUnusableHere(parents_list[0][0])
1100
1070
        real_trees = []
1101
1071
        ghosts = []
1102
 
 
1103
 
        parent_ids = [rev_id for rev_id, tree in parents_list]
1104
 
        graph = self.branch.repository.get_graph()
1105
 
        heads = graph.heads(parent_ids)
1106
 
        accepted_revisions = set()
1107
 
 
1108
1072
        # convert absent trees to the null tree, which we convert back to
1109
1073
        # missing on access.
1110
1074
        for rev_id, tree in parents_list:
1111
 
            if len(accepted_revisions) > 0:
1112
 
                # we always accept the first tree
1113
 
                if rev_id in accepted_revisions or rev_id not in heads:
1114
 
                    # We have already included either this tree, or its
1115
 
                    # descendent, so we skip it.
1116
 
                    continue
1117
 
            _mod_revision.check_not_reserved_id(rev_id)
 
1075
            rev_id = osutils.safe_revision_id(rev_id)
1118
1076
            if tree is not None:
1119
1077
                real_trees.append((rev_id, tree))
1120
1078
            else:
1121
1079
                real_trees.append((rev_id,
1122
 
                    self.branch.repository.revision_tree(
1123
 
                        _mod_revision.NULL_REVISION)))
 
1080
                    self.branch.repository.revision_tree(None)))
1124
1081
                ghosts.append(rev_id)
1125
 
            accepted_revisions.add(rev_id)
 
1082
        dirstate._validate()
1126
1083
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
 
1084
        dirstate._validate()
1127
1085
        self._make_dirty(reset_inventory=False)
 
1086
        dirstate._validate()
1128
1087
 
1129
1088
    def _set_root_id(self, file_id):
1130
1089
        """See WorkingTree.set_root_id."""
1133
1092
        if state._dirblock_state == dirstate.DirState.IN_MEMORY_MODIFIED:
1134
1093
            self._make_dirty(reset_inventory=True)
1135
1094
 
1136
 
    def _sha_from_stat(self, path, stat_result):
1137
 
        """Get a sha digest from the tree's stat cache.
1138
 
 
1139
 
        The default implementation assumes no stat cache is present.
1140
 
 
1141
 
        :param path: The path.
1142
 
        :param stat_result: The stat result being looked up.
1143
 
        """
1144
 
        return self.current_dirstate().sha1_from_stat(path, stat_result)
1145
 
 
1146
1095
    @needs_read_lock
1147
1096
    def supports_tree_reference(self):
1148
1097
        return self._repo_supports_tree_reference
1149
1098
 
1150
1099
    def unlock(self):
1151
1100
        """Unlock in format 4 trees needs to write the entire dirstate."""
1152
 
        # do non-implementation specific cleanup
1153
 
        self._cleanup()
1154
 
 
1155
1101
        if self._control_files._lock_count == 1:
1156
1102
            # eventually we should do signature checking during read locks for
1157
1103
            # dirstate updates.
1188
1134
            return
1189
1135
        state = self.current_dirstate()
1190
1136
        state._read_dirblocks_if_needed()
1191
 
        ids_to_unversion = set(file_ids)
 
1137
        ids_to_unversion = set()
 
1138
        for file_id in file_ids:
 
1139
            ids_to_unversion.add(osutils.safe_file_id(file_id))
1192
1140
        paths_to_unversion = set()
1193
1141
        # sketch:
1194
1142
        # check if the root is to be unversioned, if so, assert for now.
1221
1169
                # just forget the whole block.
1222
1170
                entry_index = 0
1223
1171
                while entry_index < len(block[1]):
 
1172
                    # Mark this file id as having been removed
1224
1173
                    entry = block[1][entry_index]
1225
 
                    if entry[1][0][0] in 'ar':
1226
 
                        # don't remove absent or renamed entries
 
1174
                    ids_to_unversion.discard(entry[0][2])
 
1175
                    if (entry[1][0][0] == 'a'
 
1176
                        or not state._make_absent(entry)):
1227
1177
                        entry_index += 1
1228
 
                    else:
1229
 
                        # Mark this file id as having been removed
1230
 
                        ids_to_unversion.discard(entry[0][2])
1231
 
                        if not state._make_absent(entry):
1232
 
                            # The block has not shrunk.
1233
 
                            entry_index += 1
1234
1178
                # go to the next block. (At the moment we dont delete empty
1235
1179
                # dirblocks)
1236
1180
                block_index += 1
1257
1201
        # have to change the legacy inventory too.
1258
1202
        if self._inventory is not None:
1259
1203
            for file_id in file_ids:
1260
 
                if self._inventory.has_id(file_id):
1261
 
                    self._inventory.remove_recursive_id(file_id)
1262
 
 
1263
 
    @needs_tree_write_lock
1264
 
    def rename_one(self, from_rel, to_rel, after=False):
1265
 
        """See WorkingTree.rename_one"""
1266
 
        self.flush()
1267
 
        super(DirStateWorkingTree, self).rename_one(from_rel, to_rel, after)
1268
 
 
1269
 
    @needs_tree_write_lock
1270
 
    def apply_inventory_delta(self, changes):
1271
 
        """See MutableTree.apply_inventory_delta"""
1272
 
        state = self.current_dirstate()
1273
 
        state.update_by_delta(changes)
1274
 
        self._make_dirty(reset_inventory=True)
1275
 
 
1276
 
    def update_basis_by_delta(self, new_revid, delta):
1277
 
        """See MutableTree.update_basis_by_delta."""
1278
 
        if self.last_revision() == new_revid:
1279
 
            raise AssertionError()
1280
 
        self.current_dirstate().update_basis_by_delta(delta, new_revid)
 
1204
                self._inventory.remove_recursive_id(file_id)
1281
1205
 
1282
1206
    @needs_read_lock
1283
1207
    def _validate(self):
1286
1210
    @needs_tree_write_lock
1287
1211
    def _write_inventory(self, inv):
1288
1212
        """Write inventory as the current inventory."""
1289
 
        if self._dirty:
1290
 
            raise AssertionError("attempting to write an inventory when the "
1291
 
                "dirstate is dirty will lose pending changes")
1292
 
        had_inventory = self._inventory is not None
1293
 
        # Setting self._inventory = None forces the dirstate to regenerate the
1294
 
        # working inventory. We do this because self.inventory may be inv, or
1295
 
        # may have been modified, and either case would prevent a clean delta
1296
 
        # being created.
1297
 
        self._inventory = None
1298
 
        # generate a delta,
1299
 
        delta = inv._make_delta(self.inventory)
1300
 
        # and apply it.
1301
 
        self.apply_inventory_delta(delta)
1302
 
        if had_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:
1303
1217
            self._inventory = inv
1304
1218
        self.flush()
1305
1219
 
1306
 
    @needs_tree_write_lock
1307
 
    def reset_state(self, revision_ids=None):
1308
 
        """Reset the state of the working tree.
1309
 
 
1310
 
        This does a hard-reset to a last-known-good state. This is a way to
1311
 
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
1312
 
        """
1313
 
        if revision_ids is None:
1314
 
            revision_ids = self.get_parent_ids()
1315
 
        if not revision_ids:
1316
 
            base_tree = self.branch.repository.revision_tree(
1317
 
                _mod_revision.NULL_REVISION)
1318
 
            trees = []
1319
 
        else:
1320
 
            trees = zip(revision_ids,
1321
 
                        self.branch.repository.revision_trees(revision_ids))
1322
 
            base_tree = trees[0][1]
1323
 
        state = self.current_dirstate()
1324
 
        # We don't support ghosts yet
1325
 
        state.set_state_from_scratch(base_tree.inventory, trees, [])
1326
 
 
1327
 
 
1328
 
class ContentFilterAwareSHA1Provider(dirstate.SHA1Provider):
1329
 
 
1330
 
    def __init__(self, tree):
1331
 
        self.tree = tree
1332
 
 
1333
 
    def sha1(self, abspath):
1334
 
        """See dirstate.SHA1Provider.sha1()."""
1335
 
        filters = self.tree._content_filter_stack(
1336
 
            self.tree.relpath(osutils.safe_unicode(abspath)))
1337
 
        return _mod_filters.internal_size_sha_file_byname(abspath, filters)[1]
1338
 
 
1339
 
    def stat_and_sha1(self, abspath):
1340
 
        """See dirstate.SHA1Provider.stat_and_sha1()."""
1341
 
        filters = self.tree._content_filter_stack(
1342
 
            self.tree.relpath(osutils.safe_unicode(abspath)))
1343
 
        file_obj = file(abspath, 'rb', 65000)
1344
 
        try:
1345
 
            statvalue = os.fstat(file_obj.fileno())
1346
 
            if filters:
1347
 
                file_obj = _mod_filters.filtered_input_file(file_obj, filters)
1348
 
            sha1 = osutils.size_sha_file(file_obj)[1]
1349
 
        finally:
1350
 
            file_obj.close()
1351
 
        return statvalue, sha1
1352
 
 
1353
 
 
1354
 
class ContentFilteringDirStateWorkingTree(DirStateWorkingTree):
1355
 
    """Dirstate working tree that supports content filtering.
1356
 
 
1357
 
    The dirstate holds the hash and size of the canonical form of the file, 
1358
 
    and most methods must return that.
1359
 
    """
1360
 
 
1361
 
    def _file_content_summary(self, path, stat_result):
1362
 
        # This is to support the somewhat obsolete path_content_summary method
1363
 
        # with content filtering: see
1364
 
        # <https://bugs.launchpad.net/bzr/+bug/415508>.
1365
 
        #
1366
 
        # If the dirstate cache is up to date and knows the hash and size,
1367
 
        # return that.
1368
 
        # Otherwise if there are no content filters, return the on-disk size
1369
 
        # and leave the hash blank.
1370
 
        # Otherwise, read and filter the on-disk file and use its size and
1371
 
        # hash.
1372
 
        #
1373
 
        # The dirstate doesn't store the size of the canonical form so we
1374
 
        # can't trust it for content-filtered trees.  We just return None.
1375
 
        dirstate_sha1 = self._dirstate.sha1_from_stat(path, stat_result)
1376
 
        executable = self._is_executable_from_path_and_stat(path, stat_result)
1377
 
        return ('file', None, executable, dirstate_sha1)
1378
 
 
1379
 
 
1380
 
class WorkingTree4(DirStateWorkingTree):
1381
 
    """This is the Format 4 working tree.
1382
 
 
1383
 
    This differs from WorkingTree by:
1384
 
     - Having a consolidated internal dirstate, stored in a
1385
 
       randomly-accessible sorted file on disk.
1386
 
     - Not having a regular inventory attribute.  One can be synthesized
1387
 
       on demand but this is expensive and should be avoided.
1388
 
 
1389
 
    This is new in bzr 0.15.
1390
 
    """
1391
 
 
1392
 
 
1393
 
class WorkingTree5(ContentFilteringDirStateWorkingTree):
1394
 
    """This is the Format 5 working tree.
1395
 
 
1396
 
    This differs from WorkingTree4 by:
1397
 
     - Supporting content filtering.
1398
 
 
1399
 
    This is new in bzr 1.11.
1400
 
    """
1401
 
 
1402
 
 
1403
 
class WorkingTree6(ContentFilteringDirStateWorkingTree):
1404
 
    """This is the Format 6 working tree.
1405
 
 
1406
 
    This differs from WorkingTree5 by:
1407
 
     - Supporting a current view that may mask the set of files in a tree
1408
 
       impacted by most user operations.
1409
 
 
1410
 
    This is new in bzr 1.14.
1411
 
    """
1412
 
 
1413
 
    def _make_views(self):
1414
 
        return views.PathBasedViews(self)
1415
 
 
1416
 
 
1417
 
class DirStateWorkingTreeFormat(WorkingTreeFormat):
1418
 
 
1419
 
    missing_parent_conflicts = True
1420
 
 
1421
 
    _lock_class = LockDir
1422
 
    _lock_file_name = 'lock'
1423
 
 
1424
 
    def _open_control_files(self, a_bzrdir):
1425
 
        transport = a_bzrdir.get_workingtree_transport(None)
1426
 
        return LockableFiles(transport, self._lock_file_name,
1427
 
                             self._lock_class)
1428
 
 
1429
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
1430
 
                   accelerator_tree=None, hardlink=False):
 
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):
1431
1244
        """See WorkingTreeFormat.initialize().
1432
1245
 
1433
1246
        :param revision_id: allows creating a working tree at a different
1434
1247
        revision than the branch is at.
1435
 
        :param accelerator_tree: A tree which can be used for retrieving file
1436
 
            contents more quickly than the revision tree, i.e. a workingtree.
1437
 
            The revision tree will be used for cases where accelerator_tree's
1438
 
            content is different.
1439
 
        :param hardlink: If true, hard-link files from accelerator_tree,
1440
 
            where possible.
1441
1248
 
1442
 
        These trees get an initial random root id, if their repository supports
1443
 
        rich root data, TREE_ROOT otherwise.
 
1249
        These trees get an initial random root id.
1444
1250
        """
 
1251
        revision_id = osutils.safe_revision_id(revision_id)
1445
1252
        if not isinstance(a_bzrdir.transport, LocalTransport):
1446
1253
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1447
1254
        transport = a_bzrdir.get_workingtree_transport(self)
1448
1255
        control_files = self._open_control_files(a_bzrdir)
1449
1256
        control_files.create_lock()
1450
1257
        control_files.lock_write()
1451
 
        transport.put_bytes('format', self.get_format_string(),
1452
 
            mode=a_bzrdir._get_file_mode())
1453
 
        if from_branch is not None:
1454
 
            branch = from_branch
1455
 
        else:
1456
 
            branch = a_bzrdir.open_branch()
 
1258
        control_files.put_utf8('format', self.get_format_string())
 
1259
        branch = a_bzrdir.open_branch()
1457
1260
        if revision_id is None:
1458
1261
            revision_id = branch.last_revision()
1459
1262
        local_path = transport.local_abspath('dirstate')
1461
1264
        state = dirstate.DirState.initialize(local_path)
1462
1265
        state.unlock()
1463
1266
        del state
1464
 
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
1267
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
1465
1268
                         branch,
1466
1269
                         _format=self,
1467
1270
                         _bzrdir=a_bzrdir,
1468
1271
                         _control_files=control_files)
1469
1272
        wt._new_tree()
1470
1273
        wt.lock_tree_write()
 
1274
        wt.current_dirstate()._validate()
1471
1275
        try:
1472
 
            self._init_custom_control_files(wt)
1473
 
            if revision_id in (None, _mod_revision.NULL_REVISION):
1474
 
                if branch.repository.supports_rich_root():
1475
 
                    wt._set_root_id(generate_ids.gen_root_id())
1476
 
                else:
1477
 
                    wt._set_root_id(ROOT_ID)
 
1276
            if revision_id in (None, NULL_REVISION):
 
1277
                wt._set_root_id(generate_ids.gen_root_id())
1478
1278
                wt.flush()
1479
 
            basis = None
1480
 
            # frequently, we will get here due to branching.  The accelerator
1481
 
            # tree will be the tree from the branch, so the desired basis
1482
 
            # tree will often be a parent of the accelerator tree.
1483
 
            if accelerator_tree is not None:
1484
 
                try:
1485
 
                    basis = accelerator_tree.revision_tree(revision_id)
1486
 
                except errors.NoSuchRevision:
1487
 
                    pass
1488
 
            if basis is None:
1489
 
                basis = branch.repository.revision_tree(revision_id)
1490
 
            if revision_id == _mod_revision.NULL_REVISION:
1491
 
                parents_list = []
1492
 
            else:
1493
 
                parents_list = [(revision_id, basis)]
 
1279
                wt.current_dirstate()._validate()
 
1280
            wt.set_last_revision(revision_id)
 
1281
            wt.flush()
 
1282
            basis = wt.basis_tree()
1494
1283
            basis.lock_read()
1495
 
            try:
1496
 
                wt.set_parent_trees(parents_list, allow_leftmost_as_ghost=True)
 
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)
1497
1289
                wt.flush()
1498
 
                # if the basis has a root id we have to use that; otherwise we
1499
 
                # use a new random one
1500
 
                basis_root_id = basis.get_root_id()
1501
 
                if basis_root_id is not None:
1502
 
                    wt._set_root_id(basis_root_id)
1503
 
                    wt.flush()
1504
 
                if wt.supports_content_filtering():
1505
 
                    # The original tree may not have the same content filters
1506
 
                    # applied so we can't safely build the inventory delta from
1507
 
                    # the source tree.
1508
 
                    delta_from_tree = False
1509
 
                else:
1510
 
                    delta_from_tree = True
1511
 
                # delta_from_tree is safe even for DirStateRevisionTrees,
1512
 
                # because wt4.apply_inventory_delta does not mutate the input
1513
 
                # inventory entries.
1514
 
                transform.build_tree(basis, wt, accelerator_tree,
1515
 
                                     hardlink=hardlink,
1516
 
                                     delta_from_tree=delta_from_tree)
1517
 
            finally:
1518
 
                basis.unlock()
 
1290
            transform.build_tree(basis, wt)
 
1291
            basis.unlock()
1519
1292
        finally:
1520
1293
            control_files.unlock()
1521
1294
            wt.unlock()
1522
1295
        return wt
1523
1296
 
1524
 
    def _init_custom_control_files(self, wt):
1525
 
        """Subclasses with custom control files should override this method.
1526
 
 
1527
 
        The working tree and control files are locked for writing when this
1528
 
        method is called.
1529
 
 
1530
 
        :param wt: the WorkingTree object
1531
 
        """
1532
 
 
1533
 
    def open(self, a_bzrdir, _found=False):
1534
 
        """Return the WorkingTree object for a_bzrdir
1535
 
 
1536
 
        _found is a private parameter, do not use it. It is used to indicate
1537
 
               if format probing has already been done.
1538
 
        """
1539
 
        if not _found:
1540
 
            # we are being called directly and must probe.
1541
 
            raise NotImplementedError
1542
 
        if not isinstance(a_bzrdir.transport, LocalTransport):
1543
 
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1544
 
        wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
1545
 
        return wt
1546
 
 
1547
1297
    def _open(self, a_bzrdir, control_files):
1548
1298
        """Open the tree itself.
1549
1299
 
1550
1300
        :param a_bzrdir: the dir for the tree.
1551
1301
        :param control_files: the control files for the tree.
1552
1302
        """
1553
 
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
1303
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
1554
1304
                           branch=a_bzrdir.open_branch(),
1555
1305
                           _format=self,
1556
1306
                           _bzrdir=a_bzrdir,
1557
1307
                           _control_files=control_files)
1558
1308
 
1559
1309
    def __get_matchingbzrdir(self):
1560
 
        return self._get_matchingbzrdir()
1561
 
 
1562
 
    def _get_matchingbzrdir(self):
1563
 
        """Overrideable method to get a bzrdir for testing."""
1564
1310
        # please test against something that will let us do tree references
1565
1311
        return bzrdir.format_registry.make_bzrdir(
1566
1312
            'dirstate-with-subtree')
1568
1314
    _matchingbzrdir = property(__get_matchingbzrdir)
1569
1315
 
1570
1316
 
1571
 
class WorkingTreeFormat4(DirStateWorkingTreeFormat):
1572
 
    """The first consolidated dirstate working tree format.
1573
 
 
1574
 
    This format:
1575
 
        - exists within a metadir controlling .bzr
1576
 
        - includes an explicit version marker for the workingtree control
1577
 
          files, separate from the BzrDir format
1578
 
        - modifies the hash cache format
1579
 
        - is new in bzr 0.15
1580
 
        - uses a LockDir to guard access to it.
1581
 
    """
1582
 
 
1583
 
    upgrade_recommended = False
1584
 
 
1585
 
    _tree_class = WorkingTree4
1586
 
 
1587
 
    def get_format_string(self):
1588
 
        """See WorkingTreeFormat.get_format_string()."""
1589
 
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
1590
 
 
1591
 
    def get_format_description(self):
1592
 
        """See WorkingTreeFormat.get_format_description()."""
1593
 
        return "Working tree format 4"
1594
 
 
1595
 
 
1596
 
class WorkingTreeFormat5(DirStateWorkingTreeFormat):
1597
 
    """WorkingTree format supporting content filtering.
1598
 
    """
1599
 
 
1600
 
    upgrade_recommended = False
1601
 
 
1602
 
    _tree_class = WorkingTree5
1603
 
 
1604
 
    def get_format_string(self):
1605
 
        """See WorkingTreeFormat.get_format_string()."""
1606
 
        return "Bazaar Working Tree Format 5 (bzr 1.11)\n"
1607
 
 
1608
 
    def get_format_description(self):
1609
 
        """See WorkingTreeFormat.get_format_description()."""
1610
 
        return "Working tree format 5"
1611
 
 
1612
 
    def supports_content_filtering(self):
1613
 
        return True
1614
 
 
1615
 
 
1616
 
class WorkingTreeFormat6(DirStateWorkingTreeFormat):
1617
 
    """WorkingTree format supporting views.
1618
 
    """
1619
 
 
1620
 
    upgrade_recommended = False
1621
 
 
1622
 
    _tree_class = WorkingTree6
1623
 
 
1624
 
    def get_format_string(self):
1625
 
        """See WorkingTreeFormat.get_format_string()."""
1626
 
        return "Bazaar Working Tree Format 6 (bzr 1.14)\n"
1627
 
 
1628
 
    def get_format_description(self):
1629
 
        """See WorkingTreeFormat.get_format_description()."""
1630
 
        return "Working tree format 6"
1631
 
 
1632
 
    def _init_custom_control_files(self, wt):
1633
 
        """Subclasses with custom control files should override this method."""
1634
 
        wt._transport.put_bytes('views', '', mode=wt.bzrdir._get_file_mode())
1635
 
 
1636
 
    def supports_content_filtering(self):
1637
 
        return True
1638
 
 
1639
 
    def supports_views(self):
1640
 
        return True
1641
 
 
1642
 
 
1643
 
class DirStateRevisionTree(InventoryTree):
1644
 
    """A revision tree pulling the inventory from a dirstate.
1645
 
    
1646
 
    Note that this is one of the historical (ie revision) trees cached in the
1647
 
    dirstate for easy access, not the workingtree.
1648
 
    """
 
1317
class DirStateRevisionTree(Tree):
 
1318
    """A revision tree pulling the inventory from a dirstate."""
1649
1319
 
1650
1320
    def __init__(self, dirstate, revision_id, repository):
1651
1321
        self._dirstate = dirstate
1652
 
        self._revision_id = revision_id
 
1322
        self._revision_id = osutils.safe_revision_id(revision_id)
1653
1323
        self._repository = repository
1654
1324
        self._inventory = None
1655
1325
        self._locked = 0
1656
1326
        self._dirstate_locked = False
1657
 
        self._repo_supports_tree_reference = getattr(
1658
 
            repository._format, "supports_tree_reference",
1659
 
            False)
1660
1327
 
1661
1328
    def __repr__(self):
1662
1329
        return "<%s of %s in %s>" % \
1663
1330
            (self.__class__.__name__, self._revision_id, self._dirstate)
1664
1331
 
1665
 
    def annotate_iter(self, file_id,
1666
 
                      default_revision=_mod_revision.CURRENT_REVISION):
 
1332
    def annotate_iter(self, file_id):
1667
1333
        """See Tree.annotate_iter"""
1668
 
        text_key = (file_id, self.get_file_revision(file_id))
1669
 
        annotations = self._repository.texts.annotate(text_key)
1670
 
        return [(key[-1], line) for (key, line) in annotations]
 
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)
1671
1337
 
1672
 
    def _get_ancestors(self, default_revision):
1673
 
        return set(self._repository.get_ancestry(self._revision_id,
1674
 
                                                 topo_sorted=False))
1675
1338
    def _comparison_data(self, entry, path):
1676
1339
        """See Tree._comparison_data."""
1677
1340
        if entry is None:
1694
1357
    def get_root_id(self):
1695
1358
        return self.path2id('')
1696
1359
 
1697
 
    def id2path(self, file_id):
1698
 
        "Convert a file-id to a path."
1699
 
        entry = self._get_entry(file_id=file_id)
1700
 
        if entry == (None, None):
1701
 
            raise errors.NoSuchId(tree=self, file_id=file_id)
1702
 
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
1703
 
        return path_utf8.decode('utf8')
1704
 
 
1705
 
    def iter_references(self):
1706
 
        if not self._repo_supports_tree_reference:
1707
 
            # When the repo doesn't support references, we will have nothing to
1708
 
            # return
1709
 
            return iter([])
1710
 
        # Otherwise, fall back to the default implementation
1711
 
        return super(DirStateRevisionTree, self).iter_references()
1712
 
 
1713
1360
    def _get_parent_index(self):
1714
1361
        """Return the index in the dirstate referenced by this tree."""
1715
1362
        return self._dirstate.get_parent_ids().index(self._revision_id) + 1
1720
1367
        If either file_id or path is supplied, it is used as the key to lookup.
1721
1368
        If both are supplied, the fastest lookup is used, and an error is
1722
1369
        raised if they do not both point at the same row.
1723
 
 
 
1370
        
1724
1371
        :param file_id: An optional unicode file_id to be looked up.
1725
1372
        :param path: An optional unicode path to be looked up.
1726
1373
        :return: The dirstate row tuple for path/file_id, or (None, None)
1727
1374
        """
1728
1375
        if file_id is None and path is None:
1729
1376
            raise errors.BzrError('must supply file_id or path')
 
1377
        file_id = osutils.safe_file_id(file_id)
1730
1378
        if path is not None:
1731
1379
            path = path.encode('utf8')
1732
1380
        parent_index = self._get_parent_index()
1740
1388
 
1741
1389
        This is relatively expensive: we have to walk the entire dirstate.
1742
1390
        """
1743
 
        if not self._locked:
1744
 
            raise AssertionError(
1745
 
                'cannot generate inventory of an unlocked '
1746
 
                'dirstate revision tree')
 
1391
        assert self._locked, 'cannot generate inventory of an unlocked '\
 
1392
            'dirstate revision tree'
1747
1393
        # separate call for profiling - makes it clear where the costs are.
1748
1394
        self._dirstate._read_dirblocks_if_needed()
1749
 
        if self._revision_id not in self._dirstate.get_parent_ids():
1750
 
            raise AssertionError(
1751
 
                'parent %s has disappeared from %s' % (
1752
 
                self._revision_id, self._dirstate.get_parent_ids()))
 
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())
1753
1398
        parent_index = self._dirstate.get_parent_ids().index(self._revision_id) + 1
1754
1399
        # This is identical now to the WorkingTree _generate_inventory except
1755
1400
        # for the tree index use.
1756
1401
        root_key, current_entry = self._dirstate._get_entry(parent_index, path_utf8='')
1757
1402
        current_id = root_key[2]
1758
 
        if current_entry[parent_index][0] != 'd':
1759
 
            raise AssertionError()
 
1403
        assert current_entry[parent_index][0] == 'd'
1760
1404
        inv = Inventory(root_id=current_id, revision_id=self._revision_id)
1761
1405
        inv.root.revision = current_entry[parent_index][4]
1762
1406
        # Turn some things into local variables
1793
1437
                elif kind == 'directory':
1794
1438
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
1795
1439
                elif kind == 'symlink':
 
1440
                    inv_entry.executable = False
 
1441
                    inv_entry.text_size = None
1796
1442
                    inv_entry.symlink_target = utf8_decode(fingerprint)[0]
1797
1443
                elif kind == 'tree-reference':
1798
1444
                    inv_entry.reference_revision = fingerprint or None
1800
1446
                    raise AssertionError("cannot convert entry %r into an InventoryEntry"
1801
1447
                            % entry)
1802
1448
                # These checks cost us around 40ms on a 55k entry tree
1803
 
                if file_id in inv_byid:
1804
 
                    raise AssertionError('file_id %s already in'
1805
 
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
1806
 
                if name_unicode in parent_ie.children:
1807
 
                    raise AssertionError('name %r already in parent'
1808
 
                        % (name_unicode,))
 
1449
                assert file_id not in inv_byid
 
1450
                assert name_unicode not in parent_ie.children
1809
1451
                inv_byid[file_id] = inv_entry
1810
1452
                parent_ie.children[name_unicode] = inv_entry
1811
1453
        self._inventory = inv
1821
1463
            return None
1822
1464
        parent_index = self._get_parent_index()
1823
1465
        last_changed_revision = entry[1][parent_index][4]
1824
 
        try:
1825
 
            rev = self._repository.get_revision(last_changed_revision)
1826
 
        except errors.NoSuchRevision:
1827
 
            raise errors.FileTimestampUnavailable(self.id2path(file_id))
1828
 
        return rev.timestamp
 
1466
        return self._repository.get_revision(last_changed_revision).timestamp
1829
1467
 
1830
1468
    def get_file_sha1(self, file_id, path=None, stat_value=None):
1831
1469
        entry = self._get_entry(file_id=file_id, path=path)
1835
1473
            return parent_details[1]
1836
1474
        return None
1837
1475
 
1838
 
    @needs_read_lock
1839
 
    def get_file_revision(self, file_id):
1840
 
        return self.inventory[file_id].revision
1841
 
 
1842
 
    def get_file(self, file_id, path=None):
 
1476
    def get_file(self, file_id):
1843
1477
        return StringIO(self.get_file_text(file_id))
1844
1478
 
 
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
 
1845
1484
    def get_file_size(self, file_id):
1846
 
        """See Tree.get_file_size"""
1847
1485
        return self.inventory[file_id].text_size
1848
1486
 
1849
 
    def get_file_text(self, file_id, path=None):
1850
 
        _, content = list(self.iter_files_bytes([(file_id, None)]))[0]
1851
 
        return ''.join(content)
 
1487
    def get_file_text(self, file_id):
 
1488
        return ''.join(self.get_file_lines(file_id))
1852
1489
 
1853
1490
    def get_reference_revision(self, file_id, path=None):
1854
1491
        return self.inventory[file_id].reference_revision
1855
1492
 
1856
 
    def iter_files_bytes(self, desired_files):
1857
 
        """See Tree.iter_files_bytes.
1858
 
 
1859
 
        This version is implemented on top of Repository.iter_files_bytes"""
1860
 
        parent_index = self._get_parent_index()
1861
 
        repo_desired_files = []
1862
 
        for file_id, identifier in desired_files:
1863
 
            entry = self._get_entry(file_id)
1864
 
            if entry == (None, None):
1865
 
                raise errors.NoSuchId(self, file_id)
1866
 
            repo_desired_files.append((file_id, entry[1][parent_index][4],
1867
 
                                       identifier))
1868
 
        return self._repository.iter_files_bytes(repo_desired_files)
1869
 
 
1870
1493
    def get_symlink_target(self, file_id):
1871
1494
        entry = self._get_entry(file_id=file_id)
1872
1495
        parent_index = self._get_parent_index()
1873
1496
        if entry[1][parent_index][0] != 'l':
1874
1497
            return None
1875
1498
        else:
1876
 
            target = entry[1][parent_index][1]
1877
 
            target = target.decode('utf8')
1878
 
            return target
 
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]
1879
1503
 
1880
1504
    def get_revision_id(self):
1881
1505
        """Return the revision id for this tree."""
1899
1523
        return bool(self.path2id(filename))
1900
1524
 
1901
1525
    def kind(self, file_id):
1902
 
        entry = self._get_entry(file_id=file_id)[1]
1903
 
        if entry is None:
1904
 
            raise errors.NoSuchId(tree=self, file_id=file_id)
1905
 
        parent_index = self._get_parent_index()
1906
 
        return dirstate.DirState._minikind_to_kind[entry[parent_index][0]]
1907
 
 
1908
 
    def stored_kind(self, file_id):
1909
 
        """See Tree.stored_kind"""
1910
 
        return self.kind(file_id)
1911
 
 
1912
 
    def path_content_summary(self, path):
1913
 
        """See Tree.path_content_summary."""
1914
 
        id = self.inventory.path2id(path)
1915
 
        if id is None:
1916
 
            return ('missing', None, None, None)
1917
 
        entry = self._inventory[id]
1918
 
        kind = entry.kind
1919
 
        if kind == 'file':
1920
 
            return (kind, entry.text_size, entry.executable, entry.text_sha1)
1921
 
        elif kind == 'symlink':
1922
 
            return (kind, None, None, entry.symlink_target)
1923
 
        else:
1924
 
            return (kind, None, None, None)
 
1526
        return self.inventory[file_id].kind
1925
1527
 
1926
1528
    def is_executable(self, file_id, path=None):
1927
1529
        ie = self.inventory[file_id]
1928
1530
        if ie.kind != "file":
1929
 
            return False
 
1531
            return None
1930
1532
        return ie.executable
1931
1533
 
1932
 
    def is_locked(self):
1933
 
        return self._locked
1934
 
 
1935
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
1534
    def list_files(self, include_root=False):
1936
1535
        # We use a standard implementation, because DirStateRevisionTree is
1937
1536
        # dealing with one of the parents of the current state
1938
1537
        inv = self._get_inventory()
1939
 
        if from_dir is None:
1940
 
            from_dir_id = None
1941
 
        else:
1942
 
            from_dir_id = inv.path2id(from_dir)
1943
 
            if from_dir_id is None:
1944
 
                # Directory not versioned
1945
 
                return
1946
 
        entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
1947
 
        if inv.root is not None and not include_root and from_dir is None:
 
1538
        entries = inv.iter_entries()
 
1539
        if self.inventory.root is not None and not include_root:
1948
1540
            entries.next()
1949
1541
        for path, entry in entries:
1950
1542
            yield path, 'V', entry.kind, entry.file_id, entry
1951
1543
 
1952
1544
    def lock_read(self):
1953
 
        """Lock the tree for a set of operations.
1954
 
 
1955
 
        :return: A bzrlib.lock.LogicalLockResult.
1956
 
        """
 
1545
        """Lock the tree for a set of operations."""
1957
1546
        if not self._locked:
1958
1547
            self._repository.lock_read()
1959
1548
            if self._dirstate._lock_token is None:
1960
1549
                self._dirstate.lock_read()
1961
1550
                self._dirstate_locked = True
1962
1551
        self._locked += 1
1963
 
        return LogicalLockResult(self.unlock)
1964
1552
 
1965
1553
    def _must_be_locked(self):
1966
1554
        if not self._locked:
1987
1575
                self._dirstate_locked = False
1988
1576
            self._repository.unlock()
1989
1577
 
1990
 
    @needs_read_lock
1991
 
    def supports_tree_reference(self):
1992
 
        return self._repo_supports_tree_reference
1993
 
 
1994
1578
    def walkdirs(self, prefix=""):
1995
1579
        # TODO: jam 20070215 This is the lazy way by using the RevisionTree
1996
 
        # implementation based on an inventory.
 
1580
        # implementation based on an inventory.  
1997
1581
        # This should be cleaned up to use the much faster Dirstate code
1998
1582
        # So for now, we just build up the parent inventory, and extract
1999
1583
        # it the same way RevisionTree does.
2028
1612
 
2029
1613
class InterDirStateTree(InterTree):
2030
1614
    """Fast path optimiser for changes_from with dirstate trees.
2031
 
 
2032
 
    This is used only when both trees are in the dirstate working file, and
2033
 
    the source is any parent within the dirstate, and the destination is
 
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 
2034
1618
    the current working tree of the same dirstate.
2035
1619
    """
2036
1620
    # this could be generalized to allow comparisons between any trees in the
2045
1629
    def make_source_parent_tree(source, target):
2046
1630
        """Change the source tree into a parent of the target."""
2047
1631
        revid = source.commit('record tree')
2048
 
        target.branch.fetch(source.branch, revid)
 
1632
        target.branch.repository.fetch(source.branch.repository, revid)
2049
1633
        target.set_parent_ids([revid])
2050
1634
        return target.basis_tree(), target
2051
1635
 
2052
 
    @classmethod
2053
 
    def make_source_parent_tree_python_dirstate(klass, test_case, source, target):
2054
 
        result = klass.make_source_parent_tree(source, target)
2055
 
        result[1]._iter_changes = dirstate.ProcessEntryPython
2056
 
        return result
2057
 
 
2058
 
    @classmethod
2059
 
    def make_source_parent_tree_compiled_dirstate(klass, test_case, source,
2060
 
                                                  target):
2061
 
        from bzrlib.tests.test__dirstate_helpers import \
2062
 
            compiled_dirstate_helpers_feature
2063
 
        test_case.requireFeature(compiled_dirstate_helpers_feature)
2064
 
        from bzrlib._dirstate_helpers_pyx import ProcessEntryC
2065
 
        result = klass.make_source_parent_tree(source, target)
2066
 
        result[1]._iter_changes = ProcessEntryC
2067
 
        return result
2068
 
 
2069
1636
    _matching_from_tree_format = WorkingTreeFormat4()
2070
1637
    _matching_to_tree_format = WorkingTreeFormat4()
2071
 
 
2072
 
    @classmethod
2073
 
    def _test_mutable_trees_to_test_trees(klass, test_case, source, target):
2074
 
        # This method shouldn't be called, because we have python and C
2075
 
        # specific flavours.
2076
 
        raise NotImplementedError
2077
 
 
2078
 
    def iter_changes(self, include_unchanged=False,
 
1638
    _test_mutable_trees_to_test_trees = make_source_parent_tree
 
1639
 
 
1640
    def _iter_changes(self, include_unchanged=False,
2079
1641
                      specific_files=None, pb=None, extra_trees=[],
2080
1642
                      require_versioned=True, want_unversioned=False):
2081
1643
        """Return the changes from source to target.
2082
1644
 
2083
 
        :return: An iterator that yields tuples. See InterTree.iter_changes
 
1645
        :return: An iterator that yields tuples. See InterTree._iter_changes
2084
1646
            for details.
2085
1647
        :param specific_files: An optional list of file paths to restrict the
2086
1648
            comparison to. When mapping filenames to ids, all matches in all
2097
1659
            output. An unversioned file is defined as one with (False, False)
2098
1660
            for the versioned pair.
2099
1661
        """
 
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
2100
1666
        # TODO: handle extra trees in the dirstate.
2101
 
        if (extra_trees or specific_files == []):
 
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):
2102
1670
            # we can't fast-path these cases (yet)
2103
 
            return super(InterDirStateTree, self).iter_changes(
 
1671
            for f in super(InterDirStateTree, self)._iter_changes(
2104
1672
                include_unchanged, specific_files, pb, extra_trees,
2105
 
                require_versioned, want_unversioned=want_unversioned)
 
1673
                require_versioned, want_unversioned=want_unversioned):
 
1674
                yield f
 
1675
            return
2106
1676
        parent_ids = self.target.get_parent_ids()
2107
 
        if not (self.source._revision_id in parent_ids
2108
 
                or self.source._revision_id == _mod_revision.NULL_REVISION):
2109
 
            raise AssertionError(
2110
 
                "revision {%s} is not stored in {%s}, but %s "
2111
 
                "can only be used for trees stored in the dirstate"
2112
 
                % (self.source._revision_id, self.target, self.iter_changes))
 
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)
2113
1681
        target_index = 0
2114
 
        if self.source._revision_id == _mod_revision.NULL_REVISION:
 
1682
        if self.source._revision_id == NULL_REVISION:
2115
1683
            source_index = None
2116
1684
            indices = (target_index,)
2117
1685
        else:
2118
 
            if not (self.source._revision_id in parent_ids):
2119
 
                raise AssertionError(
2120
 
                    "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
2121
 
                    self.source._revision_id, parent_ids))
 
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)
2122
1689
            source_index = 1 + parent_ids.index(self.source._revision_id)
2123
 
            indices = (source_index, target_index)
 
1690
            indices = (source_index,target_index)
2124
1691
        # -- make all specific_files utf8 --
2125
1692
        if specific_files:
2126
1693
            specific_files_utf8 = set()
2127
1694
            for path in specific_files:
2128
 
                # Note, if there are many specific files, using cache_utf8
2129
 
                # would be good here.
2130
1695
                specific_files_utf8.add(path.encode('utf8'))
2131
1696
            specific_files = specific_files_utf8
2132
1697
        else:
2133
1698
            specific_files = set([''])
2134
1699
        # -- specific_files is now a utf8 path set --
2135
 
 
2136
1700
        # -- get the state object and prepare it.
2137
1701
        state = self.target.current_dirstate()
2138
1702
        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
2139
1721
        if require_versioned:
2140
1722
            # -- check all supplied paths are versioned in a search tree. --
2141
 
            not_versioned = []
 
1723
            all_versioned = True
2142
1724
            for path in specific_files:
2143
 
                path_entries = state._entries_for_path(path)
 
1725
                path_entries = _entries_for_path(path)
2144
1726
                if not path_entries:
2145
1727
                    # this specified path is not present at all: error
2146
 
                    not_versioned.append(path)
2147
 
                    continue
 
1728
                    all_versioned = False
 
1729
                    break
2148
1730
                found_versioned = False
2149
1731
                # for each id at this path
2150
1732
                for entry in path_entries:
2157
1739
                if not found_versioned:
2158
1740
                    # none of the indexes was not 'absent' at all ids for this
2159
1741
                    # path.
2160
 
                    not_versioned.append(path)
2161
 
            if len(not_versioned) > 0:
2162
 
                raise errors.PathsNotVersionedError(not_versioned)
 
1742
                    all_versioned = False
 
1743
                    break
 
1744
            if not all_versioned:
 
1745
                raise errors.PathsNotVersionedError(specific_files)
2163
1746
        # -- remove redundancy in supplied specific_files to prevent over-scanning --
2164
 
        search_specific_files = osutils.minimum_path_selection(specific_files)
 
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]
2165
1798
 
2166
1799
        use_filesystem_for_exec = (sys.platform != 'win32')
2167
 
        iter_changes = self.target._iter_changes(include_unchanged,
2168
 
            use_filesystem_for_exec, search_specific_files, state,
2169
 
            source_index, target_index, want_unversioned, self.target)
2170
 
        return iter_changes.iter_changes()
 
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
 
2171
2338
 
2172
2339
    @staticmethod
2173
2340
    def is_compatible(source, target):
2174
2341
        # the target must be a dirstate working tree
2175
 
        if not isinstance(target, DirStateWorkingTree):
 
2342
        if not isinstance(target, WorkingTree4):
2176
2343
            return False
2177
 
        # the source must be a revtree or dirstate rev tree.
 
2344
        # the source must be a revtreee or dirstate rev tree.
2178
2345
        if not isinstance(source,
2179
2346
            (revisiontree.RevisionTree, DirStateRevisionTree)):
2180
2347
            return False
2181
2348
        # the source revid must be in the target dirstate
2182
 
        if not (source._revision_id == _mod_revision.NULL_REVISION or
 
2349
        if not (source._revision_id == NULL_REVISION or
2183
2350
            source._revision_id in target.get_parent_ids()):
2184
 
            # TODO: what about ghosts? it may well need to
 
2351
            # TODO: what about ghosts? it may well need to 
2185
2352
            # check for them explicitly.
2186
2353
            return False
2187
2354
        return True
2197
2364
 
2198
2365
    def convert(self, tree):
2199
2366
        # lock the control files not the tree, so that we dont get tree
2200
 
        # on-unlock behaviours, and so that noone else diddles with the
 
2367
        # on-unlock behaviours, and so that noone else diddles with the 
2201
2368
        # tree during upgrade.
2202
2369
        tree._control_files.lock_write()
2203
2370
        try:
2229
2396
 
2230
2397
    def update_format(self, tree):
2231
2398
        """Change the format marker."""
2232
 
        tree._transport.put_bytes('format',
2233
 
            self.target_format.get_format_string(),
2234
 
            mode=tree.bzrdir._get_file_mode())
2235
 
 
2236
 
 
2237
 
class Converter4to5(object):
2238
 
    """Perform an in-place upgrade of format 4 to format 5 trees."""
2239
 
 
2240
 
    def __init__(self):
2241
 
        self.target_format = WorkingTreeFormat5()
2242
 
 
2243
 
    def convert(self, tree):
2244
 
        # lock the control files not the tree, so that we don't get tree
2245
 
        # on-unlock behaviours, and so that no-one else diddles with the
2246
 
        # tree during upgrade.
2247
 
        tree._control_files.lock_write()
2248
 
        try:
2249
 
            self.update_format(tree)
2250
 
        finally:
2251
 
            tree._control_files.unlock()
2252
 
 
2253
 
    def update_format(self, tree):
2254
 
        """Change the format marker."""
2255
 
        tree._transport.put_bytes('format',
2256
 
            self.target_format.get_format_string(),
2257
 
            mode=tree.bzrdir._get_file_mode())
2258
 
 
2259
 
 
2260
 
class Converter4or5to6(object):
2261
 
    """Perform an in-place upgrade of format 4 or 5 to format 6 trees."""
2262
 
 
2263
 
    def __init__(self):
2264
 
        self.target_format = WorkingTreeFormat6()
2265
 
 
2266
 
    def convert(self, tree):
2267
 
        # lock the control files not the tree, so that we don't get tree
2268
 
        # on-unlock behaviours, and so that no-one else diddles with the
2269
 
        # tree during upgrade.
2270
 
        tree._control_files.lock_write()
2271
 
        try:
2272
 
            self.init_custom_control_files(tree)
2273
 
            self.update_format(tree)
2274
 
        finally:
2275
 
            tree._control_files.unlock()
2276
 
 
2277
 
    def init_custom_control_files(self, tree):
2278
 
        """Initialize custom control files."""
2279
 
        tree._transport.put_bytes('views', '',
2280
 
            mode=tree.bzrdir._get_file_mode())
2281
 
 
2282
 
    def update_format(self, tree):
2283
 
        """Change the format marker."""
2284
 
        tree._transport.put_bytes('format',
2285
 
            self.target_format.get_format_string(),
2286
 
            mode=tree.bzrdir._get_file_mode())
 
2399
        tree._control_files.put_utf8('format',
 
2400
            self.target_format.get_format_string())