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.errors import (BzrCheckError,
81
WeaveRevisionNotPresent,
85
MergeModifiedFormatError,
88
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
89
from bzrlib.lockable_files import LockableFiles, TransportLock
90
from bzrlib.lockdir import LockDir
91
import bzrlib.mutabletree
92
from bzrlib.mutabletree import needs_tree_write_lock
93
from bzrlib.osutils import (
105
from bzrlib.trace import mutter, note
106
from bzrlib.transport.local import LocalTransport
108
from bzrlib.progress import DummyProgress, ProgressPhase
109
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
110
import bzrlib.revisiontree
111
from bzrlib.rio import RioReader, rio_file, Stanza
112
from bzrlib.symbol_versioning import (deprecated_passed,
115
DEPRECATED_PARAMETER,
122
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
123
CONFLICT_HEADER_1 = "BZR conflict list format 1"
126
@deprecated_function(zero_thirteen)
127
def gen_file_id(name):
128
"""Return new file id for the basename 'name'.
130
Use bzrlib.generate_ids.gen_file_id() instead
132
return generate_ids.gen_file_id(name)
135
@deprecated_function(zero_thirteen)
137
"""Return a new tree-root file id.
139
This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
141
return generate_ids.gen_root_id()
144
class TreeEntry(object):
145
"""An entry that implements the minimum interface used by commands.
147
This needs further inspection, it may be better to have
148
InventoryEntries without ids - though that seems wrong. For now,
149
this is a parallel hierarchy to InventoryEntry, and needs to become
150
one of several things: decorates to that hierarchy, children of, or
152
Another note is that these objects are currently only used when there is
153
no InventoryEntry available - i.e. for unversioned objects.
154
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
157
def __eq__(self, other):
158
# yes, this us ugly, TODO: best practice __eq__ style.
159
return (isinstance(other, TreeEntry)
160
and other.__class__ == self.__class__)
162
def kind_character(self):
166
class TreeDirectory(TreeEntry):
167
"""See TreeEntry. This is a directory in a working tree."""
169
def __eq__(self, other):
170
return (isinstance(other, TreeDirectory)
171
and other.__class__ == self.__class__)
173
def kind_character(self):
177
class TreeFile(TreeEntry):
178
"""See TreeEntry. This is a regular file in a working tree."""
180
def __eq__(self, other):
181
return (isinstance(other, TreeFile)
182
and other.__class__ == self.__class__)
184
def kind_character(self):
188
class TreeLink(TreeEntry):
189
"""See TreeEntry. This is a symlink in a working tree."""
191
def __eq__(self, other):
192
return (isinstance(other, TreeLink)
193
and other.__class__ == self.__class__)
195
def kind_character(self):
199
class WorkingTree(bzrlib.mutabletree.MutableTree):
200
"""Working copy tree.
202
The inventory is held in the `Branch` working-inventory, and the
203
files are in a directory on disk.
205
It is possible for a `WorkingTree` to have a filename which is
206
not listed in the Inventory and vice versa.
209
def __init__(self, basedir='.',
210
branch=DEPRECATED_PARAMETER,
216
"""Construct a WorkingTree for basedir.
218
If the branch is not supplied, it is opened automatically.
219
If the branch is supplied, it must be the branch for this basedir.
220
(branch.base is not cross checked, because for remote branches that
221
would be meaningless).
223
self._format = _format
224
self.bzrdir = _bzrdir
226
# not created via open etc.
227
warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
228
"Please use bzrdir.open_workingtree or WorkingTree.open().",
231
wt = WorkingTree.open(basedir)
232
self._branch = wt.branch
233
self.basedir = wt.basedir
234
self._control_files = wt._control_files
235
self._hashcache = wt._hashcache
236
self._set_inventory(wt._inventory, dirty=False)
237
self._format = wt._format
238
self.bzrdir = wt.bzrdir
239
assert isinstance(basedir, basestring), \
240
"base directory %r is not a string" % basedir
241
basedir = safe_unicode(basedir)
242
mutter("opening working tree %r", basedir)
243
if deprecated_passed(branch):
245
warnings.warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
246
" Please use bzrdir.open_workingtree() or"
247
" WorkingTree.open().",
251
self._branch = branch
253
self._branch = self.bzrdir.open_branch()
254
self.basedir = realpath(basedir)
255
# if branch is at our basedir and is a format 6 or less
256
if isinstance(self._format, WorkingTreeFormat2):
257
# share control object
258
self._control_files = self.branch.control_files
260
# assume all other formats have their own control files.
261
assert isinstance(_control_files, LockableFiles), \
262
"_control_files must be a LockableFiles, not %r" \
264
self._control_files = _control_files
265
# update the whole cache up front and write to disk if anything changed;
266
# in the future we might want to do this more selectively
267
# two possible ways offer themselves : in self._unlock, write the cache
268
# if needed, or, when the cache sees a change, append it to the hash
269
# cache file, and have the parser take the most recent entry for a
271
cache_filename = self.bzrdir.get_workingtree_transport(None).local_abspath('stat-cache')
272
self._hashcache = hashcache.HashCache(basedir, cache_filename,
273
self._control_files._file_mode)
276
# is this scan needed ? it makes things kinda slow.
283
if _inventory is None:
284
self._inventory_is_modified = False
285
self.read_working_inventory()
287
# the caller of __init__ has provided an inventory,
288
# we assume they know what they are doing - as its only
289
# the Format factory and creation methods that are
290
# permitted to do this.
291
self._set_inventory(_inventory, dirty=False)
294
fget=lambda self: self._branch,
295
doc="""The branch this WorkingTree is connected to.
297
This cannot be set - it is reflective of the actual disk structure
298
the working tree has been constructed from.
301
def break_lock(self):
302
"""Break a lock if one is present from another instance.
304
Uses the ui factory to ask for confirmation if the lock may be from
307
This will probe the repository for its lock as well.
309
self._control_files.break_lock()
310
self.branch.break_lock()
312
def requires_rich_root(self):
313
return self._format.requires_rich_root
315
def _set_inventory(self, inv, dirty):
316
"""Set the internal cached inventory.
318
:param inv: The inventory to set.
319
:param dirty: A boolean indicating whether the inventory is the same
320
logical inventory as whats on disk. If True the inventory is not
321
the same and should be written to disk or data will be lost, if
322
False then the inventory is the same as that on disk and any
323
serialisation would be unneeded overhead.
325
assert inv.root is not None
326
self._inventory = inv
327
self._inventory_is_modified = dirty
330
def open(path=None, _unsupported=False):
331
"""Open an existing working tree at path.
335
path = os.path.getcwdu()
336
control = bzrdir.BzrDir.open(path, _unsupported)
337
return control.open_workingtree(_unsupported)
340
def open_containing(path=None):
341
"""Open an existing working tree which has its root about path.
343
This probes for a working tree at path and searches upwards from there.
345
Basically we keep looking up until we find the control directory or
346
run into /. If there isn't one, raises NotBranchError.
347
TODO: give this a new exception.
348
If there is one, it is returned, along with the unused portion of path.
350
:return: The WorkingTree that contains 'path', and the rest of path
353
path = osutils.getcwd()
354
control, relpath = bzrdir.BzrDir.open_containing(path)
356
return control.open_workingtree(), relpath
359
def open_downlevel(path=None):
360
"""Open an unsupported working tree.
362
Only intended for advanced situations like upgrading part of a bzrdir.
364
return WorkingTree.open(path, _unsupported=True)
367
"""Iterate through file_ids for this tree.
369
file_ids are in a WorkingTree if they are in the working inventory
370
and the working file exists.
372
inv = self._inventory
373
for path, ie in inv.iter_entries():
374
if osutils.lexists(self.abspath(path)):
378
return "<%s of %s>" % (self.__class__.__name__,
379
getattr(self, 'basedir', None))
381
def abspath(self, filename):
382
return pathjoin(self.basedir, filename)
384
def basis_tree(self):
385
"""Return RevisionTree for the current last revision.
387
If the left most parent is a ghost then the returned tree will be an
388
empty tree - one obtained by calling repository.revision_tree(None).
391
revision_id = self.get_parent_ids()[0]
393
# no parents, return an empty revision tree.
394
# in the future this should return the tree for
395
# 'empty:' - the implicit root empty tree.
396
return self.branch.repository.revision_tree(None)
399
xml = self.read_basis_inventory()
400
inv = xml6.serializer_v6.read_inventory_from_string(xml)
401
if inv is not None and inv.revision_id == revision_id:
402
return bzrlib.revisiontree.RevisionTree(
403
self.branch.repository, inv, revision_id)
404
except (NoSuchFile, errors.BadInventoryFormat):
406
# No cached copy available, retrieve from the repository.
407
# FIXME? RBC 20060403 should we cache the inventory locally
410
return self.branch.repository.revision_tree(revision_id)
411
except errors.RevisionNotPresent:
412
# the basis tree *may* be a ghost or a low level error may have
413
# occured. If the revision is present, its a problem, if its not
415
if self.branch.repository.has_revision(revision_id):
417
# the basis tree is a ghost so return an empty tree.
418
return self.branch.repository.revision_tree(None)
421
@deprecated_method(zero_eight)
422
def create(branch, directory):
423
"""Create a workingtree for branch at directory.
425
If existing_directory already exists it must have a .bzr directory.
426
If it does not exist, it will be created.
428
This returns a new WorkingTree object for the new checkout.
430
TODO FIXME RBC 20060124 when we have checkout formats in place this
431
should accept an optional revisionid to checkout [and reject this if
432
checking out into the same dir as a pre-checkout-aware branch format.]
434
XXX: When BzrDir is present, these should be created through that
437
warnings.warn('delete WorkingTree.create', stacklevel=3)
438
transport = get_transport(directory)
439
if branch.bzrdir.root_transport.base == transport.base:
441
return branch.bzrdir.create_workingtree()
442
# different directory,
443
# create a branch reference
444
# and now a working tree.
445
raise NotImplementedError
448
@deprecated_method(zero_eight)
449
def create_standalone(directory):
450
"""Create a checkout and a branch and a repo at directory.
452
Directory must exist and be empty.
454
please use BzrDir.create_standalone_workingtree
456
return bzrdir.BzrDir.create_standalone_workingtree(directory)
458
def relpath(self, path):
459
"""Return the local path portion from a given path.
461
The path may be absolute or relative. If its a relative path it is
462
interpreted relative to the python current working directory.
464
return osutils.relpath(self.basedir, path)
466
def has_filename(self, filename):
467
return osutils.lexists(self.abspath(filename))
469
def get_file(self, file_id):
470
return self.get_file_byname(self.id2path(file_id))
472
def get_file_text(self, file_id):
473
return self.get_file(file_id).read()
475
def get_file_byname(self, filename):
476
return file(self.abspath(filename), 'rb')
478
def annotate_iter(self, file_id):
479
"""See Tree.annotate_iter
481
This implementation will use the basis tree implementation if possible.
482
Lines not in the basis are attributed to CURRENT_REVISION
484
If there are pending merges, lines added by those merges will be
485
incorrectly attributed to CURRENT_REVISION (but after committing, the
486
attribution will be correct).
488
basis = self.basis_tree()
489
changes = self._iter_changes(basis, True, [file_id]).next()
490
changed_content, kind = changes[2], changes[6]
491
if not changed_content:
492
return basis.annotate_iter(file_id)
496
if kind[0] != 'file':
499
old_lines = list(basis.annotate_iter(file_id))
501
for tree in self.branch.repository.revision_trees(
502
self.get_parent_ids()[1:]):
503
if file_id not in tree:
505
old.append(list(tree.annotate_iter(file_id)))
506
return annotate.reannotate(old, self.get_file(file_id).readlines(),
509
def get_parent_ids(self):
510
"""See Tree.get_parent_ids.
512
This implementation reads the pending merges list and last_revision
513
value and uses that to decide what the parents list should be.
515
last_rev = self._last_revision()
521
merges_file = self._control_files.get_utf8('pending-merges')
525
for l in merges_file.readlines():
526
parents.append(l.rstrip('\n'))
530
def get_root_id(self):
531
"""Return the id of this trees root"""
532
return self._inventory.root.file_id
534
def _get_store_filename(self, file_id):
535
## XXX: badly named; this is not in the store at all
536
return self.abspath(self.id2path(file_id))
539
def clone(self, to_bzrdir, revision_id=None, basis=None):
540
"""Duplicate this working tree into to_bzr, including all state.
542
Specifically modified files are kept as modified, but
543
ignored and unknown files are discarded.
545
If you want to make a new line of development, see bzrdir.sprout()
548
If not None, the cloned tree will have its last revision set to
549
revision, and and difference between the source trees last revision
550
and this one merged in.
553
If not None, a closer copy of a tree which may have some files in
554
common, and which file content should be preferentially copied from.
556
# assumes the target bzr dir format is compatible.
557
result = self._format.initialize(to_bzrdir)
558
self.copy_content_into(result, revision_id)
562
def copy_content_into(self, tree, revision_id=None):
563
"""Copy the current content and user files of this tree into tree."""
564
tree.set_root_id(self.get_root_id())
565
if revision_id is None:
566
merge.transform_tree(tree, self)
568
# TODO now merge from tree.last_revision to revision (to preserve
569
# user local changes)
570
merge.transform_tree(tree, self)
571
tree.set_parent_ids([revision_id])
573
def id2abspath(self, file_id):
574
return self.abspath(self.id2path(file_id))
576
def has_id(self, file_id):
577
# files that have been deleted are excluded
578
inv = self._inventory
579
if not inv.has_id(file_id):
581
path = inv.id2path(file_id)
582
return osutils.lexists(self.abspath(path))
584
def has_or_had_id(self, file_id):
585
if file_id == self.inventory.root.file_id:
587
return self.inventory.has_id(file_id)
589
__contains__ = has_id
591
def get_file_size(self, file_id):
592
return os.path.getsize(self.id2abspath(file_id))
595
def get_file_sha1(self, file_id, path=None, stat_value=None):
597
path = self._inventory.id2path(file_id)
598
return self._hashcache.get_sha1(path, stat_value)
600
def get_file_mtime(self, file_id, path=None):
602
path = self._inventory.id2path(file_id)
603
return os.lstat(self.abspath(path)).st_mtime
605
if not supports_executable():
606
def is_executable(self, file_id, path=None):
607
return self._inventory[file_id].executable
609
def is_executable(self, file_id, path=None):
611
path = self._inventory.id2path(file_id)
612
mode = os.lstat(self.abspath(path)).st_mode
613
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
616
def _add(self, files, ids, kinds):
617
"""See MutableTree._add."""
618
# TODO: Re-adding a file that is removed in the working copy
619
# should probably put it back with the previous ID.
620
# the read and write working inventory should not occur in this
621
# function - they should be part of lock_write and unlock.
622
inv = self.read_working_inventory()
623
for f, file_id, kind in zip(files, ids, kinds):
624
assert kind is not None
626
inv.add_path(f, kind=kind)
628
inv.add_path(f, kind=kind, file_id=file_id)
629
self._write_inventory(inv)
631
def add_reference(self, sub_tree):
632
"""Add a TreeReference to the tree, pointing at sub_tree"""
633
raise UnsupportedOperation(self.add_reference, self)
635
@needs_tree_write_lock
636
def _gather_kinds(self, files, kinds):
637
"""See MutableTree._gather_kinds."""
638
for pos, f in enumerate(files):
639
if kinds[pos] is None:
640
fullpath = normpath(self.abspath(f))
642
kinds[pos] = file_kind(fullpath)
644
if e.errno == errno.ENOENT:
645
raise NoSuchFile(fullpath)
648
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
649
"""Add revision_id as a parent.
651
This is equivalent to retrieving the current list of parent ids
652
and setting the list to its value plus revision_id.
654
:param revision_id: The revision id to add to the parent list. It may
655
be a ghost revision as long as its not the first parent to be added,
656
or the allow_leftmost_as_ghost parameter is set True.
657
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
659
parents = self.get_parent_ids() + [revision_id]
660
self.set_parent_ids(parents,
661
allow_leftmost_as_ghost=len(parents) > 1 or allow_leftmost_as_ghost)
663
@needs_tree_write_lock
664
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
665
"""Add revision_id, tree tuple as a parent.
667
This is equivalent to retrieving the current list of parent trees
668
and setting the list to its value plus parent_tuple. See also
669
add_parent_tree_id - if you only have a parent id available it will be
670
simpler to use that api. If you have the parent already available, using
671
this api is preferred.
673
:param parent_tuple: The (revision id, tree) to add to the parent list.
674
If the revision_id is a ghost, pass None for the tree.
675
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
677
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
678
if len(parent_ids) > 1:
679
# the leftmost may have already been a ghost, preserve that if it
681
allow_leftmost_as_ghost = True
682
self.set_parent_ids(parent_ids,
683
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
685
@needs_tree_write_lock
686
def add_pending_merge(self, *revision_ids):
687
# TODO: Perhaps should check at this point that the
688
# history of the revision is actually present?
689
parents = self.get_parent_ids()
691
for rev_id in revision_ids:
692
if rev_id in parents:
694
parents.append(rev_id)
697
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
699
@deprecated_method(zero_eleven)
701
def pending_merges(self):
702
"""Return a list of pending merges.
704
These are revisions that have been merged into the working
705
directory but not yet committed.
707
As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
708
instead - which is available on all tree objects.
710
return self.get_parent_ids()[1:]
712
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
713
"""Common ghost checking functionality from set_parent_*.
715
This checks that the left hand-parent exists if there are any
718
if len(revision_ids) > 0:
719
leftmost_id = revision_ids[0]
720
if (not allow_leftmost_as_ghost and not
721
self.branch.repository.has_revision(leftmost_id)):
722
raise errors.GhostRevisionUnusableHere(leftmost_id)
724
def _set_merges_from_parent_ids(self, parent_ids):
725
merges = parent_ids[1:]
726
self._control_files.put_utf8('pending-merges', '\n'.join(merges))
728
@needs_tree_write_lock
729
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
730
"""Set the parent ids to revision_ids.
732
See also set_parent_trees. This api will try to retrieve the tree data
733
for each element of revision_ids from the trees repository. If you have
734
tree data already available, it is more efficient to use
735
set_parent_trees rather than set_parent_ids. set_parent_ids is however
736
an easier API to use.
738
:param revision_ids: The revision_ids to set as the parent ids of this
739
working tree. Any of these may be ghosts.
741
self._check_parents_for_ghosts(revision_ids,
742
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
744
if len(revision_ids) > 0:
745
self.set_last_revision(revision_ids[0])
747
self.set_last_revision(None)
749
self._set_merges_from_parent_ids(revision_ids)
751
@needs_tree_write_lock
752
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
753
"""See MutableTree.set_parent_trees."""
754
parent_ids = [rev for (rev, tree) in parents_list]
756
self._check_parents_for_ghosts(parent_ids,
757
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
759
if len(parent_ids) == 0:
760
leftmost_parent_id = None
761
leftmost_parent_tree = None
763
leftmost_parent_id, leftmost_parent_tree = parents_list[0]
765
if self._change_last_revision(leftmost_parent_id):
766
if leftmost_parent_tree is None:
767
# If we don't have a tree, fall back to reading the
768
# parent tree from the repository.
769
self._cache_basis_inventory(leftmost_parent_id)
771
inv = leftmost_parent_tree.inventory
772
xml = self._create_basis_xml_from_inventory(
773
leftmost_parent_id, inv)
774
self._write_basis_inventory(xml)
775
self._set_merges_from_parent_ids(parent_ids)
777
@needs_tree_write_lock
778
def set_pending_merges(self, rev_list):
779
parents = self.get_parent_ids()
780
leftmost = parents[:1]
781
new_parents = leftmost + rev_list
782
self.set_parent_ids(new_parents)
784
@needs_tree_write_lock
785
def set_merge_modified(self, modified_hashes):
787
for file_id, hash in modified_hashes.iteritems():
788
yield Stanza(file_id=file_id, hash=hash)
789
self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
791
@needs_tree_write_lock
792
def _put_rio(self, filename, stanzas, header):
793
my_file = rio_file(stanzas, header)
794
self._control_files.put(filename, my_file)
796
@needs_write_lock # because merge pulls data into the branch.
797
def merge_from_branch(self, branch, to_revision=None):
798
"""Merge from a branch into this working tree.
800
:param branch: The branch to merge from.
801
:param to_revision: If non-None, the merge will merge to to_revision, but
802
not beyond it. to_revision does not need to be in the history of
803
the branch when it is supplied. If None, to_revision defaults to
804
branch.last_revision().
806
from bzrlib.merge import Merger, Merge3Merger
807
pb = bzrlib.ui.ui_factory.nested_progress_bar()
809
merger = Merger(self.branch, this_tree=self, pb=pb)
810
merger.pp = ProgressPhase("Merge phase", 5, pb)
811
merger.pp.next_phase()
812
# check that there are no
814
merger.check_basis(check_clean=True, require_commits=False)
815
if to_revision is None:
816
to_revision = branch.last_revision()
817
merger.other_rev_id = to_revision
818
if merger.other_rev_id is None:
819
raise error.NoCommits(branch)
820
self.branch.fetch(branch, last_revision=merger.other_rev_id)
821
merger.other_basis = merger.other_rev_id
822
merger.other_tree = self.branch.repository.revision_tree(
824
merger.pp.next_phase()
826
if merger.base_rev_id == merger.other_rev_id:
827
raise errors.PointlessMerge
828
merger.backup_files = False
829
merger.merge_type = Merge3Merger
830
merger.set_interesting_files(None)
831
merger.show_base = False
832
merger.reprocess = False
833
conflicts = merger.do_merge()
840
def subsume(self, other_tree):
841
def add_children(inventory, entry):
842
for child_entry in entry.children.values():
843
inventory._byid[child_entry.file_id] = child_entry
844
if child_entry.kind == 'directory':
845
add_children(inventory, child_entry)
846
if other_tree.get_root_id() == self.get_root_id():
847
raise errors.BadSubsumeSource(self, other_tree,
848
'Trees have the same root')
850
other_tree_path = self.relpath(other_tree.basedir)
851
except errors.PathNotChild:
852
raise errors.BadSubsumeSource(self, other_tree,
853
'Tree is not contained by the other')
854
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
855
if new_root_parent is None:
856
raise errors.BadSubsumeSource(self, other_tree,
857
'Parent directory is not versioned.')
858
# We need to ensure that the result of a fetch will have a
859
# versionedfile for the other_tree root, and only fetching into
860
# RepositoryKnit2 guarantees that.
861
if not self.branch.repository.supports_rich_root():
862
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
863
other_tree.lock_tree_write()
865
for parent_id in other_tree.get_parent_ids():
866
self.branch.fetch(other_tree.branch, parent_id)
867
self.add_parent_tree_id(parent_id)
868
other_root = other_tree.inventory.root
869
other_root.parent_id = new_root_parent
870
other_root.name = osutils.basename(other_tree_path)
871
self.inventory.add(other_root)
872
add_children(self.inventory, other_root)
873
self._write_inventory(self.inventory)
876
other_tree.bzrdir.destroy_workingtree_metadata()
878
@needs_tree_write_lock
879
def extract(self, file_id, format=None):
880
"""Extract a subtree from this tree.
882
A new branch will be created, relative to the path for this tree.
885
segments = osutils.splitpath(path)
886
transport = self.branch.bzrdir.root_transport
887
for name in segments:
888
transport = transport.clone(name)
891
except errors.FileExists:
895
sub_path = self.id2path(file_id)
896
branch_transport = mkdirs(sub_path)
898
format = bzrdir.format_registry.make_bzrdir('experimental-knit2')
900
branch_transport.mkdir('.')
901
except errors.FileExists:
903
branch_bzrdir = format.initialize_on_transport(branch_transport)
905
repo = branch_bzrdir.find_repository()
906
except errors.NoRepositoryPresent:
907
repo = branch_bzrdir.create_repository()
908
assert repo.supports_rich_root()
910
if not repo.supports_rich_root():
911
raise errors.RootNotRich()
912
new_branch = branch_bzrdir.create_branch()
913
new_branch.pull(self.branch)
914
for parent_id in self.get_parent_ids():
915
new_branch.fetch(self.branch, parent_id)
916
tree_transport = self.bzrdir.root_transport.clone(sub_path)
917
if tree_transport.base != branch_transport.base:
918
tree_bzrdir = format.initialize_on_transport(tree_transport)
919
branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
921
tree_bzrdir = branch_bzrdir
922
wt = tree_bzrdir.create_workingtree(NULL_REVISION)
923
wt.set_parent_ids(self.get_parent_ids())
924
my_inv = self.inventory
925
child_inv = Inventory(root_id=None)
926
new_root = my_inv[file_id]
927
my_inv.remove_recursive_id(file_id)
928
new_root.parent_id = None
929
child_inv.add(new_root)
930
self._write_inventory(my_inv)
931
wt._write_inventory(child_inv)
935
def merge_modified(self):
937
hashfile = self._control_files.get('merge-hashes')
942
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
943
raise MergeModifiedFormatError()
944
except StopIteration:
945
raise MergeModifiedFormatError()
946
for s in RioReader(hashfile):
947
file_id = s.get("file_id")
948
if file_id not in self.inventory:
951
if hash == self.get_file_sha1(file_id):
952
merge_hashes[file_id] = hash
956
def mkdir(self, path, file_id=None):
957
"""See MutableTree.mkdir()."""
959
file_id = generate_ids.gen_file_id(os.path.basename(path))
960
os.mkdir(self.abspath(path))
961
self.add(path, file_id, 'directory')
964
def get_symlink_target(self, file_id):
965
return os.readlink(self.id2abspath(file_id))
967
def file_class(self, filename):
968
if self.path2id(filename):
970
elif self.is_ignored(filename):
976
"""Write the in memory inventory to disk."""
977
# TODO: Maybe this should only write on dirty ?
978
if self._control_files._lock_mode != 'w':
979
raise errors.NotWriteLocked(self)
981
self._serialize(self._inventory, sio)
983
self._control_files.put('inventory', sio)
984
self._inventory_is_modified = False
986
def _serialize(self, inventory, out_file):
987
xml5.serializer_v5.write_inventory(self._inventory, out_file)
989
def _deserialize(selt, in_file):
990
return xml5.serializer_v5.read_inventory(in_file)
992
def list_files(self, include_root=False):
993
"""Recursively list all files as (path, class, kind, id, entry).
995
Lists, but does not descend into unversioned directories.
997
This does not include files that have been deleted in this
1000
Skips the control directory.
1002
inv = self._inventory
1003
if include_root is True:
1004
yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1005
# Convert these into local objects to save lookup times
1006
pathjoin = osutils.pathjoin
1007
file_kind = osutils.file_kind
1009
# transport.base ends in a slash, we want the piece
1010
# between the last two slashes
1011
transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
1013
fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1015
# directory file_id, relative path, absolute path, reverse sorted children
1016
children = os.listdir(self.basedir)
1018
# jam 20060527 The kernel sized tree seems equivalent whether we
1019
# use a deque and popleft to keep them sorted, or if we use a plain
1020
# list and just reverse() them.
1021
children = collections.deque(children)
1022
stack = [(inv.root.file_id, u'', self.basedir, children)]
1024
from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1027
f = children.popleft()
1028
## TODO: If we find a subdirectory with its own .bzr
1029
## directory, then that is a separate tree and we
1030
## should exclude it.
1032
# the bzrdir for this tree
1033
if transport_base_dir == f:
1036
# we know that from_dir_relpath and from_dir_abspath never end in a slash
1037
# and 'f' doesn't begin with one, we can do a string op, rather
1038
# than the checks of pathjoin(), all relative paths will have an extra slash
1040
fp = from_dir_relpath + '/' + f
1043
fap = from_dir_abspath + '/' + f
1045
f_ie = inv.get_child(from_dir_id, f)
1048
elif self.is_ignored(fp[1:]):
1051
# we may not have found this file, because of a unicode issue
1052
f_norm, can_access = osutils.normalized_filename(f)
1053
if f == f_norm or not can_access:
1054
# No change, so treat this file normally
1057
# this file can be accessed by a normalized path
1058
# check again if it is versioned
1059
# these lines are repeated here for performance
1061
fp = from_dir_relpath + '/' + f
1062
fap = from_dir_abspath + '/' + f
1063
f_ie = inv.get_child(from_dir_id, f)
1066
elif self.is_ignored(fp[1:]):
1075
raise BzrCheckError("file %r entered as kind %r id %r, "
1077
% (fap, f_ie.kind, f_ie.file_id, fk))
1079
# make a last minute entry
1081
yield fp[1:], c, fk, f_ie.file_id, f_ie
1084
yield fp[1:], c, fk, None, fk_entries[fk]()
1086
yield fp[1:], c, fk, None, TreeEntry()
1089
if fk != 'directory':
1092
# But do this child first
1093
new_children = os.listdir(fap)
1095
new_children = collections.deque(new_children)
1096
stack.append((f_ie.file_id, fp, fap, new_children))
1097
# Break out of inner loop, so that we start outer loop with child
1100
# if we finished all children, pop it off the stack
1103
@needs_tree_write_lock
1104
def move(self, from_paths, to_name):
1107
to_name must exist in the inventory.
1109
If to_name exists and is a directory, the files are moved into
1110
it, keeping their old names.
1112
Note that to_name is only the last component of the new name;
1113
this doesn't change the directory.
1115
This returns a list of (from_path, to_path) pairs for each
1116
entry that is moved.
1119
## TODO: Option to move IDs only
1120
assert not isinstance(from_paths, basestring)
1121
inv = self.inventory
1122
to_abs = self.abspath(to_name)
1123
if not isdir(to_abs):
1124
raise BzrError("destination %r is not a directory" % to_abs)
1125
if not self.has_filename(to_name):
1126
raise BzrError("destination %r not in working directory" % to_abs)
1127
to_dir_id = inv.path2id(to_name)
1128
if to_dir_id is None and to_name != '':
1129
raise BzrError("destination %r is not a versioned directory" % to_name)
1130
to_dir_ie = inv[to_dir_id]
1131
if to_dir_ie.kind != 'directory':
1132
raise BzrError("destination %r is not a directory" % to_abs)
1134
to_idpath = inv.get_idpath(to_dir_id)
1136
for f in from_paths:
1137
if not self.has_filename(f):
1138
raise BzrError("%r does not exist in working tree" % f)
1139
f_id = inv.path2id(f)
1141
raise BzrError("%r is not versioned" % f)
1142
name_tail = splitpath(f)[-1]
1143
dest_path = pathjoin(to_name, name_tail)
1144
if self.has_filename(dest_path):
1145
raise BzrError("destination %r already exists" % dest_path)
1146
if f_id in to_idpath:
1147
raise BzrError("can't move %r to a subdirectory of itself" % f)
1149
# OK, so there's a race here, it's possible that someone will
1150
# create a file in this interval and then the rename might be
1151
# left half-done. But we should have caught most problems.
1152
orig_inv = deepcopy(self.inventory)
1153
original_modified = self._inventory_is_modified
1156
self._inventory_is_modified = True
1157
for f in from_paths:
1158
name_tail = splitpath(f)[-1]
1159
dest_path = pathjoin(to_name, name_tail)
1160
result.append((f, dest_path))
1161
inv.rename(inv.path2id(f), to_dir_id, name_tail)
1163
osutils.rename(self.abspath(f), self.abspath(dest_path))
1165
raise BzrError("failed to rename %r to %r: %s" %
1166
(f, dest_path, e[1]))
1168
# restore the inventory on error
1169
self._set_inventory(orig_inv, dirty=original_modified)
1171
self._write_inventory(inv)
1174
@needs_tree_write_lock
1175
def rename_one(self, from_rel, to_rel):
1178
This can change the directory or the filename or both.
1180
inv = self.inventory
1181
if not self.has_filename(from_rel):
1182
raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1183
if self.has_filename(to_rel):
1184
raise BzrError("can't rename: new working file %r already exists" % to_rel)
1186
file_id = inv.path2id(from_rel)
1188
raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1190
entry = inv[file_id]
1191
from_parent = entry.parent_id
1192
from_name = entry.name
1194
if inv.path2id(to_rel):
1195
raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1197
to_dir, to_tail = os.path.split(to_rel)
1198
to_dir_id = inv.path2id(to_dir)
1199
if to_dir_id is None and to_dir != '':
1200
raise BzrError("can't determine destination directory id for %r" % to_dir)
1202
mutter("rename_one:")
1203
mutter(" file_id {%s}" % file_id)
1204
mutter(" from_rel %r" % from_rel)
1205
mutter(" to_rel %r" % to_rel)
1206
mutter(" to_dir %r" % to_dir)
1207
mutter(" to_dir_id {%s}" % to_dir_id)
1209
inv.rename(file_id, to_dir_id, to_tail)
1211
from_abs = self.abspath(from_rel)
1212
to_abs = self.abspath(to_rel)
1214
osutils.rename(from_abs, to_abs)
1216
inv.rename(file_id, from_parent, from_name)
1217
raise BzrError("failed to rename %r to %r: %s"
1218
% (from_abs, to_abs, e[1]))
1219
self._write_inventory(inv)
1223
"""Return all unknown files.
1225
These are files in the working directory that are not versioned or
1226
control files or ignored.
1228
for subp in self.extras():
1229
if not self.is_ignored(subp):
1232
@needs_tree_write_lock
1233
def unversion(self, file_ids):
1234
"""Remove the file ids in file_ids from the current versioned set.
1236
When a file_id is unversioned, all of its children are automatically
1239
:param file_ids: The file ids to stop versioning.
1240
:raises: NoSuchId if any fileid is not currently versioned.
1242
for file_id in file_ids:
1243
if self._inventory.has_id(file_id):
1244
self._inventory.remove_recursive_id(file_id)
1246
raise errors.NoSuchId(self, file_id)
1248
# in the future this should just set a dirty bit to wait for the
1249
# final unlock. However, until all methods of workingtree start
1250
# with the current in -memory inventory rather than triggering
1251
# a read, it is more complex - we need to teach read_inventory
1252
# to know when to read, and when to not read first... and possibly
1253
# to save first when the in memory one may be corrupted.
1254
# so for now, we just only write it if it is indeed dirty.
1256
self._write_inventory(self._inventory)
1258
@deprecated_method(zero_eight)
1259
def iter_conflicts(self):
1260
"""List all files in the tree that have text or content conflicts.
1261
DEPRECATED. Use conflicts instead."""
1262
return self._iter_conflicts()
1264
def _iter_conflicts(self):
1266
for info in self.list_files():
1268
stem = get_conflicted_stem(path)
1271
if stem not in conflicted:
1272
conflicted.add(stem)
1276
def pull(self, source, overwrite=False, stop_revision=None):
1277
top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1280
pp = ProgressPhase("Pull phase", 2, top_pb)
1282
old_revision_history = self.branch.revision_history()
1283
basis_tree = self.basis_tree()
1284
count = self.branch.pull(source, overwrite, stop_revision)
1285
new_revision_history = self.branch.revision_history()
1286
if new_revision_history != old_revision_history:
1288
if len(old_revision_history):
1289
other_revision = old_revision_history[-1]
1291
other_revision = None
1292
repository = self.branch.repository
1293
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1295
new_basis_tree = self.branch.basis_tree()
1302
if (basis_tree.inventory.root is None and
1303
new_basis_tree.inventory.root is not None):
1304
self.set_root_id(new_basis_tree.inventory.root.file_id)
1307
# TODO - dedup parents list with things merged by pull ?
1308
# reuse the revisiontree we merged against to set the new
1310
parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1311
# we have to pull the merge trees out again, because
1312
# merge_inner has set the ids. - this corner is not yet
1313
# layered well enough to prevent double handling.
1314
merges = self.get_parent_ids()[1:]
1315
parent_trees.extend([
1316
(parent, repository.revision_tree(parent)) for
1318
self.set_parent_trees(parent_trees)
1325
def put_file_bytes_non_atomic(self, file_id, bytes):
1326
"""See MutableTree.put_file_bytes_non_atomic."""
1327
stream = file(self.id2abspath(file_id), 'wb')
1332
# TODO: update the hashcache here ?
1335
"""Yield all unknown files in this WorkingTree.
1337
If there are any unknown directories then only the directory is
1338
returned, not all its children. But if there are unknown files
1339
under a versioned subdirectory, they are returned.
1341
Currently returned depth-first, sorted by name within directories.
1343
## TODO: Work from given directory downwards
1344
for path, dir_entry in self.inventory.directories():
1345
# mutter("search for unknowns in %r", path)
1346
dirabs = self.abspath(path)
1347
if not isdir(dirabs):
1348
# e.g. directory deleted
1352
for subf in os.listdir(dirabs):
1355
if subf not in dir_entry.children:
1356
subf_norm, can_access = osutils.normalized_filename(subf)
1357
if subf_norm != subf and can_access:
1358
if subf_norm not in dir_entry.children:
1359
fl.append(subf_norm)
1365
subp = pathjoin(path, subf)
1369
def ignored_files(self):
1370
"""Yield list of PATH, IGNORE_PATTERN"""
1371
for subp in self.extras():
1372
pat = self.is_ignored(subp)
1376
def get_ignore_list(self):
1377
"""Return list of ignore patterns.
1379
Cached in the Tree object after the first call.
1381
ignoreset = getattr(self, '_ignoreset', None)
1382
if ignoreset is not None:
1385
ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1386
ignore_globs.update(ignores.get_runtime_ignores())
1387
ignore_globs.update(ignores.get_user_ignores())
1388
if self.has_filename(bzrlib.IGNORE_FILENAME):
1389
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1391
ignore_globs.update(ignores.parse_ignore_file(f))
1394
self._ignoreset = ignore_globs
1397
def _flush_ignore_list_cache(self):
1398
"""Resets the cached ignore list to force a cache rebuild."""
1399
self._ignoreset = None
1400
self._ignoreglobster = None
1402
def is_ignored(self, filename):
1403
r"""Check whether the filename matches an ignore pattern.
1405
Patterns containing '/' or '\' need to match the whole path;
1406
others match against only the last component.
1408
If the file is ignored, returns the pattern which caused it to
1409
be ignored, otherwise None. So this can simply be used as a
1410
boolean if desired."""
1411
if getattr(self, '_ignoreglobster', None) is None:
1412
self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1413
return self._ignoreglobster.match(filename)
1415
def kind(self, file_id):
1416
return file_kind(self.id2abspath(file_id))
1418
def _comparison_data(self, entry, path):
1419
abspath = self.abspath(path)
1421
stat_value = os.lstat(abspath)
1423
if getattr(e, 'errno', None) == errno.ENOENT:
1430
mode = stat_value.st_mode
1431
kind = osutils.file_kind_from_stat_mode(mode)
1432
if not supports_executable():
1433
executable = entry.executable
1435
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1436
return kind, executable, stat_value
1438
def _file_size(self, entry, stat_value):
1439
return stat_value.st_size
1441
def last_revision(self):
1442
"""Return the last revision of the branch for this tree.
1444
This format tree does not support a separate marker for last-revision
1445
compared to the branch.
1447
See MutableTree.last_revision
1449
return self._last_revision()
1452
def _last_revision(self):
1453
"""helper for get_parent_ids."""
1454
return self.branch.last_revision()
1456
def is_locked(self):
1457
return self._control_files.is_locked()
1459
def lock_read(self):
1460
"""See Branch.lock_read, and WorkingTree.unlock."""
1461
self.branch.lock_read()
1463
return self._control_files.lock_read()
1465
self.branch.unlock()
1468
def lock_tree_write(self):
1469
"""See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1470
self.branch.lock_read()
1472
return self._control_files.lock_write()
1474
self.branch.unlock()
1477
def lock_write(self):
1478
"""See MutableTree.lock_write, and WorkingTree.unlock."""
1479
self.branch.lock_write()
1481
return self._control_files.lock_write()
1483
self.branch.unlock()
1486
def get_physical_lock_status(self):
1487
return self._control_files.get_physical_lock_status()
1489
def _basis_inventory_name(self):
1490
return 'basis-inventory-cache'
1492
@needs_tree_write_lock
1493
def set_last_revision(self, new_revision):
1494
"""Change the last revision in the working tree."""
1495
if self._change_last_revision(new_revision):
1496
self._cache_basis_inventory(new_revision)
1498
def _change_last_revision(self, new_revision):
1499
"""Template method part of set_last_revision to perform the change.
1501
This is used to allow WorkingTree3 instances to not affect branch
1502
when their last revision is set.
1504
if new_revision is None:
1505
self.branch.set_revision_history([])
1508
self.branch.generate_revision_history(new_revision)
1509
except errors.NoSuchRevision:
1510
# not present in the repo - dont try to set it deeper than the tip
1511
self.branch.set_revision_history([new_revision])
1514
def _write_basis_inventory(self, xml):
1515
"""Write the basis inventory XML to the basis-inventory file"""
1516
assert isinstance(xml, str), 'serialised xml must be bytestring.'
1517
path = self._basis_inventory_name()
1519
self._control_files.put(path, sio)
1521
def _create_basis_xml_from_inventory(self, revision_id, inventory):
1522
"""Create the text that will be saved in basis-inventory"""
1523
inventory.revision_id = revision_id
1524
return xml7.serializer_v7.write_inventory_to_string(inventory)
1526
def _cache_basis_inventory(self, new_revision):
1527
"""Cache new_revision as the basis inventory."""
1528
# TODO: this should allow the ready-to-use inventory to be passed in,
1529
# as commit already has that ready-to-use [while the format is the
1532
# this double handles the inventory - unpack and repack -
1533
# but is easier to understand. We can/should put a conditional
1534
# in here based on whether the inventory is in the latest format
1535
# - perhaps we should repack all inventories on a repository
1537
# the fast path is to copy the raw xml from the repository. If the
1538
# xml contains 'revision_id="', then we assume the right
1539
# revision_id is set. We must check for this full string, because a
1540
# root node id can legitimately look like 'revision_id' but cannot
1542
xml = self.branch.repository.get_inventory_xml(new_revision)
1543
firstline = xml.split('\n', 1)[0]
1544
if (not 'revision_id="' in firstline or
1545
'format="7"' not in firstline):
1546
inv = self.branch.repository.deserialise_inventory(
1548
xml = self._create_basis_xml_from_inventory(new_revision, inv)
1549
self._write_basis_inventory(xml)
1550
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1553
def read_basis_inventory(self):
1554
"""Read the cached basis inventory."""
1555
path = self._basis_inventory_name()
1556
return self._control_files.get(path).read()
1559
def read_working_inventory(self):
1560
"""Read the working inventory.
1562
:raises errors.InventoryModified: read_working_inventory will fail
1563
when the current in memory inventory has been modified.
1565
# conceptually this should be an implementation detail of the tree.
1566
# XXX: Deprecate this.
1567
# ElementTree does its own conversion from UTF-8, so open in
1569
if self._inventory_is_modified:
1570
raise errors.InventoryModified(self)
1571
result = self._deserialize(self._control_files.get('inventory'))
1572
self._set_inventory(result, dirty=False)
1575
@needs_tree_write_lock
1576
def remove(self, files, verbose=False, to_file=None):
1577
"""Remove nominated files from the working inventory..
1579
This does not remove their text. This does not run on XXX on what? RBC
1581
TODO: Refuse to remove modified files unless --force is given?
1583
TODO: Do something useful with directories.
1585
TODO: Should this remove the text or not? Tough call; not
1586
removing may be useful and the user can just use use rm, and
1587
is the opposite of add. Removing it is consistent with most
1588
other tools. Maybe an option.
1590
## TODO: Normalize names
1591
## TODO: Remove nested loops; better scalability
1592
if isinstance(files, basestring):
1595
inv = self.inventory
1597
# do this before any modifications
1599
fid = inv.path2id(f)
1601
# TODO: Perhaps make this just a warning, and continue?
1602
# This tends to happen when
1603
raise NotVersionedError(path=f)
1605
# having remove it, it must be either ignored or unknown
1606
if self.is_ignored(f):
1610
textui.show_status(new_status, inv[fid].kind, f,
1614
self._write_inventory(inv)
1616
@needs_tree_write_lock
1617
def revert(self, filenames, old_tree=None, backups=True,
1618
pb=DummyProgress()):
1619
from bzrlib.conflicts import resolve
1620
if old_tree is None:
1621
old_tree = self.basis_tree()
1622
conflicts = transform.revert(self, old_tree, filenames, backups, pb)
1623
if not len(filenames):
1624
self.set_parent_ids(self.get_parent_ids()[:1])
1627
resolve(self, filenames, ignore_misses=True)
1630
# XXX: This method should be deprecated in favour of taking in a proper
1631
# new Inventory object.
1632
@needs_tree_write_lock
1633
def set_inventory(self, new_inventory_list):
1634
from bzrlib.inventory import (Inventory,
1639
inv = Inventory(self.get_root_id())
1640
for path, file_id, parent, kind in new_inventory_list:
1641
name = os.path.basename(path)
1644
# fixme, there should be a factory function inv,add_??
1645
if kind == 'directory':
1646
inv.add(InventoryDirectory(file_id, name, parent))
1647
elif kind == 'file':
1648
inv.add(InventoryFile(file_id, name, parent))
1649
elif kind == 'symlink':
1650
inv.add(InventoryLink(file_id, name, parent))
1652
raise BzrError("unknown kind %r" % kind)
1653
self._write_inventory(inv)
1655
@needs_tree_write_lock
1656
def set_root_id(self, file_id):
1657
"""Set the root id for this tree."""
1660
symbol_versioning.warn(symbol_versioning.zero_twelve
1661
% 'WorkingTree.set_root_id with fileid=None',
1665
inv = self._inventory
1666
orig_root_id = inv.root.file_id
1667
# TODO: it might be nice to exit early if there was nothing
1668
# to do, saving us from trigger a sync on unlock.
1669
self._inventory_is_modified = True
1670
# we preserve the root inventory entry object, but
1671
# unlinkit from the byid index
1672
del inv._byid[inv.root.file_id]
1673
inv.root.file_id = file_id
1674
# and link it into the index with the new changed id.
1675
inv._byid[inv.root.file_id] = inv.root
1676
# and finally update all children to reference the new id.
1677
# XXX: this should be safe to just look at the root.children
1678
# list, not the WHOLE INVENTORY.
1681
if entry.parent_id == orig_root_id:
1682
entry.parent_id = inv.root.file_id
1685
"""See Branch.unlock.
1687
WorkingTree locking just uses the Branch locking facilities.
1688
This is current because all working trees have an embedded branch
1689
within them. IF in the future, we were to make branch data shareable
1690
between multiple working trees, i.e. via shared storage, then we
1691
would probably want to lock both the local tree, and the branch.
1693
raise NotImplementedError(self.unlock)
1696
"""Update a working tree along its branch.
1698
This will update the branch if its bound too, which means we have
1699
multiple trees involved:
1701
- The new basis tree of the master.
1702
- The old basis tree of the branch.
1703
- The old basis tree of the working tree.
1704
- The current working tree state.
1706
Pathologically, all three may be different, and non-ancestors of each
1707
other. Conceptually we want to:
1709
- Preserve the wt.basis->wt.state changes
1710
- Transform the wt.basis to the new master basis.
1711
- Apply a merge of the old branch basis to get any 'local' changes from
1713
- Restore the wt.basis->wt.state changes.
1715
There isn't a single operation at the moment to do that, so we:
1716
- Merge current state -> basis tree of the master w.r.t. the old tree
1718
- Do a 'normal' merge of the old branch basis if it is relevant.
1720
if self.branch.get_master_branch() is not None:
1722
update_branch = True
1724
self.lock_tree_write()
1725
update_branch = False
1728
old_tip = self.branch.update()
1731
return self._update_tree(old_tip)
1735
@needs_tree_write_lock
1736
def _update_tree(self, old_tip=None):
1737
"""Update a tree to the master branch.
1739
:param old_tip: if supplied, the previous tip revision the branch,
1740
before it was changed to the master branch's tip.
1742
# here if old_tip is not None, it is the old tip of the branch before
1743
# it was updated from the master branch. This should become a pending
1744
# merge in the working tree to preserve the user existing work. we
1745
# cant set that until we update the working trees last revision to be
1746
# one from the new branch, because it will just get absorbed by the
1747
# parent de-duplication logic.
1749
# We MUST save it even if an error occurs, because otherwise the users
1750
# local work is unreferenced and will appear to have been lost.
1754
last_rev = self.get_parent_ids()[0]
1757
if last_rev != self.branch.last_revision():
1758
# merge tree state up to new branch tip.
1759
basis = self.basis_tree()
1760
to_tree = self.branch.basis_tree()
1761
if basis.inventory.root is None:
1762
self.set_root_id(to_tree.inventory.root.file_id)
1763
result += merge.merge_inner(
1768
# TODO - dedup parents list with things merged by pull ?
1769
# reuse the tree we've updated to to set the basis:
1770
parent_trees = [(self.branch.last_revision(), to_tree)]
1771
merges = self.get_parent_ids()[1:]
1772
# Ideally we ask the tree for the trees here, that way the working
1773
# tree can decide whether to give us teh entire tree or give us a
1774
# lazy initialised tree. dirstate for instance will have the trees
1775
# in ram already, whereas a last-revision + basis-inventory tree
1776
# will not, but also does not need them when setting parents.
1777
for parent in merges:
1778
parent_trees.append(
1779
(parent, self.branch.repository.revision_tree(parent)))
1780
if old_tip is not None:
1781
parent_trees.append(
1782
(old_tip, self.branch.repository.revision_tree(old_tip)))
1783
self.set_parent_trees(parent_trees)
1784
last_rev = parent_trees[0][0]
1786
# the working tree had the same last-revision as the master
1787
# branch did. We may still have pivot local work from the local
1788
# branch into old_tip:
1789
if old_tip is not None:
1790
self.add_parent_tree_id(old_tip)
1791
if old_tip and old_tip != last_rev:
1792
# our last revision was not the prior branch last revision
1793
# and we have converted that last revision to a pending merge.
1794
# base is somewhere between the branch tip now
1795
# and the now pending merge
1796
from bzrlib.revision import common_ancestor
1798
base_rev_id = common_ancestor(self.branch.last_revision(),
1800
self.branch.repository)
1801
except errors.NoCommonAncestor:
1803
base_tree = self.branch.repository.revision_tree(base_rev_id)
1804
other_tree = self.branch.repository.revision_tree(old_tip)
1805
result += merge.merge_inner(
1812
def _write_hashcache_if_dirty(self):
1813
"""Write out the hashcache if it is dirty."""
1814
if self._hashcache.needs_write:
1816
self._hashcache.write()
1818
if e.errno not in (errno.EPERM, errno.EACCES):
1820
# TODO: jam 20061219 Should this be a warning? A single line
1821
# warning might be sufficient to let the user know what
1823
mutter('Could not write hashcache for %s\nError: %s',
1824
self._hashcache.cache_file_name(), e)
1826
@needs_tree_write_lock
1827
def _write_inventory(self, inv):
1828
"""Write inventory as the current inventory."""
1829
self._set_inventory(inv, dirty=True)
1832
def set_conflicts(self, arg):
1833
raise UnsupportedOperation(self.set_conflicts, self)
1835
def add_conflicts(self, arg):
1836
raise UnsupportedOperation(self.add_conflicts, self)
1839
def conflicts(self):
1840
conflicts = _mod_conflicts.ConflictList()
1841
for conflicted in self._iter_conflicts():
1844
if file_kind(self.abspath(conflicted)) != "file":
1846
except errors.NoSuchFile:
1849
for suffix in ('.THIS', '.OTHER'):
1851
kind = file_kind(self.abspath(conflicted+suffix))
1854
except errors.NoSuchFile:
1858
ctype = {True: 'text conflict', False: 'contents conflict'}[text]
1859
conflicts.append(_mod_conflicts.Conflict.factory(ctype,
1861
file_id=self.path2id(conflicted)))
1865
class WorkingTree2(WorkingTree):
1866
"""This is the Format 2 working tree.
1868
This was the first weave based working tree.
1869
- uses os locks for locking.
1870
- uses the branch last-revision.
1873
def lock_tree_write(self):
1874
"""See WorkingTree.lock_tree_write().
1876
In Format2 WorkingTrees we have a single lock for the branch and tree
1877
so lock_tree_write() degrades to lock_write().
1879
self.branch.lock_write()
1881
return self._control_files.lock_write()
1883
self.branch.unlock()
1887
# we share control files:
1888
if self._control_files._lock_count == 3:
1889
# _inventory_is_modified is always False during a read lock.
1890
if self._inventory_is_modified:
1892
self._write_hashcache_if_dirty()
1894
# reverse order of locking.
1896
return self._control_files.unlock()
1898
self.branch.unlock()
1901
class WorkingTree3(WorkingTree):
1902
"""This is the Format 3 working tree.
1904
This differs from the base WorkingTree by:
1905
- having its own file lock
1906
- having its own last-revision property.
1908
This is new in bzr 0.8
1912
def _last_revision(self):
1913
"""See Mutable.last_revision."""
1915
return self._control_files.get_utf8('last-revision').read()
1919
def _change_last_revision(self, revision_id):
1920
"""See WorkingTree._change_last_revision."""
1921
if revision_id is None or revision_id == NULL_REVISION:
1923
self._control_files._transport.delete('last-revision')
1924
except errors.NoSuchFile:
1928
self._control_files.put_utf8('last-revision', revision_id)
1931
@needs_tree_write_lock
1932
def set_conflicts(self, conflicts):
1933
self._put_rio('conflicts', conflicts.to_stanzas(),
1936
@needs_tree_write_lock
1937
def add_conflicts(self, new_conflicts):
1938
conflict_set = set(self.conflicts())
1939
conflict_set.update(set(list(new_conflicts)))
1940
self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
1941
key=_mod_conflicts.Conflict.sort_key)))
1944
def conflicts(self):
1946
confile = self._control_files.get('conflicts')
1948
return _mod_conflicts.ConflictList()
1950
if confile.next() != CONFLICT_HEADER_1 + '\n':
1951
raise ConflictFormatError()
1952
except StopIteration:
1953
raise ConflictFormatError()
1954
return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
1957
if self._control_files._lock_count == 1:
1958
# _inventory_is_modified is always False during a read lock.
1959
if self._inventory_is_modified:
1961
self._write_hashcache_if_dirty()
1962
# reverse order of locking.
1964
return self._control_files.unlock()
1966
self.branch.unlock()
1969
class WorkingTree4(WorkingTree3):
1971
def add_reference(self, sub_tree):
1973
sub_tree_path = self.relpath(sub_tree.basedir)
1974
except errors.PathNotChild:
1975
raise errors.BadReferenceTarget(self, sub_tree,
1976
'Target not inside tree.')
1977
parent_id = self.path2id(osutils.dirname(sub_tree_path))
1978
name = osutils.basename(sub_tree_path)
1979
sub_tree_id = sub_tree.get_root_id()
1980
if sub_tree_id == self.get_root_id():
1981
raise errors.BadReferenceTarget(self, sub_tree,
1982
'Trees have the same root id.')
1983
if sub_tree_id in self.inventory:
1984
raise errors.BadReferenceTarget(self, sub_tree,
1985
'Root id already present in tree')
1986
entry = TreeReference(sub_tree_id, name, parent_id, None,
1988
self.inventory.add(entry)
1989
self._write_inventory(self.inventory)
1991
def _serialize(self, inventory, out_file):
1992
xml7.serializer_v7.write_inventory(self._inventory, out_file)
1994
def _deserialize(selt, in_file):
1995
return xml7.serializer_v7.read_inventory(in_file)
1998
def get_conflicted_stem(path):
1999
for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
2000
if path.endswith(suffix):
2001
return path[:-len(suffix)]
2003
@deprecated_function(zero_eight)
2004
def is_control_file(filename):
2005
"""See WorkingTree.is_control_filename(filename)."""
2006
## FIXME: better check
2007
filename = normpath(filename)
2008
while filename != '':
2009
head, tail = os.path.split(filename)
2010
## mutter('check %r for control file' % ((head, tail),))
2013
if filename == head:
2019
class WorkingTreeFormat(object):
2020
"""An encapsulation of the initialization and open routines for a format.
2022
Formats provide three things:
2023
* An initialization routine,
2027
Formats are placed in an dict by their format string for reference
2028
during workingtree opening. Its not required that these be instances, they
2029
can be classes themselves with class methods - it simply depends on
2030
whether state is needed for a given format or not.
2032
Once a format is deprecated, just deprecate the initialize and open
2033
methods on the format class. Do not deprecate the object, as the
2034
object will be created every time regardless.
2037
_default_format = None
2038
"""The default format used for new trees."""
2041
"""The known formats."""
2043
requires_rich_root = False
2046
def find_format(klass, a_bzrdir):
2047
"""Return the format for the working tree object in a_bzrdir."""
2049
transport = a_bzrdir.get_workingtree_transport(None)
2050
format_string = transport.get("format").read()
2051
return klass._formats[format_string]
2053
raise errors.NoWorkingTree(base=transport.base)
2055
raise errors.UnknownFormatError(format=format_string)
2058
def get_default_format(klass):
2059
"""Return the current default format."""
2060
return klass._default_format
2062
def get_format_string(self):
2063
"""Return the ASCII format string that identifies this format."""
2064
raise NotImplementedError(self.get_format_string)
2066
def get_format_description(self):
2067
"""Return the short description for this format."""
2068
raise NotImplementedError(self.get_format_description)
2070
def is_supported(self):
2071
"""Is this format supported?
2073
Supported formats can be initialized and opened.
2074
Unsupported formats may not support initialization or committing or
2075
some other features depending on the reason for not being supported.
2080
def register_format(klass, format):
2081
klass._formats[format.get_format_string()] = format
2084
def set_default_format(klass, format):
2085
klass._default_format = format
2088
def unregister_format(klass, format):
2089
assert klass._formats[format.get_format_string()] is format
2090
del klass._formats[format.get_format_string()]
2094
class WorkingTreeFormat2(WorkingTreeFormat):
2095
"""The second working tree format.
2097
This format modified the hash cache from the format 1 hash cache.
2100
def get_format_description(self):
2101
"""See WorkingTreeFormat.get_format_description()."""
2102
return "Working tree format 2"
2104
def stub_initialize_remote(self, control_files):
2105
"""As a special workaround create critical control files for a remote working tree
2107
This ensures that it can later be updated and dealt with locally,
2108
since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
2109
no working tree. (See bug #43064).
2113
xml5.serializer_v5.write_inventory(inv, sio)
2115
control_files.put('inventory', sio)
2117
control_files.put_utf8('pending-merges', '')
2120
def initialize(self, a_bzrdir, revision_id=None):
2121
"""See WorkingTreeFormat.initialize()."""
2122
if not isinstance(a_bzrdir.transport, LocalTransport):
2123
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2124
branch = a_bzrdir.open_branch()
2125
if revision_id is not None:
2128
revision_history = branch.revision_history()
2130
position = revision_history.index(revision_id)
2132
raise errors.NoSuchRevision(branch, revision_id)
2133
branch.set_revision_history(revision_history[:position + 1])
2136
revision = branch.last_revision()
2138
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2144
basis_tree = branch.repository.revision_tree(revision)
2145
if basis_tree.inventory.root is not None:
2146
wt.set_root_id(basis_tree.inventory.root.file_id)
2147
# set the parent list and cache the basis tree.
2148
wt.set_parent_trees([(revision, basis_tree)])
2149
transform.build_tree(basis_tree, wt)
2153
super(WorkingTreeFormat2, self).__init__()
2154
self._matchingbzrdir = bzrdir.BzrDirFormat6()
2156
def open(self, a_bzrdir, _found=False):
2157
"""Return the WorkingTree object for a_bzrdir
2159
_found is a private parameter, do not use it. It is used to indicate
2160
if format probing has already been done.
2163
# we are being called directly and must probe.
2164
raise NotImplementedError
2165
if not isinstance(a_bzrdir.transport, LocalTransport):
2166
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2167
return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2173
class WorkingTreeFormat3(WorkingTreeFormat):
2174
"""The second working tree format updated to record a format marker.
2177
- exists within a metadir controlling .bzr
2178
- includes an explicit version marker for the workingtree control
2179
files, separate from the BzrDir format
2180
- modifies the hash cache format
2182
- uses a LockDir to guard access for writes.
2185
def get_format_string(self):
2186
"""See WorkingTreeFormat.get_format_string()."""
2187
return "Bazaar-NG Working Tree format 3"
2189
def get_format_description(self):
2190
"""See WorkingTreeFormat.get_format_description()."""
2191
return "Working tree format 3"
2193
_lock_file_name = 'lock'
2194
_lock_class = LockDir
2195
_tree_class = WorkingTree3
2197
def __get_matchingbzrdir(self):
2198
return bzrdir.BzrDirMetaFormat1()
2200
_matchingbzrdir = property(__get_matchingbzrdir)
2202
def _open_control_files(self, a_bzrdir):
2203
transport = a_bzrdir.get_workingtree_transport(None)
2204
return LockableFiles(transport, self._lock_file_name,
2207
def initialize(self, a_bzrdir, revision_id=None):
2208
"""See WorkingTreeFormat.initialize().
2210
revision_id allows creating a working tree at a different
2211
revision than the branch is at.
2213
if not isinstance(a_bzrdir.transport, LocalTransport):
2214
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2215
transport = a_bzrdir.get_workingtree_transport(self)
2216
control_files = self._open_control_files(a_bzrdir)
2217
control_files.create_lock()
2218
control_files.lock_write()
2219
control_files.put_utf8('format', self.get_format_string())
2220
branch = a_bzrdir.open_branch()
2221
if revision_id is None:
2222
revision_id = branch.last_revision()
2223
inv = self._initial_inventory()
2224
wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2230
_control_files=control_files)
2231
wt.lock_tree_write()
2233
basis_tree = branch.repository.revision_tree(revision_id)
2234
# only set an explicit root id if there is one to set.
2235
if basis_tree.inventory.root is not None:
2236
wt.set_root_id(basis_tree.inventory.root.file_id)
2237
if revision_id == NULL_REVISION:
2238
wt.set_parent_trees([])
2240
wt.set_parent_trees([(revision_id, basis_tree)])
2241
transform.build_tree(basis_tree, wt)
2243
# Unlock in this order so that the unlock-triggers-flush in
2244
# WorkingTree is given a chance to fire.
2245
control_files.unlock()
2249
def _initial_inventory(self):
2253
super(WorkingTreeFormat3, self).__init__()
2255
def open(self, a_bzrdir, _found=False):
2256
"""Return the WorkingTree object for a_bzrdir
2258
_found is a private parameter, do not use it. It is used to indicate
2259
if format probing has already been done.
2262
# we are being called directly and must probe.
2263
raise NotImplementedError
2264
if not isinstance(a_bzrdir.transport, LocalTransport):
2265
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2266
return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
2268
def _open(self, a_bzrdir, control_files):
2269
"""Open the tree itself.
2271
:param a_bzrdir: the dir for the tree.
2272
:param control_files: the control files for the tree.
2274
return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2278
_control_files=control_files)
2281
return self.get_format_string()
2284
class WorkingTreeFormat4(WorkingTreeFormat3):
2286
"""Working tree format that supports unique roots and nested trees"""
2288
_tree_class = WorkingTree4
2290
requires_rich_root = True
2293
WorkingTreeFormat3.__init__(self)
2295
def __get_matchingbzrdir(self):
2296
return bzrdir.format_registry.make_bzrdir('experimental-knit3')
2298
_matchingbzrdir = property(__get_matchingbzrdir)
2300
def get_format_string(self):
2301
"""See WorkingTreeFormat.get_format_string()."""
2302
return "Bazaar-NG Working Tree format 4"
2304
def get_format_description(self):
2305
"""See WorkingTreeFormat.get_format_description()."""
2306
return "Working tree format 4"
2308
def _initial_inventory(self):
2309
return Inventory(root_id=generate_ids.gen_root_id())
2311
# formats which have no format string are not discoverable
2312
# and not independently creatable, so are not registered.
2313
__default_format = WorkingTreeFormat3()
2314
WorkingTreeFormat.register_format(__default_format)
2315
WorkingTreeFormat.register_format(WorkingTreeFormat4())
2316
WorkingTreeFormat.set_default_format(__default_format)
2317
_legacy_formats = [WorkingTreeFormat2(),
2321
class WorkingTreeTestProviderAdapter(object):
2322
"""A tool to generate a suite testing multiple workingtree formats at once.
2324
This is done by copying the test once for each transport and injecting
2325
the transport_server, transport_readonly_server, and workingtree_format
2326
classes into each copy. Each copy is also given a new id() to make it
2330
def __init__(self, transport_server, transport_readonly_server, formats):
2331
self._transport_server = transport_server
2332
self._transport_readonly_server = transport_readonly_server
2333
self._formats = formats
2335
def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2336
"""Clone test for adaption."""
2337
new_test = deepcopy(test)
2338
new_test.transport_server = self._transport_server
2339
new_test.transport_readonly_server = self._transport_readonly_server
2340
new_test.bzrdir_format = bzrdir_format
2341
new_test.workingtree_format = workingtree_format
2342
def make_new_test_id():
2343
new_id = "%s(%s)" % (test.id(), variation)
2344
return lambda: new_id
2345
new_test.id = make_new_test_id()
2348
def adapt(self, test):
2349
from bzrlib.tests import TestSuite
2350
result = TestSuite()
2351
for workingtree_format, bzrdir_format in self._formats:
2352
new_test = self._clone_test(
2355
workingtree_format, workingtree_format.__class__.__name__)
2356
result.addTest(new_test)