1
# Copyright (C) 2005, 2006 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""WorkingTree object and friends.
19
A WorkingTree represents the editable working copy of a branch.
20
Operations which represent the WorkingTree are also done here,
21
such as renaming or adding files. The WorkingTree has an inventory
22
which is updated by these operations. A commit produces a
23
new revision based on the workingtree and its inventory.
25
At the moment every WorkingTree has its own branch. Remote
26
WorkingTrees aren't supported.
28
To get a WorkingTree, call bzrdir.open_workingtree() or
29
WorkingTree.open(dir).
32
# TODO: Give the workingtree sole responsibility for the working inventory;
33
# remove the variable and references to it from the branch. This may require
34
# updating the commit code so as to update the inventory within the working
35
# copy, and making sure there's only one WorkingTree for any directory on disk.
36
# At the moment they may alias the inventory and have old copies of it in
37
# memory. (Now done? -- mbp 20060309)
39
from cStringIO import StringIO
42
from bzrlib.lazy_import import lazy_import
43
lazy_import(globals(), """
45
from copy import deepcopy
55
conflicts as _mod_conflicts,
72
from bzrlib.transport import get_transport
76
from bzrlib import symbol_versioning
77
from bzrlib.decorators import needs_read_lock, needs_write_lock
78
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
79
from bzrlib.lockable_files import LockableFiles, TransportLock
80
from bzrlib.lockdir import LockDir
81
import bzrlib.mutabletree
82
from bzrlib.mutabletree import needs_tree_write_lock
83
from bzrlib.osutils import (
95
from bzrlib.trace import mutter, note
96
from bzrlib.transport.local import LocalTransport
98
from bzrlib.progress import DummyProgress, ProgressPhase
99
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
100
import bzrlib.revisiontree
101
from bzrlib.rio import RioReader, rio_file, Stanza
102
from bzrlib.symbol_versioning import (deprecated_passed,
105
DEPRECATED_PARAMETER,
112
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
113
CONFLICT_HEADER_1 = "BZR conflict list format 1"
116
@deprecated_function(zero_thirteen)
117
def gen_file_id(name):
118
"""Return new file id for the basename 'name'.
120
Use bzrlib.generate_ids.gen_file_id() instead
122
return generate_ids.gen_file_id(name)
125
@deprecated_function(zero_thirteen)
127
"""Return a new tree-root file id.
129
This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
131
return generate_ids.gen_root_id()
134
class TreeEntry(object):
135
"""An entry that implements the minimum interface used by commands.
137
This needs further inspection, it may be better to have
138
InventoryEntries without ids - though that seems wrong. For now,
139
this is a parallel hierarchy to InventoryEntry, and needs to become
140
one of several things: decorates to that hierarchy, children of, or
142
Another note is that these objects are currently only used when there is
143
no InventoryEntry available - i.e. for unversioned objects.
144
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
147
def __eq__(self, other):
148
# yes, this us ugly, TODO: best practice __eq__ style.
149
return (isinstance(other, TreeEntry)
150
and other.__class__ == self.__class__)
152
def kind_character(self):
156
class TreeDirectory(TreeEntry):
157
"""See TreeEntry. This is a directory in a working tree."""
159
def __eq__(self, other):
160
return (isinstance(other, TreeDirectory)
161
and other.__class__ == self.__class__)
163
def kind_character(self):
167
class TreeFile(TreeEntry):
168
"""See TreeEntry. This is a regular file in a working tree."""
170
def __eq__(self, other):
171
return (isinstance(other, TreeFile)
172
and other.__class__ == self.__class__)
174
def kind_character(self):
178
class TreeLink(TreeEntry):
179
"""See TreeEntry. This is a symlink in a working tree."""
181
def __eq__(self, other):
182
return (isinstance(other, TreeLink)
183
and other.__class__ == self.__class__)
185
def kind_character(self):
189
class WorkingTree(bzrlib.mutabletree.MutableTree):
190
"""Working copy tree.
192
The inventory is held in the `Branch` working-inventory, and the
193
files are in a directory on disk.
195
It is possible for a `WorkingTree` to have a filename which is
196
not listed in the Inventory and vice versa.
199
def __init__(self, basedir='.',
200
branch=DEPRECATED_PARAMETER,
206
"""Construct a WorkingTree for basedir.
208
If the branch is not supplied, it is opened automatically.
209
If the branch is supplied, it must be the branch for this basedir.
210
(branch.base is not cross checked, because for remote branches that
211
would be meaningless).
213
self._format = _format
214
self.bzrdir = _bzrdir
216
# not created via open etc.
217
warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
218
"Please use bzrdir.open_workingtree or WorkingTree.open().",
221
wt = WorkingTree.open(basedir)
222
self._branch = wt.branch
223
self.basedir = wt.basedir
224
self._control_files = wt._control_files
225
self._hashcache = wt._hashcache
226
self._set_inventory(wt._inventory, dirty=False)
227
self._format = wt._format
228
self.bzrdir = wt.bzrdir
229
assert isinstance(basedir, basestring), \
230
"base directory %r is not a string" % basedir
231
basedir = safe_unicode(basedir)
232
mutter("opening working tree %r", basedir)
233
if deprecated_passed(branch):
235
warnings.warn("WorkingTree(..., branch=XXX) is deprecated"
236
" as of bzr 0.8. Please use bzrdir.open_workingtree() or"
237
" WorkingTree.open().",
241
self._branch = branch
243
self._branch = self.bzrdir.open_branch()
244
self.basedir = realpath(basedir)
245
# if branch is at our basedir and is a format 6 or less
246
if isinstance(self._format, WorkingTreeFormat2):
247
# share control object
248
self._control_files = self.branch.control_files
250
# assume all other formats have their own control files.
251
assert isinstance(_control_files, LockableFiles), \
252
"_control_files must be a LockableFiles, not %r" \
254
self._control_files = _control_files
255
# update the whole cache up front and write to disk if anything changed;
256
# in the future we might want to do this more selectively
257
# two possible ways offer themselves : in self._unlock, write the cache
258
# if needed, or, when the cache sees a change, append it to the hash
259
# cache file, and have the parser take the most recent entry for a
261
wt_trans = self.bzrdir.get_workingtree_transport(None)
262
cache_filename = wt_trans.local_abspath('stat-cache')
263
self._hashcache = hashcache.HashCache(basedir, cache_filename,
264
self._control_files._file_mode)
267
# is this scan needed ? it makes things kinda slow.
274
if _inventory is None:
275
self._inventory_is_modified = False
276
self.read_working_inventory()
278
# the caller of __init__ has provided an inventory,
279
# we assume they know what they are doing - as its only
280
# the Format factory and creation methods that are
281
# permitted to do this.
282
self._set_inventory(_inventory, dirty=False)
285
fget=lambda self: self._branch,
286
doc="""The branch this WorkingTree is connected to.
288
This cannot be set - it is reflective of the actual disk structure
289
the working tree has been constructed from.
292
def break_lock(self):
293
"""Break a lock if one is present from another instance.
295
Uses the ui factory to ask for confirmation if the lock may be from
298
This will probe the repository for its lock as well.
300
self._control_files.break_lock()
301
self.branch.break_lock()
303
def requires_rich_root(self):
304
return self._format.requires_rich_root
306
def supports_tree_reference(self):
307
return getattr(self._format, 'supports_tree_reference', False)
309
def _set_inventory(self, inv, dirty):
310
"""Set the internal cached inventory.
312
:param inv: The inventory to set.
313
:param dirty: A boolean indicating whether the inventory is the same
314
logical inventory as whats on disk. If True the inventory is not
315
the same and should be written to disk or data will be lost, if
316
False then the inventory is the same as that on disk and any
317
serialisation would be unneeded overhead.
319
assert inv.root is not None
320
self._inventory = inv
321
self._inventory_is_modified = dirty
324
def open(path=None, _unsupported=False):
325
"""Open an existing working tree at path.
329
path = os.path.getcwdu()
330
control = bzrdir.BzrDir.open(path, _unsupported)
331
return control.open_workingtree(_unsupported)
334
def open_containing(path=None):
335
"""Open an existing working tree which has its root about path.
337
This probes for a working tree at path and searches upwards from there.
339
Basically we keep looking up until we find the control directory or
340
run into /. If there isn't one, raises NotBranchError.
341
TODO: give this a new exception.
342
If there is one, it is returned, along with the unused portion of path.
344
:return: The WorkingTree that contains 'path', and the rest of path
347
path = osutils.getcwd()
348
control, relpath = bzrdir.BzrDir.open_containing(path)
350
return control.open_workingtree(), relpath
353
def open_downlevel(path=None):
354
"""Open an unsupported working tree.
356
Only intended for advanced situations like upgrading part of a bzrdir.
358
return WorkingTree.open(path, _unsupported=True)
361
"""Iterate through file_ids for this tree.
363
file_ids are in a WorkingTree if they are in the working inventory
364
and the working file exists.
366
inv = self._inventory
367
for path, ie in inv.iter_entries():
368
if osutils.lexists(self.abspath(path)):
372
return "<%s of %s>" % (self.__class__.__name__,
373
getattr(self, 'basedir', None))
375
def abspath(self, filename):
376
return pathjoin(self.basedir, filename)
378
def basis_tree(self):
379
"""Return RevisionTree for the current last revision.
381
If the left most parent is a ghost then the returned tree will be an
382
empty tree - one obtained by calling repository.revision_tree(None).
385
revision_id = self.get_parent_ids()[0]
387
# no parents, return an empty revision tree.
388
# in the future this should return the tree for
389
# 'empty:' - the implicit root empty tree.
390
return self.branch.repository.revision_tree(None)
393
xml = self.read_basis_inventory()
394
inv = xml6.serializer_v6.read_inventory_from_string(xml)
395
if inv is not None and inv.revision_id == revision_id:
396
return bzrlib.revisiontree.RevisionTree(
397
self.branch.repository, inv, revision_id)
398
except (errors.NoSuchFile, errors.BadInventoryFormat):
400
# No cached copy available, retrieve from the repository.
401
# FIXME? RBC 20060403 should we cache the inventory locally
404
return self.branch.repository.revision_tree(revision_id)
405
except errors.RevisionNotPresent:
406
# the basis tree *may* be a ghost or a low level error may have
407
# occured. If the revision is present, its a problem, if its not
409
if self.branch.repository.has_revision(revision_id):
411
# the basis tree is a ghost so return an empty tree.
412
return self.branch.repository.revision_tree(None)
415
@deprecated_method(zero_eight)
416
def create(branch, directory):
417
"""Create a workingtree for branch at directory.
419
If existing_directory already exists it must have a .bzr directory.
420
If it does not exist, it will be created.
422
This returns a new WorkingTree object for the new checkout.
424
TODO FIXME RBC 20060124 when we have checkout formats in place this
425
should accept an optional revisionid to checkout [and reject this if
426
checking out into the same dir as a pre-checkout-aware branch format.]
428
XXX: When BzrDir is present, these should be created through that
431
warnings.warn('delete WorkingTree.create', stacklevel=3)
432
transport = get_transport(directory)
433
if branch.bzrdir.root_transport.base == transport.base:
435
return branch.bzrdir.create_workingtree()
436
# different directory,
437
# create a branch reference
438
# and now a working tree.
439
raise NotImplementedError
442
@deprecated_method(zero_eight)
443
def create_standalone(directory):
444
"""Create a checkout and a branch and a repo at directory.
446
Directory must exist and be empty.
448
please use BzrDir.create_standalone_workingtree
450
return bzrdir.BzrDir.create_standalone_workingtree(directory)
452
def relpath(self, path):
453
"""Return the local path portion from a given path.
455
The path may be absolute or relative. If its a relative path it is
456
interpreted relative to the python current working directory.
458
return osutils.relpath(self.basedir, path)
460
def has_filename(self, filename):
461
return osutils.lexists(self.abspath(filename))
463
def get_file(self, file_id):
464
return self.get_file_byname(self.id2path(file_id))
466
def get_file_text(self, file_id):
467
return self.get_file(file_id).read()
469
def get_file_byname(self, filename):
470
return file(self.abspath(filename), 'rb')
472
def annotate_iter(self, file_id):
473
"""See Tree.annotate_iter
475
This implementation will use the basis tree implementation if possible.
476
Lines not in the basis are attributed to CURRENT_REVISION
478
If there are pending merges, lines added by those merges will be
479
incorrectly attributed to CURRENT_REVISION (but after committing, the
480
attribution will be correct).
482
basis = self.basis_tree()
483
changes = self._iter_changes(basis, True, [file_id]).next()
484
changed_content, kind = changes[2], changes[6]
485
if not changed_content:
486
return basis.annotate_iter(file_id)
490
if kind[0] != 'file':
493
old_lines = list(basis.annotate_iter(file_id))
495
for tree in self.branch.repository.revision_trees(
496
self.get_parent_ids()[1:]):
497
if file_id not in tree:
499
old.append(list(tree.annotate_iter(file_id)))
500
return annotate.reannotate(old, self.get_file(file_id).readlines(),
503
def get_parent_ids(self):
504
"""See Tree.get_parent_ids.
506
This implementation reads the pending merges list and last_revision
507
value and uses that to decide what the parents list should be.
509
last_rev = self._last_revision()
515
merges_file = self._control_files.get_utf8('pending-merges')
516
except errors.NoSuchFile:
519
for l in merges_file.readlines():
520
parents.append(l.rstrip('\n'))
524
def get_root_id(self):
525
"""Return the id of this trees root"""
526
return self._inventory.root.file_id
528
def _get_store_filename(self, file_id):
529
## XXX: badly named; this is not in the store at all
530
return self.abspath(self.id2path(file_id))
533
def clone(self, to_bzrdir, revision_id=None, basis=None):
534
"""Duplicate this working tree into to_bzr, including all state.
536
Specifically modified files are kept as modified, but
537
ignored and unknown files are discarded.
539
If you want to make a new line of development, see bzrdir.sprout()
542
If not None, the cloned tree will have its last revision set to
543
revision, and and difference between the source trees last revision
544
and this one merged in.
547
If not None, a closer copy of a tree which may have some files in
548
common, and which file content should be preferentially copied from.
550
# assumes the target bzr dir format is compatible.
551
result = self._format.initialize(to_bzrdir)
552
self.copy_content_into(result, revision_id)
556
def copy_content_into(self, tree, revision_id=None):
557
"""Copy the current content and user files of this tree into tree."""
558
tree.set_root_id(self.get_root_id())
559
if revision_id is None:
560
merge.transform_tree(tree, self)
562
# TODO now merge from tree.last_revision to revision (to preserve
563
# user local changes)
564
merge.transform_tree(tree, self)
565
tree.set_parent_ids([revision_id])
567
def id2abspath(self, file_id):
568
return self.abspath(self.id2path(file_id))
570
def has_id(self, file_id):
571
# files that have been deleted are excluded
572
inv = self._inventory
573
if not inv.has_id(file_id):
575
path = inv.id2path(file_id)
576
return osutils.lexists(self.abspath(path))
578
def has_or_had_id(self, file_id):
579
if file_id == self.inventory.root.file_id:
581
return self.inventory.has_id(file_id)
583
__contains__ = has_id
585
def get_file_size(self, file_id):
586
return os.path.getsize(self.id2abspath(file_id))
589
def get_file_sha1(self, file_id, path=None, stat_value=None):
591
path = self._inventory.id2path(file_id)
592
return self._hashcache.get_sha1(path, stat_value)
594
def get_file_mtime(self, file_id, path=None):
596
path = self._inventory.id2path(file_id)
597
return os.lstat(self.abspath(path)).st_mtime
599
if not supports_executable():
600
def is_executable(self, file_id, path=None):
601
return self._inventory[file_id].executable
603
def is_executable(self, file_id, path=None):
605
path = self._inventory.id2path(file_id)
606
mode = os.lstat(self.abspath(path)).st_mode
607
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
610
def _add(self, files, ids, kinds):
611
"""See MutableTree._add."""
612
# TODO: Re-adding a file that is removed in the working copy
613
# should probably put it back with the previous ID.
614
# the read and write working inventory should not occur in this
615
# function - they should be part of lock_write and unlock.
616
inv = self.read_working_inventory()
617
for f, file_id, kind in zip(files, ids, kinds):
618
assert kind is not None
620
inv.add_path(f, kind=kind)
622
inv.add_path(f, kind=kind, file_id=file_id)
623
self._write_inventory(inv)
625
def add_reference(self, sub_tree):
626
"""Add a TreeReference to the tree, pointing at sub_tree"""
627
raise errors.UnsupportedOperation(self.add_reference, self)
629
@needs_tree_write_lock
630
def _gather_kinds(self, files, kinds):
631
"""See MutableTree._gather_kinds."""
632
for pos, f in enumerate(files):
633
if kinds[pos] is None:
634
fullpath = normpath(self.abspath(f))
636
kinds[pos] = file_kind(fullpath)
638
if e.errno == errno.ENOENT:
639
raise errors.NoSuchFile(fullpath)
642
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
643
"""Add revision_id as a parent.
645
This is equivalent to retrieving the current list of parent ids
646
and setting the list to its value plus revision_id.
648
:param revision_id: The revision id to add to the parent list. It may
649
be a ghost revision as long as its not the first parent to be added,
650
or the allow_leftmost_as_ghost parameter is set True.
651
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
653
parents = self.get_parent_ids() + [revision_id]
654
self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
655
or allow_leftmost_as_ghost)
657
@needs_tree_write_lock
658
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
659
"""Add revision_id, tree tuple as a parent.
661
This is equivalent to retrieving the current list of parent trees
662
and setting the list to its value plus parent_tuple. See also
663
add_parent_tree_id - if you only have a parent id available it will be
664
simpler to use that api. If you have the parent already available, using
665
this api is preferred.
667
:param parent_tuple: The (revision id, tree) to add to the parent list.
668
If the revision_id is a ghost, pass None for the tree.
669
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
671
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
672
if len(parent_ids) > 1:
673
# the leftmost may have already been a ghost, preserve that if it
675
allow_leftmost_as_ghost = True
676
self.set_parent_ids(parent_ids,
677
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
679
@needs_tree_write_lock
680
def add_pending_merge(self, *revision_ids):
681
# TODO: Perhaps should check at this point that the
682
# history of the revision is actually present?
683
parents = self.get_parent_ids()
685
for rev_id in revision_ids:
686
if rev_id in parents:
688
parents.append(rev_id)
691
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
693
@deprecated_method(zero_eleven)
695
def pending_merges(self):
696
"""Return a list of pending merges.
698
These are revisions that have been merged into the working
699
directory but not yet committed.
701
As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
702
instead - which is available on all tree objects.
704
return self.get_parent_ids()[1:]
706
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
707
"""Common ghost checking functionality from set_parent_*.
709
This checks that the left hand-parent exists if there are any
712
if len(revision_ids) > 0:
713
leftmost_id = revision_ids[0]
714
if (not allow_leftmost_as_ghost and not
715
self.branch.repository.has_revision(leftmost_id)):
716
raise errors.GhostRevisionUnusableHere(leftmost_id)
718
def _set_merges_from_parent_ids(self, parent_ids):
719
merges = parent_ids[1:]
720
self._control_files.put_utf8('pending-merges', '\n'.join(merges))
722
@needs_tree_write_lock
723
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
724
"""Set the parent ids to revision_ids.
726
See also set_parent_trees. This api will try to retrieve the tree data
727
for each element of revision_ids from the trees repository. If you have
728
tree data already available, it is more efficient to use
729
set_parent_trees rather than set_parent_ids. set_parent_ids is however
730
an easier API to use.
732
:param revision_ids: The revision_ids to set as the parent ids of this
733
working tree. Any of these may be ghosts.
735
self._check_parents_for_ghosts(revision_ids,
736
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
738
if len(revision_ids) > 0:
739
self.set_last_revision(revision_ids[0])
741
self.set_last_revision(None)
743
self._set_merges_from_parent_ids(revision_ids)
745
@needs_tree_write_lock
746
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
747
"""See MutableTree.set_parent_trees."""
748
parent_ids = [rev for (rev, tree) in parents_list]
750
self._check_parents_for_ghosts(parent_ids,
751
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
753
if len(parent_ids) == 0:
754
leftmost_parent_id = None
755
leftmost_parent_tree = None
757
leftmost_parent_id, leftmost_parent_tree = parents_list[0]
759
if self._change_last_revision(leftmost_parent_id):
760
if leftmost_parent_tree is None:
761
# If we don't have a tree, fall back to reading the
762
# parent tree from the repository.
763
self._cache_basis_inventory(leftmost_parent_id)
765
inv = leftmost_parent_tree.inventory
766
xml = self._create_basis_xml_from_inventory(
767
leftmost_parent_id, inv)
768
self._write_basis_inventory(xml)
769
self._set_merges_from_parent_ids(parent_ids)
771
@needs_tree_write_lock
772
def set_pending_merges(self, rev_list):
773
parents = self.get_parent_ids()
774
leftmost = parents[:1]
775
new_parents = leftmost + rev_list
776
self.set_parent_ids(new_parents)
778
@needs_tree_write_lock
779
def set_merge_modified(self, modified_hashes):
781
for file_id, hash in modified_hashes.iteritems():
782
yield Stanza(file_id=file_id, hash=hash)
783
self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
785
@needs_tree_write_lock
786
def _put_rio(self, filename, stanzas, header):
787
my_file = rio_file(stanzas, header)
788
self._control_files.put(filename, my_file)
790
@needs_write_lock # because merge pulls data into the branch.
791
def merge_from_branch(self, branch, to_revision=None):
792
"""Merge from a branch into this working tree.
794
:param branch: The branch to merge from.
795
:param to_revision: If non-None, the merge will merge to to_revision,
796
but not beyond it. to_revision does not need to be in the history
797
of the branch when it is supplied. If None, to_revision defaults to
798
branch.last_revision().
800
from bzrlib.merge import Merger, Merge3Merger
801
pb = bzrlib.ui.ui_factory.nested_progress_bar()
803
merger = Merger(self.branch, this_tree=self, pb=pb)
804
merger.pp = ProgressPhase("Merge phase", 5, pb)
805
merger.pp.next_phase()
806
# check that there are no
808
merger.check_basis(check_clean=True, require_commits=False)
809
if to_revision is None:
810
to_revision = branch.last_revision()
811
merger.other_rev_id = to_revision
812
if merger.other_rev_id is None:
813
raise error.NoCommits(branch)
814
self.branch.fetch(branch, last_revision=merger.other_rev_id)
815
merger.other_basis = merger.other_rev_id
816
merger.other_tree = self.branch.repository.revision_tree(
818
merger.other_branch = branch
819
merger.pp.next_phase()
821
if merger.base_rev_id == merger.other_rev_id:
822
raise errors.PointlessMerge
823
merger.backup_files = False
824
merger.merge_type = Merge3Merger
825
merger.set_interesting_files(None)
826
merger.show_base = False
827
merger.reprocess = False
828
conflicts = merger.do_merge()
835
def subsume(self, other_tree):
836
def add_children(inventory, entry):
837
for child_entry in entry.children.values():
838
inventory._byid[child_entry.file_id] = child_entry
839
if child_entry.kind == 'directory':
840
add_children(inventory, child_entry)
841
if other_tree.get_root_id() == self.get_root_id():
842
raise errors.BadSubsumeSource(self, other_tree,
843
'Trees have the same root')
845
other_tree_path = self.relpath(other_tree.basedir)
846
except errors.PathNotChild:
847
raise errors.BadSubsumeSource(self, other_tree,
848
'Tree is not contained by the other')
849
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
850
if new_root_parent is None:
851
raise errors.BadSubsumeSource(self, other_tree,
852
'Parent directory is not versioned.')
853
# We need to ensure that the result of a fetch will have a
854
# versionedfile for the other_tree root, and only fetching into
855
# RepositoryKnit2 guarantees that.
856
if not self.branch.repository.supports_rich_root():
857
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
858
other_tree.lock_tree_write()
860
for parent_id in other_tree.get_parent_ids():
861
self.branch.fetch(other_tree.branch, parent_id)
862
self.add_parent_tree_id(parent_id)
863
other_root = other_tree.inventory.root
864
other_root.parent_id = new_root_parent
865
other_root.name = osutils.basename(other_tree_path)
866
self.inventory.add(other_root)
867
add_children(self.inventory, other_root)
868
self._write_inventory(self.inventory)
871
other_tree.bzrdir.destroy_workingtree_metadata()
873
@needs_tree_write_lock
874
def extract(self, file_id, format=None):
875
"""Extract a subtree from this tree.
877
A new branch will be created, relative to the path for this tree.
880
segments = osutils.splitpath(path)
881
transport = self.branch.bzrdir.root_transport
882
for name in segments:
883
transport = transport.clone(name)
886
except errors.FileExists:
890
sub_path = self.id2path(file_id)
891
branch_transport = mkdirs(sub_path)
893
format = bzrdir.format_registry.make_bzrdir('experimental-knit2')
895
branch_transport.mkdir('.')
896
except errors.FileExists:
898
branch_bzrdir = format.initialize_on_transport(branch_transport)
900
repo = branch_bzrdir.find_repository()
901
except errors.NoRepositoryPresent:
902
repo = branch_bzrdir.create_repository()
903
assert repo.supports_rich_root()
905
if not repo.supports_rich_root():
906
raise errors.RootNotRich()
907
new_branch = branch_bzrdir.create_branch()
908
new_branch.pull(self.branch)
909
for parent_id in self.get_parent_ids():
910
new_branch.fetch(self.branch, parent_id)
911
tree_transport = self.bzrdir.root_transport.clone(sub_path)
912
if tree_transport.base != branch_transport.base:
913
tree_bzrdir = format.initialize_on_transport(tree_transport)
914
branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
916
tree_bzrdir = branch_bzrdir
917
wt = tree_bzrdir.create_workingtree(NULL_REVISION)
918
wt.set_parent_ids(self.get_parent_ids())
919
my_inv = self.inventory
920
child_inv = Inventory(root_id=None)
921
new_root = my_inv[file_id]
922
my_inv.remove_recursive_id(file_id)
923
new_root.parent_id = None
924
child_inv.add(new_root)
925
self._write_inventory(my_inv)
926
wt._write_inventory(child_inv)
930
def merge_modified(self):
932
hashfile = self._control_files.get('merge-hashes')
933
except errors.NoSuchFile:
937
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
938
raise errors.MergeModifiedFormatError()
939
except StopIteration:
940
raise errors.MergeModifiedFormatError()
941
for s in RioReader(hashfile):
942
file_id = s.get("file_id")
943
if file_id not in self.inventory:
946
if hash == self.get_file_sha1(file_id):
947
merge_hashes[file_id] = hash
951
def mkdir(self, path, file_id=None):
952
"""See MutableTree.mkdir()."""
954
file_id = generate_ids.gen_file_id(os.path.basename(path))
955
os.mkdir(self.abspath(path))
956
self.add(path, file_id, 'directory')
959
def get_symlink_target(self, file_id):
960
return os.readlink(self.id2abspath(file_id))
962
def file_class(self, filename):
963
if self.path2id(filename):
965
elif self.is_ignored(filename):
971
"""Write the in memory inventory to disk."""
972
# TODO: Maybe this should only write on dirty ?
973
if self._control_files._lock_mode != 'w':
974
raise errors.NotWriteLocked(self)
976
self._serialize(self._inventory, sio)
978
self._control_files.put('inventory', sio)
979
self._inventory_is_modified = False
981
def _serialize(self, inventory, out_file):
982
xml5.serializer_v5.write_inventory(self._inventory, out_file)
984
def _deserialize(selt, in_file):
985
return xml5.serializer_v5.read_inventory(in_file)
987
def list_files(self, include_root=False):
988
"""Recursively list all files as (path, class, kind, id, entry).
990
Lists, but does not descend into unversioned directories.
992
This does not include files that have been deleted in this
995
Skips the control directory.
997
inv = self._inventory
998
if include_root is True:
999
yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1000
# Convert these into local objects to save lookup times
1001
pathjoin = osutils.pathjoin
1002
file_kind = osutils.file_kind
1004
# transport.base ends in a slash, we want the piece
1005
# between the last two slashes
1006
transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
1008
fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1010
# directory file_id, relative path, absolute path, reverse sorted children
1011
children = os.listdir(self.basedir)
1013
# jam 20060527 The kernel sized tree seems equivalent whether we
1014
# use a deque and popleft to keep them sorted, or if we use a plain
1015
# list and just reverse() them.
1016
children = collections.deque(children)
1017
stack = [(inv.root.file_id, u'', self.basedir, children)]
1019
from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1022
f = children.popleft()
1023
## TODO: If we find a subdirectory with its own .bzr
1024
## directory, then that is a separate tree and we
1025
## should exclude it.
1027
# the bzrdir for this tree
1028
if transport_base_dir == f:
1031
# we know that from_dir_relpath and from_dir_abspath never end in a slash
1032
# and 'f' doesn't begin with one, we can do a string op, rather
1033
# than the checks of pathjoin(), all relative paths will have an extra slash
1035
fp = from_dir_relpath + '/' + f
1038
fap = from_dir_abspath + '/' + f
1040
f_ie = inv.get_child(from_dir_id, f)
1043
elif self.is_ignored(fp[1:]):
1046
# we may not have found this file, because of a unicode issue
1047
f_norm, can_access = osutils.normalized_filename(f)
1048
if f == f_norm or not can_access:
1049
# No change, so treat this file normally
1052
# this file can be accessed by a normalized path
1053
# check again if it is versioned
1054
# these lines are repeated here for performance
1056
fp = from_dir_relpath + '/' + f
1057
fap = from_dir_abspath + '/' + f
1058
f_ie = inv.get_child(from_dir_id, f)
1061
elif self.is_ignored(fp[1:]):
1070
raise errors.BzrCheckError(
1071
"file %r entered as kind %r id %r, now of kind %r"
1072
% (fap, f_ie.kind, f_ie.file_id, fk))
1074
# make a last minute entry
1076
yield fp[1:], c, fk, f_ie.file_id, f_ie
1079
yield fp[1:], c, fk, None, fk_entries[fk]()
1081
yield fp[1:], c, fk, None, TreeEntry()
1084
if fk != 'directory':
1087
# But do this child first
1088
new_children = os.listdir(fap)
1090
new_children = collections.deque(new_children)
1091
stack.append((f_ie.file_id, fp, fap, new_children))
1092
# Break out of inner loop,
1093
# so that we start outer loop with child
1096
# if we finished all children, pop it off the stack
1099
@needs_tree_write_lock
1100
def move(self, from_paths, to_dir=None, after=False, **kwargs):
1103
to_dir must exist in the inventory.
1105
If to_dir exists and is a directory, the files are moved into
1106
it, keeping their old names.
1108
Note that to_dir is only the last component of the new name;
1109
this doesn't change the directory.
1111
For each entry in from_paths the move mode will be determined
1114
The first mode moves the file in the filesystem and updates the
1115
inventory. The second mode only updates the inventory without
1116
touching the file on the filesystem. This is the new mode introduced
1119
move uses the second mode if 'after == True' and the target is not
1120
versioned but present in the working tree.
1122
move uses the second mode if 'after == False' and the source is
1123
versioned but no longer in the working tree, and the target is not
1124
versioned but present in the working tree.
1126
move uses the first mode if 'after == False' and the source is
1127
versioned and present in the working tree, and the target is not
1128
versioned and not present in the working tree.
1130
Everything else results in an error.
1132
This returns a list of (from_path, to_path) pairs for each
1133
entry that is moved.
1138
# check for deprecated use of signature
1140
to_dir = kwargs.get('to_name', None)
1142
raise TypeError('You must supply a target directory')
1144
symbol_versioning.warn('The parameter to_name was deprecated'
1145
' in version 0.13. Use to_dir instead',
1148
# check destination directory
1149
assert not isinstance(from_paths, basestring)
1150
inv = self.inventory
1151
to_abs = self.abspath(to_dir)
1152
if not isdir(to_abs):
1153
raise errors.BzrMoveFailedError('',to_dir,
1154
errors.NotADirectory(to_abs))
1155
if not self.has_filename(to_dir):
1156
raise errors.BzrMoveFailedError('',to_dir,
1157
errors.NotInWorkingDirectory(to_dir))
1158
to_dir_id = inv.path2id(to_dir)
1159
if to_dir_id is None:
1160
raise errors.BzrMoveFailedError('',to_dir,
1161
errors.NotVersionedError(path=str(to_dir)))
1163
to_dir_ie = inv[to_dir_id]
1164
if to_dir_ie.kind != 'directory':
1165
raise errors.BzrMoveFailedError('',to_dir,
1166
errors.NotADirectory(to_abs))
1168
# create rename entries and tuples
1169
for from_rel in from_paths:
1170
from_tail = splitpath(from_rel)[-1]
1171
from_id = inv.path2id(from_rel)
1173
raise errors.BzrMoveFailedError(from_rel,to_dir,
1174
errors.NotVersionedError(path=str(from_rel)))
1176
from_entry = inv[from_id]
1177
from_parent_id = from_entry.parent_id
1178
to_rel = pathjoin(to_dir, from_tail)
1179
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1181
from_tail=from_tail,
1182
from_parent_id=from_parent_id,
1183
to_rel=to_rel, to_tail=from_tail,
1184
to_parent_id=to_dir_id)
1185
rename_entries.append(rename_entry)
1186
rename_tuples.append((from_rel, to_rel))
1188
# determine which move mode to use. checks also for movability
1189
rename_entries = self._determine_mv_mode(rename_entries, after)
1191
original_modified = self._inventory_is_modified
1194
self._inventory_is_modified = True
1195
self._move(rename_entries)
1197
# restore the inventory on error
1198
self._inventory_is_modified = original_modified
1200
self._write_inventory(inv)
1201
return rename_tuples
1203
def _determine_mv_mode(self, rename_entries, after=False):
1204
"""Determines for each from-to pair if both inventory and working tree
1205
or only the inventory has to be changed.
1207
Also does basic plausability tests.
1209
inv = self.inventory
1211
for rename_entry in rename_entries:
1212
# store to local variables for easier reference
1213
from_rel = rename_entry.from_rel
1214
from_id = rename_entry.from_id
1215
to_rel = rename_entry.to_rel
1216
to_id = inv.path2id(to_rel)
1217
only_change_inv = False
1219
# check the inventory for source and destination
1221
raise errors.BzrMoveFailedError(from_rel,to_rel,
1222
errors.NotVersionedError(path=str(from_rel)))
1223
if to_id is not None:
1224
raise errors.BzrMoveFailedError(from_rel,to_rel,
1225
errors.AlreadyVersionedError(path=str(to_rel)))
1227
# try to determine the mode for rename (only change inv or change
1228
# inv and file system)
1230
if not self.has_filename(to_rel):
1231
raise errors.BzrMoveFailedError(from_id,to_rel,
1232
errors.NoSuchFile(path=str(to_rel),
1233
extra="New file has not been created yet"))
1234
only_change_inv = True
1235
elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1236
only_change_inv = True
1237
elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1238
only_change_inv = False
1240
# something is wrong, so lets determine what exactly
1241
if not self.has_filename(from_rel) and \
1242
not self.has_filename(to_rel):
1243
raise errors.BzrRenameFailedError(from_rel,to_rel,
1244
errors.PathsDoNotExist(paths=(str(from_rel),
1247
raise errors.RenameFailedFilesExist(from_rel, to_rel,
1248
extra="(Use --after to update the Bazaar id)")
1249
rename_entry.only_change_inv = only_change_inv
1250
return rename_entries
1252
def _move(self, rename_entries):
1253
"""Moves a list of files.
1255
Depending on the value of the flag 'only_change_inv', the
1256
file will be moved on the file system or not.
1258
inv = self.inventory
1261
for entry in rename_entries:
1263
self._move_entry(entry)
1265
self._rollback_move(moved)
1269
def _rollback_move(self, moved):
1270
"""Try to rollback a previous move in case of an filesystem error."""
1271
inv = self.inventory
1274
self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1275
entry.to_tail, entry.to_parent_id, entry.from_rel,
1276
entry.from_tail, entry.from_parent_id,
1277
entry.only_change_inv))
1278
except errors.BzrMoveFailedError, e:
1279
raise errors.BzrMoveFailedError( '', '', "Rollback failed."
1280
" The working tree is in an inconsistent state."
1281
" Please consider doing a 'bzr revert'."
1282
" Error message is: %s" % e)
1284
def _move_entry(self, entry):
1285
inv = self.inventory
1286
from_rel_abs = self.abspath(entry.from_rel)
1287
to_rel_abs = self.abspath(entry.to_rel)
1288
if from_rel_abs == to_rel_abs:
1289
raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
1290
"Source and target are identical.")
1292
if not entry.only_change_inv:
1294
osutils.rename(from_rel_abs, to_rel_abs)
1296
raise errors.BzrMoveFailedError(entry.from_rel,
1298
inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1300
@needs_tree_write_lock
1301
def rename_one(self, from_rel, to_rel, after=False):
1304
This can change the directory or the filename or both.
1306
rename_one has several 'modes' to work. First, it can rename a physical
1307
file and change the file_id. That is the normal mode. Second, it can
1308
only change the file_id without touching any physical file. This is
1309
the new mode introduced in version 0.15.
1311
rename_one uses the second mode if 'after == True' and 'to_rel' is not
1312
versioned but present in the working tree.
1314
rename_one uses the second mode if 'after == False' and 'from_rel' is
1315
versioned but no longer in the working tree, and 'to_rel' is not
1316
versioned but present in the working tree.
1318
rename_one uses the first mode if 'after == False' and 'from_rel' is
1319
versioned and present in the working tree, and 'to_rel' is not
1320
versioned and not present in the working tree.
1322
Everything else results in an error.
1324
inv = self.inventory
1327
# create rename entries and tuples
1328
from_tail = splitpath(from_rel)[-1]
1329
from_id = inv.path2id(from_rel)
1331
raise errors.BzrRenameFailedError(from_rel,to_rel,
1332
errors.NotVersionedError(path=str(from_rel)))
1333
from_entry = inv[from_id]
1334
from_parent_id = from_entry.parent_id
1335
to_dir, to_tail = os.path.split(to_rel)
1336
to_dir_id = inv.path2id(to_dir)
1337
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1339
from_tail=from_tail,
1340
from_parent_id=from_parent_id,
1341
to_rel=to_rel, to_tail=to_tail,
1342
to_parent_id=to_dir_id)
1343
rename_entries.append(rename_entry)
1345
# determine which move mode to use. checks also for movability
1346
rename_entries = self._determine_mv_mode(rename_entries, after)
1348
# check if the target changed directory and if the target directory is
1350
if to_dir_id is None:
1351
raise errors.BzrMoveFailedError(from_rel,to_rel,
1352
errors.NotVersionedError(path=str(to_dir)))
1354
# all checks done. now we can continue with our actual work
1355
mutter('rename_one:\n'
1360
' to_dir_id {%s}\n',
1361
from_id, from_rel, to_rel, to_dir, to_dir_id)
1363
self._move(rename_entries)
1364
self._write_inventory(inv)
1366
class _RenameEntry(object):
1367
def __init__(self, from_rel, from_id, from_tail, from_parent_id,
1368
to_rel, to_tail, to_parent_id, only_change_inv=False):
1369
self.from_rel = from_rel
1370
self.from_id = from_id
1371
self.from_tail = from_tail
1372
self.from_parent_id = from_parent_id
1373
self.to_rel = to_rel
1374
self.to_tail = to_tail
1375
self.to_parent_id = to_parent_id
1376
self.only_change_inv = only_change_inv
1380
"""Return all unknown files.
1382
These are files in the working directory that are not versioned or
1383
control files or ignored.
1385
for subp in self.extras():
1386
if not self.is_ignored(subp):
1389
@needs_tree_write_lock
1390
def unversion(self, file_ids):
1391
"""Remove the file ids in file_ids from the current versioned set.
1393
When a file_id is unversioned, all of its children are automatically
1396
:param file_ids: The file ids to stop versioning.
1397
:raises: NoSuchId if any fileid is not currently versioned.
1399
for file_id in file_ids:
1400
if self._inventory.has_id(file_id):
1401
self._inventory.remove_recursive_id(file_id)
1403
raise errors.NoSuchId(self, file_id)
1405
# in the future this should just set a dirty bit to wait for the
1406
# final unlock. However, until all methods of workingtree start
1407
# with the current in -memory inventory rather than triggering
1408
# a read, it is more complex - we need to teach read_inventory
1409
# to know when to read, and when to not read first... and possibly
1410
# to save first when the in memory one may be corrupted.
1411
# so for now, we just only write it if it is indeed dirty.
1413
self._write_inventory(self._inventory)
1415
@deprecated_method(zero_eight)
1416
def iter_conflicts(self):
1417
"""List all files in the tree that have text or content conflicts.
1418
DEPRECATED. Use conflicts instead."""
1419
return self._iter_conflicts()
1421
def _iter_conflicts(self):
1423
for info in self.list_files():
1425
stem = get_conflicted_stem(path)
1428
if stem not in conflicted:
1429
conflicted.add(stem)
1433
def pull(self, source, overwrite=False, stop_revision=None,
1434
change_reporter=None):
1435
top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1438
pp = ProgressPhase("Pull phase", 2, top_pb)
1440
old_revision_info = self.branch.last_revision_info()
1441
basis_tree = self.basis_tree()
1442
count = self.branch.pull(source, overwrite, stop_revision)
1443
new_revision_info = self.branch.last_revision_info()
1444
if new_revision_info != old_revision_info:
1446
repository = self.branch.repository
1447
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1449
new_basis_tree = self.branch.basis_tree()
1456
change_reporter=change_reporter)
1457
if (basis_tree.inventory.root is None and
1458
new_basis_tree.inventory.root is not None):
1459
self.set_root_id(new_basis_tree.inventory.root.file_id)
1462
# TODO - dedup parents list with things merged by pull ?
1463
# reuse the revisiontree we merged against to set the new
1465
parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1466
# we have to pull the merge trees out again, because
1467
# merge_inner has set the ids. - this corner is not yet
1468
# layered well enough to prevent double handling.
1469
merges = self.get_parent_ids()[1:]
1470
parent_trees.extend([
1471
(parent, repository.revision_tree(parent)) for
1473
self.set_parent_trees(parent_trees)
1480
def put_file_bytes_non_atomic(self, file_id, bytes):
1481
"""See MutableTree.put_file_bytes_non_atomic."""
1482
stream = file(self.id2abspath(file_id), 'wb')
1487
# TODO: update the hashcache here ?
1490
"""Yield all unknown files in this WorkingTree.
1492
If there are any unknown directories then only the directory is
1493
returned, not all its children. But if there are unknown files
1494
under a versioned subdirectory, they are returned.
1496
Currently returned depth-first, sorted by name within directories.
1498
## TODO: Work from given directory downwards
1499
for path, dir_entry in self.inventory.directories():
1500
# mutter("search for unknowns in %r", path)
1501
dirabs = self.abspath(path)
1502
if not isdir(dirabs):
1503
# e.g. directory deleted
1507
for subf in os.listdir(dirabs):
1510
if subf not in dir_entry.children:
1511
subf_norm, can_access = osutils.normalized_filename(subf)
1512
if subf_norm != subf and can_access:
1513
if subf_norm not in dir_entry.children:
1514
fl.append(subf_norm)
1520
subp = pathjoin(path, subf)
1524
def ignored_files(self):
1525
"""Yield list of PATH, IGNORE_PATTERN"""
1526
for subp in self.extras():
1527
pat = self.is_ignored(subp)
1531
def get_ignore_list(self):
1532
"""Return list of ignore patterns.
1534
Cached in the Tree object after the first call.
1536
ignoreset = getattr(self, '_ignoreset', None)
1537
if ignoreset is not None:
1540
ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1541
ignore_globs.update(ignores.get_runtime_ignores())
1542
ignore_globs.update(ignores.get_user_ignores())
1543
if self.has_filename(bzrlib.IGNORE_FILENAME):
1544
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1546
ignore_globs.update(ignores.parse_ignore_file(f))
1549
self._ignoreset = ignore_globs
1552
def _flush_ignore_list_cache(self):
1553
"""Resets the cached ignore list to force a cache rebuild."""
1554
self._ignoreset = None
1555
self._ignoreglobster = None
1557
def is_ignored(self, filename):
1558
r"""Check whether the filename matches an ignore pattern.
1560
Patterns containing '/' or '\' need to match the whole path;
1561
others match against only the last component.
1563
If the file is ignored, returns the pattern which caused it to
1564
be ignored, otherwise None. So this can simply be used as a
1565
boolean if desired."""
1566
if getattr(self, '_ignoreglobster', None) is None:
1567
self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1568
return self._ignoreglobster.match(filename)
1570
def kind(self, file_id):
1571
return file_kind(self.id2abspath(file_id))
1573
def _comparison_data(self, entry, path):
1574
abspath = self.abspath(path)
1576
stat_value = os.lstat(abspath)
1578
if getattr(e, 'errno', None) == errno.ENOENT:
1585
mode = stat_value.st_mode
1586
kind = osutils.file_kind_from_stat_mode(mode)
1587
if not supports_executable():
1588
executable = entry.executable
1590
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1591
return kind, executable, stat_value
1593
def _file_size(self, entry, stat_value):
1594
return stat_value.st_size
1596
def last_revision(self):
1597
"""Return the last revision of the branch for this tree.
1599
This format tree does not support a separate marker for last-revision
1600
compared to the branch.
1602
See MutableTree.last_revision
1604
return self._last_revision()
1607
def _last_revision(self):
1608
"""helper for get_parent_ids."""
1609
return self.branch.last_revision()
1611
def is_locked(self):
1612
return self._control_files.is_locked()
1614
def lock_read(self):
1615
"""See Branch.lock_read, and WorkingTree.unlock."""
1616
self.branch.lock_read()
1618
return self._control_files.lock_read()
1620
self.branch.unlock()
1623
def lock_tree_write(self):
1624
"""See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1625
self.branch.lock_read()
1627
return self._control_files.lock_write()
1629
self.branch.unlock()
1632
def lock_write(self):
1633
"""See MutableTree.lock_write, and WorkingTree.unlock."""
1634
self.branch.lock_write()
1636
return self._control_files.lock_write()
1638
self.branch.unlock()
1641
def get_physical_lock_status(self):
1642
return self._control_files.get_physical_lock_status()
1644
def _basis_inventory_name(self):
1645
return 'basis-inventory-cache'
1647
@needs_tree_write_lock
1648
def set_last_revision(self, new_revision):
1649
"""Change the last revision in the working tree."""
1650
if self._change_last_revision(new_revision):
1651
self._cache_basis_inventory(new_revision)
1653
def _change_last_revision(self, new_revision):
1654
"""Template method part of set_last_revision to perform the change.
1656
This is used to allow WorkingTree3 instances to not affect branch
1657
when their last revision is set.
1659
if new_revision is None:
1660
self.branch.set_revision_history([])
1663
self.branch.generate_revision_history(new_revision)
1664
except errors.NoSuchRevision:
1665
# not present in the repo - dont try to set it deeper than the tip
1666
self.branch.set_revision_history([new_revision])
1669
def _write_basis_inventory(self, xml):
1670
"""Write the basis inventory XML to the basis-inventory file"""
1671
assert isinstance(xml, str), 'serialised xml must be bytestring.'
1672
path = self._basis_inventory_name()
1674
self._control_files.put(path, sio)
1676
def _create_basis_xml_from_inventory(self, revision_id, inventory):
1677
"""Create the text that will be saved in basis-inventory"""
1678
inventory.revision_id = revision_id
1679
return xml7.serializer_v7.write_inventory_to_string(inventory)
1681
def _cache_basis_inventory(self, new_revision):
1682
"""Cache new_revision as the basis inventory."""
1683
# TODO: this should allow the ready-to-use inventory to be passed in,
1684
# as commit already has that ready-to-use [while the format is the
1687
# this double handles the inventory - unpack and repack -
1688
# but is easier to understand. We can/should put a conditional
1689
# in here based on whether the inventory is in the latest format
1690
# - perhaps we should repack all inventories on a repository
1692
# the fast path is to copy the raw xml from the repository. If the
1693
# xml contains 'revision_id="', then we assume the right
1694
# revision_id is set. We must check for this full string, because a
1695
# root node id can legitimately look like 'revision_id' but cannot
1697
xml = self.branch.repository.get_inventory_xml(new_revision)
1698
firstline = xml.split('\n', 1)[0]
1699
if (not 'revision_id="' in firstline or
1700
'format="7"' not in firstline):
1701
inv = self.branch.repository.deserialise_inventory(
1703
xml = self._create_basis_xml_from_inventory(new_revision, inv)
1704
self._write_basis_inventory(xml)
1705
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1708
def read_basis_inventory(self):
1709
"""Read the cached basis inventory."""
1710
path = self._basis_inventory_name()
1711
return self._control_files.get(path).read()
1714
def read_working_inventory(self):
1715
"""Read the working inventory.
1717
:raises errors.InventoryModified: read_working_inventory will fail
1718
when the current in memory inventory has been modified.
1720
# conceptually this should be an implementation detail of the tree.
1721
# XXX: Deprecate this.
1722
# ElementTree does its own conversion from UTF-8, so open in
1724
if self._inventory_is_modified:
1725
raise errors.InventoryModified(self)
1726
result = self._deserialize(self._control_files.get('inventory'))
1727
self._set_inventory(result, dirty=False)
1730
@needs_tree_write_lock
1731
def remove(self, files, verbose=False, to_file=None):
1732
"""Remove nominated files from the working inventory..
1734
This does not remove their text. This does not run on XXX on what? RBC
1736
TODO: Refuse to remove modified files unless --force is given?
1738
TODO: Do something useful with directories.
1740
TODO: Should this remove the text or not? Tough call; not
1741
removing may be useful and the user can just use use rm, and
1742
is the opposite of add. Removing it is consistent with most
1743
other tools. Maybe an option.
1745
## TODO: Normalize names
1746
## TODO: Remove nested loops; better scalability
1747
if isinstance(files, basestring):
1750
inv = self.inventory
1752
# do this before any modifications
1754
fid = inv.path2id(f)
1756
note("%s is not versioned."%f)
1759
# having remove it, it must be either ignored or unknown
1760
if self.is_ignored(f):
1764
textui.show_status(new_status, inv[fid].kind, f,
1768
self._write_inventory(inv)
1770
@needs_tree_write_lock
1771
def revert(self, filenames, old_tree=None, backups=True,
1772
pb=DummyProgress(), report_changes=False):
1773
from bzrlib.conflicts import resolve
1774
if old_tree is None:
1775
old_tree = self.basis_tree()
1776
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1778
if not len(filenames):
1779
self.set_parent_ids(self.get_parent_ids()[:1])
1782
resolve(self, filenames, ignore_misses=True)
1785
# XXX: This method should be deprecated in favour of taking in a proper
1786
# new Inventory object.
1787
@needs_tree_write_lock
1788
def set_inventory(self, new_inventory_list):
1789
from bzrlib.inventory import (Inventory,
1794
inv = Inventory(self.get_root_id())
1795
for path, file_id, parent, kind in new_inventory_list:
1796
name = os.path.basename(path)
1799
# fixme, there should be a factory function inv,add_??
1800
if kind == 'directory':
1801
inv.add(InventoryDirectory(file_id, name, parent))
1802
elif kind == 'file':
1803
inv.add(InventoryFile(file_id, name, parent))
1804
elif kind == 'symlink':
1805
inv.add(InventoryLink(file_id, name, parent))
1807
raise errors.BzrError("unknown kind %r" % kind)
1808
self._write_inventory(inv)
1810
@needs_tree_write_lock
1811
def set_root_id(self, file_id):
1812
"""Set the root id for this tree."""
1815
symbol_versioning.warn(symbol_versioning.zero_twelve
1816
% 'WorkingTree.set_root_id with fileid=None',
1820
inv = self._inventory
1821
orig_root_id = inv.root.file_id
1822
# TODO: it might be nice to exit early if there was nothing
1823
# to do, saving us from trigger a sync on unlock.
1824
self._inventory_is_modified = True
1825
# we preserve the root inventory entry object, but
1826
# unlinkit from the byid index
1827
del inv._byid[inv.root.file_id]
1828
inv.root.file_id = file_id
1829
# and link it into the index with the new changed id.
1830
inv._byid[inv.root.file_id] = inv.root
1831
# and finally update all children to reference the new id.
1832
# XXX: this should be safe to just look at the root.children
1833
# list, not the WHOLE INVENTORY.
1836
if entry.parent_id == orig_root_id:
1837
entry.parent_id = inv.root.file_id
1840
"""See Branch.unlock.
1842
WorkingTree locking just uses the Branch locking facilities.
1843
This is current because all working trees have an embedded branch
1844
within them. IF in the future, we were to make branch data shareable
1845
between multiple working trees, i.e. via shared storage, then we
1846
would probably want to lock both the local tree, and the branch.
1848
raise NotImplementedError(self.unlock)
1851
"""Update a working tree along its branch.
1853
This will update the branch if its bound too, which means we have
1854
multiple trees involved:
1856
- The new basis tree of the master.
1857
- The old basis tree of the branch.
1858
- The old basis tree of the working tree.
1859
- The current working tree state.
1861
Pathologically, all three may be different, and non-ancestors of each
1862
other. Conceptually we want to:
1864
- Preserve the wt.basis->wt.state changes
1865
- Transform the wt.basis to the new master basis.
1866
- Apply a merge of the old branch basis to get any 'local' changes from
1868
- Restore the wt.basis->wt.state changes.
1870
There isn't a single operation at the moment to do that, so we:
1871
- Merge current state -> basis tree of the master w.r.t. the old tree
1873
- Do a 'normal' merge of the old branch basis if it is relevant.
1875
if self.branch.get_master_branch() is not None:
1877
update_branch = True
1879
self.lock_tree_write()
1880
update_branch = False
1883
old_tip = self.branch.update()
1886
return self._update_tree(old_tip)
1890
@needs_tree_write_lock
1891
def _update_tree(self, old_tip=None):
1892
"""Update a tree to the master branch.
1894
:param old_tip: if supplied, the previous tip revision the branch,
1895
before it was changed to the master branch's tip.
1897
# here if old_tip is not None, it is the old tip of the branch before
1898
# it was updated from the master branch. This should become a pending
1899
# merge in the working tree to preserve the user existing work. we
1900
# cant set that until we update the working trees last revision to be
1901
# one from the new branch, because it will just get absorbed by the
1902
# parent de-duplication logic.
1904
# We MUST save it even if an error occurs, because otherwise the users
1905
# local work is unreferenced and will appear to have been lost.
1909
last_rev = self.get_parent_ids()[0]
1912
if last_rev != self.branch.last_revision():
1913
# merge tree state up to new branch tip.
1914
basis = self.basis_tree()
1915
to_tree = self.branch.basis_tree()
1916
if basis.inventory.root is None:
1917
self.set_root_id(to_tree.inventory.root.file_id)
1918
result += merge.merge_inner(
1923
# TODO - dedup parents list with things merged by pull ?
1924
# reuse the tree we've updated to to set the basis:
1925
parent_trees = [(self.branch.last_revision(), to_tree)]
1926
merges = self.get_parent_ids()[1:]
1927
# Ideally we ask the tree for the trees here, that way the working
1928
# tree can decide whether to give us teh entire tree or give us a
1929
# lazy initialised tree. dirstate for instance will have the trees
1930
# in ram already, whereas a last-revision + basis-inventory tree
1931
# will not, but also does not need them when setting parents.
1932
for parent in merges:
1933
parent_trees.append(
1934
(parent, self.branch.repository.revision_tree(parent)))
1935
if old_tip is not None:
1936
parent_trees.append(
1937
(old_tip, self.branch.repository.revision_tree(old_tip)))
1938
self.set_parent_trees(parent_trees)
1939
last_rev = parent_trees[0][0]
1941
# the working tree had the same last-revision as the master
1942
# branch did. We may still have pivot local work from the local
1943
# branch into old_tip:
1944
if old_tip is not None:
1945
self.add_parent_tree_id(old_tip)
1946
if old_tip and old_tip != last_rev:
1947
# our last revision was not the prior branch last revision
1948
# and we have converted that last revision to a pending merge.
1949
# base is somewhere between the branch tip now
1950
# and the now pending merge
1951
from bzrlib.revision import common_ancestor
1953
base_rev_id = common_ancestor(self.branch.last_revision(),
1955
self.branch.repository)
1956
except errors.NoCommonAncestor:
1958
base_tree = self.branch.repository.revision_tree(base_rev_id)
1959
other_tree = self.branch.repository.revision_tree(old_tip)
1960
result += merge.merge_inner(
1967
def _write_hashcache_if_dirty(self):
1968
"""Write out the hashcache if it is dirty."""
1969
if self._hashcache.needs_write:
1971
self._hashcache.write()
1973
if e.errno not in (errno.EPERM, errno.EACCES):
1975
# TODO: jam 20061219 Should this be a warning? A single line
1976
# warning might be sufficient to let the user know what
1978
mutter('Could not write hashcache for %s\nError: %s',
1979
self._hashcache.cache_file_name(), e)
1981
@needs_tree_write_lock
1982
def _write_inventory(self, inv):
1983
"""Write inventory as the current inventory."""
1984
self._set_inventory(inv, dirty=True)
1987
def set_conflicts(self, arg):
1988
raise errors.UnsupportedOperation(self.set_conflicts, self)
1990
def add_conflicts(self, arg):
1991
raise errors.UnsupportedOperation(self.add_conflicts, self)
1994
def conflicts(self):
1995
conflicts = _mod_conflicts.ConflictList()
1996
for conflicted in self._iter_conflicts():
1999
if file_kind(self.abspath(conflicted)) != "file":
2001
except errors.NoSuchFile:
2004
for suffix in ('.THIS', '.OTHER'):
2006
kind = file_kind(self.abspath(conflicted+suffix))
2009
except errors.NoSuchFile:
2013
ctype = {True: 'text conflict', False: 'contents conflict'}[text]
2014
conflicts.append(_mod_conflicts.Conflict.factory(ctype,
2016
file_id=self.path2id(conflicted)))
2020
class WorkingTree2(WorkingTree):
2021
"""This is the Format 2 working tree.
2023
This was the first weave based working tree.
2024
- uses os locks for locking.
2025
- uses the branch last-revision.
2028
def lock_tree_write(self):
2029
"""See WorkingTree.lock_tree_write().
2031
In Format2 WorkingTrees we have a single lock for the branch and tree
2032
so lock_tree_write() degrades to lock_write().
2034
self.branch.lock_write()
2036
return self._control_files.lock_write()
2038
self.branch.unlock()
2042
# we share control files:
2043
if self._control_files._lock_count == 3:
2044
# _inventory_is_modified is always False during a read lock.
2045
if self._inventory_is_modified:
2047
self._write_hashcache_if_dirty()
2049
# reverse order of locking.
2051
return self._control_files.unlock()
2053
self.branch.unlock()
2056
class WorkingTree3(WorkingTree):
2057
"""This is the Format 3 working tree.
2059
This differs from the base WorkingTree by:
2060
- having its own file lock
2061
- having its own last-revision property.
2063
This is new in bzr 0.8
2067
def _last_revision(self):
2068
"""See Mutable.last_revision."""
2070
return self._control_files.get_utf8('last-revision').read()
2071
except errors.NoSuchFile:
2074
def _change_last_revision(self, revision_id):
2075
"""See WorkingTree._change_last_revision."""
2076
if revision_id is None or revision_id == NULL_REVISION:
2078
self._control_files._transport.delete('last-revision')
2079
except errors.NoSuchFile:
2083
self._control_files.put_utf8('last-revision', revision_id)
2086
@needs_tree_write_lock
2087
def set_conflicts(self, conflicts):
2088
self._put_rio('conflicts', conflicts.to_stanzas(),
2091
@needs_tree_write_lock
2092
def add_conflicts(self, new_conflicts):
2093
conflict_set = set(self.conflicts())
2094
conflict_set.update(set(list(new_conflicts)))
2095
self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2096
key=_mod_conflicts.Conflict.sort_key)))
2099
def conflicts(self):
2101
confile = self._control_files.get('conflicts')
2102
except errors.NoSuchFile:
2103
return _mod_conflicts.ConflictList()
2105
if confile.next() != CONFLICT_HEADER_1 + '\n':
2106
raise errors.ConflictFormatError()
2107
except StopIteration:
2108
raise errors.ConflictFormatError()
2109
return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2112
if self._control_files._lock_count == 1:
2113
# _inventory_is_modified is always False during a read lock.
2114
if self._inventory_is_modified:
2116
self._write_hashcache_if_dirty()
2117
# reverse order of locking.
2119
return self._control_files.unlock()
2121
self.branch.unlock()
2124
class WorkingTree4(WorkingTree3):
2126
def _serialize(self, inventory, out_file):
2127
xml7.serializer_v7.write_inventory(self._inventory, out_file)
2129
def _deserialize(selt, in_file):
2130
return xml7.serializer_v7.read_inventory(in_file)
2132
def _comparison_data(self, entry, path):
2133
kind, executable, stat_value = \
2134
WorkingTree3._comparison_data(self, entry, path)
2135
if kind == 'directory' and entry.kind == 'tree-reference':
2136
kind = 'tree-reference'
2137
return kind, executable, stat_value
2139
def kind(self, file_id):
2140
kind = WorkingTree3.kind(self, file_id)
2141
if kind == 'directory':
2142
entry = self.inventory[file_id]
2143
if entry.kind == 'tree-reference':
2144
kind = 'tree-reference'
2147
def add_reference(self, sub_tree):
2149
sub_tree_path = self.relpath(sub_tree.basedir)
2150
except errors.PathNotChild:
2151
raise errors.BadReferenceTarget(self, sub_tree,
2152
'Target not inside tree.')
2153
parent_id = self.path2id(osutils.dirname(sub_tree_path))
2154
name = osutils.basename(sub_tree_path)
2155
sub_tree_id = sub_tree.get_root_id()
2156
if sub_tree_id == self.get_root_id():
2157
raise errors.BadReferenceTarget(self, sub_tree,
2158
'Trees have the same root id.')
2159
if sub_tree_id in self.inventory:
2160
raise errors.BadReferenceTarget(self, sub_tree,
2161
'Root id already present in tree')
2162
entry = TreeReference(sub_tree_id, name, parent_id, None,
2164
self.inventory.add(entry)
2165
self._write_inventory(self.inventory)
2167
def get_nested_tree(self, entry, path=None):
2169
path = self.id2path(entry.file_id)
2170
return WorkingTree.open(self.abspath(path))
2172
def get_reference_revision(self, entry, path=None):
2173
return self.get_nested_tree(entry, path).last_revision()
2176
def get_conflicted_stem(path):
2177
for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
2178
if path.endswith(suffix):
2179
return path[:-len(suffix)]
2181
@deprecated_function(zero_eight)
2182
def is_control_file(filename):
2183
"""See WorkingTree.is_control_filename(filename)."""
2184
## FIXME: better check
2185
filename = normpath(filename)
2186
while filename != '':
2187
head, tail = os.path.split(filename)
2188
## mutter('check %r for control file' % ((head, tail),))
2191
if filename == head:
2197
class WorkingTreeFormat(object):
2198
"""An encapsulation of the initialization and open routines for a format.
2200
Formats provide three things:
2201
* An initialization routine,
2205
Formats are placed in an dict by their format string for reference
2206
during workingtree opening. Its not required that these be instances, they
2207
can be classes themselves with class methods - it simply depends on
2208
whether state is needed for a given format or not.
2210
Once a format is deprecated, just deprecate the initialize and open
2211
methods on the format class. Do not deprecate the object, as the
2212
object will be created every time regardless.
2215
_default_format = None
2216
"""The default format used for new trees."""
2219
"""The known formats."""
2221
requires_rich_root = False
2224
def find_format(klass, a_bzrdir):
2225
"""Return the format for the working tree object in a_bzrdir."""
2227
transport = a_bzrdir.get_workingtree_transport(None)
2228
format_string = transport.get("format").read()
2229
return klass._formats[format_string]
2230
except errors.NoSuchFile:
2231
raise errors.NoWorkingTree(base=transport.base)
2233
raise errors.UnknownFormatError(format=format_string)
2236
def get_default_format(klass):
2237
"""Return the current default format."""
2238
return klass._default_format
2240
def get_format_string(self):
2241
"""Return the ASCII format string that identifies this format."""
2242
raise NotImplementedError(self.get_format_string)
2244
def get_format_description(self):
2245
"""Return the short description for this format."""
2246
raise NotImplementedError(self.get_format_description)
2248
def is_supported(self):
2249
"""Is this format supported?
2251
Supported formats can be initialized and opened.
2252
Unsupported formats may not support initialization or committing or
2253
some other features depending on the reason for not being supported.
2258
def register_format(klass, format):
2259
klass._formats[format.get_format_string()] = format
2262
def set_default_format(klass, format):
2263
klass._default_format = format
2266
def unregister_format(klass, format):
2267
assert klass._formats[format.get_format_string()] is format
2268
del klass._formats[format.get_format_string()]
2272
class WorkingTreeFormat2(WorkingTreeFormat):
2273
"""The second working tree format.
2275
This format modified the hash cache from the format 1 hash cache.
2278
def get_format_description(self):
2279
"""See WorkingTreeFormat.get_format_description()."""
2280
return "Working tree format 2"
2282
def stub_initialize_remote(self, control_files):
2283
"""As a special workaround create critical control files for a remote working tree
2285
This ensures that it can later be updated and dealt with locally,
2286
since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
2287
no working tree. (See bug #43064).
2291
xml5.serializer_v5.write_inventory(inv, sio)
2293
control_files.put('inventory', sio)
2295
control_files.put_utf8('pending-merges', '')
2298
def initialize(self, a_bzrdir, revision_id=None):
2299
"""See WorkingTreeFormat.initialize()."""
2300
if not isinstance(a_bzrdir.transport, LocalTransport):
2301
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2302
branch = a_bzrdir.open_branch()
2303
if revision_id is not None:
2306
revision_history = branch.revision_history()
2308
position = revision_history.index(revision_id)
2310
raise errors.NoSuchRevision(branch, revision_id)
2311
branch.set_revision_history(revision_history[:position + 1])
2314
revision = branch.last_revision()
2316
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2322
basis_tree = branch.repository.revision_tree(revision)
2323
if basis_tree.inventory.root is not None:
2324
wt.set_root_id(basis_tree.inventory.root.file_id)
2325
# set the parent list and cache the basis tree.
2326
wt.set_parent_trees([(revision, basis_tree)])
2327
transform.build_tree(basis_tree, wt)
2331
super(WorkingTreeFormat2, self).__init__()
2332
self._matchingbzrdir = bzrdir.BzrDirFormat6()
2334
def open(self, a_bzrdir, _found=False):
2335
"""Return the WorkingTree object for a_bzrdir
2337
_found is a private parameter, do not use it. It is used to indicate
2338
if format probing has already been done.
2341
# we are being called directly and must probe.
2342
raise NotImplementedError
2343
if not isinstance(a_bzrdir.transport, LocalTransport):
2344
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2345
return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2351
class WorkingTreeFormat3(WorkingTreeFormat):
2352
"""The second working tree format updated to record a format marker.
2355
- exists within a metadir controlling .bzr
2356
- includes an explicit version marker for the workingtree control
2357
files, separate from the BzrDir format
2358
- modifies the hash cache format
2360
- uses a LockDir to guard access for writes.
2363
def get_format_string(self):
2364
"""See WorkingTreeFormat.get_format_string()."""
2365
return "Bazaar-NG Working Tree format 3"
2367
def get_format_description(self):
2368
"""See WorkingTreeFormat.get_format_description()."""
2369
return "Working tree format 3"
2371
_lock_file_name = 'lock'
2372
_lock_class = LockDir
2373
_tree_class = WorkingTree3
2375
def __get_matchingbzrdir(self):
2376
return bzrdir.BzrDirMetaFormat1()
2378
_matchingbzrdir = property(__get_matchingbzrdir)
2380
def _open_control_files(self, a_bzrdir):
2381
transport = a_bzrdir.get_workingtree_transport(None)
2382
return LockableFiles(transport, self._lock_file_name,
2385
def initialize(self, a_bzrdir, revision_id=None):
2386
"""See WorkingTreeFormat.initialize().
2388
revision_id allows creating a working tree at a different
2389
revision than the branch is at.
2391
if not isinstance(a_bzrdir.transport, LocalTransport):
2392
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2393
transport = a_bzrdir.get_workingtree_transport(self)
2394
control_files = self._open_control_files(a_bzrdir)
2395
control_files.create_lock()
2396
control_files.lock_write()
2397
control_files.put_utf8('format', self.get_format_string())
2398
branch = a_bzrdir.open_branch()
2399
if revision_id is None:
2400
revision_id = branch.last_revision()
2401
inv = self._initial_inventory()
2402
wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2408
_control_files=control_files)
2409
wt.lock_tree_write()
2411
basis_tree = branch.repository.revision_tree(revision_id)
2412
# only set an explicit root id if there is one to set.
2413
if basis_tree.inventory.root is not None:
2414
wt.set_root_id(basis_tree.inventory.root.file_id)
2415
if revision_id == NULL_REVISION:
2416
wt.set_parent_trees([])
2418
wt.set_parent_trees([(revision_id, basis_tree)])
2419
transform.build_tree(basis_tree, wt)
2421
# Unlock in this order so that the unlock-triggers-flush in
2422
# WorkingTree is given a chance to fire.
2423
control_files.unlock()
2427
def _initial_inventory(self):
2431
super(WorkingTreeFormat3, self).__init__()
2433
def open(self, a_bzrdir, _found=False):
2434
"""Return the WorkingTree object for a_bzrdir
2436
_found is a private parameter, do not use it. It is used to indicate
2437
if format probing has already been done.
2440
# we are being called directly and must probe.
2441
raise NotImplementedError
2442
if not isinstance(a_bzrdir.transport, LocalTransport):
2443
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2444
return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
2446
def _open(self, a_bzrdir, control_files):
2447
"""Open the tree itself.
2449
:param a_bzrdir: the dir for the tree.
2450
:param control_files: the control files for the tree.
2452
return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2456
_control_files=control_files)
2459
return self.get_format_string()
2462
class WorkingTreeFormat4(WorkingTreeFormat3):
2464
"""Working tree format that supports unique roots and nested trees"""
2466
_tree_class = WorkingTree4
2468
requires_rich_root = True
2470
supports_tree_reference = True
2473
WorkingTreeFormat3.__init__(self)
2475
def __get_matchingbzrdir(self):
2476
return bzrdir.format_registry.make_bzrdir('experimental-knit3')
2478
_matchingbzrdir = property(__get_matchingbzrdir)
2480
def get_format_string(self):
2481
"""See WorkingTreeFormat.get_format_string()."""
2482
return "Bazaar-NG Working Tree format 4"
2484
def get_format_description(self):
2485
"""See WorkingTreeFormat.get_format_description()."""
2486
return "Working tree format 4"
2488
def _initial_inventory(self):
2489
return Inventory(root_id=generate_ids.gen_root_id())
2491
# formats which have no format string are not discoverable
2492
# and not independently creatable, so are not registered.
2493
__default_format = WorkingTreeFormat3()
2494
WorkingTreeFormat.register_format(__default_format)
2495
WorkingTreeFormat.register_format(WorkingTreeFormat4())
2496
WorkingTreeFormat.set_default_format(__default_format)
2497
_legacy_formats = [WorkingTreeFormat2(),
2501
class WorkingTreeTestProviderAdapter(object):
2502
"""A tool to generate a suite testing multiple workingtree formats at once.
2504
This is done by copying the test once for each transport and injecting
2505
the transport_server, transport_readonly_server, and workingtree_format
2506
classes into each copy. Each copy is also given a new id() to make it
2510
def __init__(self, transport_server, transport_readonly_server, formats):
2511
self._transport_server = transport_server
2512
self._transport_readonly_server = transport_readonly_server
2513
self._formats = formats
2515
def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2516
"""Clone test for adaption."""
2517
new_test = deepcopy(test)
2518
new_test.transport_server = self._transport_server
2519
new_test.transport_readonly_server = self._transport_readonly_server
2520
new_test.bzrdir_format = bzrdir_format
2521
new_test.workingtree_format = workingtree_format
2522
def make_new_test_id():
2523
new_id = "%s(%s)" % (test.id(), variation)
2524
return lambda: new_id
2525
new_test.id = make_new_test_id()
2528
def adapt(self, test):
2529
from bzrlib.tests import TestSuite
2530
result = TestSuite()
2531
for workingtree_format, bzrdir_format in self._formats:
2532
new_test = self._clone_test(
2535
workingtree_format, workingtree_format.__class__.__name__)
2536
result.addTest(new_test)