1
# Copyright (C) 2005, 2006, 2007 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(), """
44
from bisect import bisect_left
46
from copy import deepcopy
59
conflicts as _mod_conflicts,
80
from bzrlib.transport import get_transport
82
from bzrlib.workingtree_4 import WorkingTreeFormat4
85
from bzrlib import symbol_versioning
86
from bzrlib.decorators import needs_read_lock, needs_write_lock
87
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
88
from bzrlib.lockable_files import LockableFiles, TransportLock
89
from bzrlib.lockdir import LockDir
90
import bzrlib.mutabletree
91
from bzrlib.mutabletree import needs_tree_write_lock
92
from bzrlib.osutils import (
104
from bzrlib.trace import mutter, note
105
from bzrlib.transport.local import LocalTransport
106
from bzrlib.progress import DummyProgress, ProgressPhase
107
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
108
from bzrlib.rio import RioReader, rio_file, Stanza
109
from bzrlib.symbol_versioning import (deprecated_passed,
112
DEPRECATED_PARAMETER,
119
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
120
CONFLICT_HEADER_1 = "BZR conflict list format 1"
123
@deprecated_function(zero_thirteen)
124
def gen_file_id(name):
125
"""Return new file id for the basename 'name'.
127
Use bzrlib.generate_ids.gen_file_id() instead
129
return generate_ids.gen_file_id(name)
132
@deprecated_function(zero_thirteen)
134
"""Return a new tree-root file id.
136
This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
138
return generate_ids.gen_root_id()
141
class TreeEntry(object):
142
"""An entry that implements the minimum interface used by commands.
144
This needs further inspection, it may be better to have
145
InventoryEntries without ids - though that seems wrong. For now,
146
this is a parallel hierarchy to InventoryEntry, and needs to become
147
one of several things: decorates to that hierarchy, children of, or
149
Another note is that these objects are currently only used when there is
150
no InventoryEntry available - i.e. for unversioned objects.
151
Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
154
def __eq__(self, other):
155
# yes, this us ugly, TODO: best practice __eq__ style.
156
return (isinstance(other, TreeEntry)
157
and other.__class__ == self.__class__)
159
def kind_character(self):
163
class TreeDirectory(TreeEntry):
164
"""See TreeEntry. This is a directory in a working tree."""
166
def __eq__(self, other):
167
return (isinstance(other, TreeDirectory)
168
and other.__class__ == self.__class__)
170
def kind_character(self):
174
class TreeFile(TreeEntry):
175
"""See TreeEntry. This is a regular file in a working tree."""
177
def __eq__(self, other):
178
return (isinstance(other, TreeFile)
179
and other.__class__ == self.__class__)
181
def kind_character(self):
185
class TreeLink(TreeEntry):
186
"""See TreeEntry. This is a symlink in a working tree."""
188
def __eq__(self, other):
189
return (isinstance(other, TreeLink)
190
and other.__class__ == self.__class__)
192
def kind_character(self):
196
class WorkingTree(bzrlib.mutabletree.MutableTree):
197
"""Working copy tree.
199
The inventory is held in the `Branch` working-inventory, and the
200
files are in a directory on disk.
202
It is possible for a `WorkingTree` to have a filename which is
203
not listed in the Inventory and vice versa.
206
def __init__(self, basedir='.',
207
branch=DEPRECATED_PARAMETER,
213
"""Construct a WorkingTree for basedir.
215
If the branch is not supplied, it is opened automatically.
216
If the branch is supplied, it must be the branch for this basedir.
217
(branch.base is not cross checked, because for remote branches that
218
would be meaningless).
220
self._format = _format
221
self.bzrdir = _bzrdir
223
# not created via open etc.
224
warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
225
"Please use bzrdir.open_workingtree or WorkingTree.open().",
228
wt = WorkingTree.open(basedir)
229
self._branch = wt.branch
230
self.basedir = wt.basedir
231
self._control_files = wt._control_files
232
self._hashcache = wt._hashcache
233
self._set_inventory(wt._inventory, dirty=False)
234
self._format = wt._format
235
self.bzrdir = wt.bzrdir
236
assert isinstance(basedir, basestring), \
237
"base directory %r is not a string" % basedir
238
basedir = safe_unicode(basedir)
239
mutter("opening working tree %r", basedir)
240
if deprecated_passed(branch):
242
warnings.warn("WorkingTree(..., branch=XXX) is deprecated"
243
" as of bzr 0.8. Please use bzrdir.open_workingtree() or"
244
" WorkingTree.open().",
248
self._branch = branch
250
self._branch = self.bzrdir.open_branch()
251
self.basedir = realpath(basedir)
252
# if branch is at our basedir and is a format 6 or less
253
if isinstance(self._format, WorkingTreeFormat2):
254
# share control object
255
self._control_files = self.branch.control_files
257
# assume all other formats have their own control files.
258
assert isinstance(_control_files, LockableFiles), \
259
"_control_files must be a LockableFiles, not %r" \
261
self._control_files = _control_files
262
# update the whole cache up front and write to disk if anything changed;
263
# in the future we might want to do this more selectively
264
# two possible ways offer themselves : in self._unlock, write the cache
265
# if needed, or, when the cache sees a change, append it to the hash
266
# cache file, and have the parser take the most recent entry for a
268
wt_trans = self.bzrdir.get_workingtree_transport(None)
269
cache_filename = wt_trans.local_abspath('stat-cache')
270
self._hashcache = hashcache.HashCache(basedir, cache_filename,
271
self._control_files._file_mode)
274
# is this scan needed ? it makes things kinda slow.
281
if _inventory is None:
282
self._inventory_is_modified = False
283
self.read_working_inventory()
285
# the caller of __init__ has provided an inventory,
286
# we assume they know what they are doing - as its only
287
# the Format factory and creation methods that are
288
# permitted to do this.
289
self._set_inventory(_inventory, dirty=False)
290
self._after_opening()
292
def _after_opening(self):
293
"""Called after the workingtree is opened.
295
self._warn_deprecated_format()
298
fget=lambda self: self._branch,
299
doc="""The branch this WorkingTree is connected to.
301
This cannot be set - it is reflective of the actual disk structure
302
the working tree has been constructed from.
305
def break_lock(self):
306
"""Break a lock if one is present from another instance.
308
Uses the ui factory to ask for confirmation if the lock may be from
311
This will probe the repository for its lock as well.
313
self._control_files.break_lock()
314
self.branch.break_lock()
316
def requires_rich_root(self):
317
return self._format.requires_rich_root
319
def supports_tree_reference(self):
322
def _set_inventory(self, inv, dirty):
323
"""Set the internal cached inventory.
325
:param inv: The inventory to set.
326
:param dirty: A boolean indicating whether the inventory is the same
327
logical inventory as whats on disk. If True the inventory is not
328
the same and should be written to disk or data will be lost, if
329
False then the inventory is the same as that on disk and any
330
serialisation would be unneeded overhead.
332
assert inv.root is not None
333
self._inventory = inv
334
self._inventory_is_modified = dirty
337
def open(path=None, _unsupported=False):
338
"""Open an existing working tree at path.
342
path = os.path.getcwdu()
343
control = bzrdir.BzrDir.open(path, _unsupported)
344
return control.open_workingtree(_unsupported)
347
def open_containing(path=None):
348
"""Open an existing working tree which has its root about path.
350
This probes for a working tree at path and searches upwards from there.
352
Basically we keep looking up until we find the control directory or
353
run into /. If there isn't one, raises NotBranchError.
354
TODO: give this a new exception.
355
If there is one, it is returned, along with the unused portion of path.
357
:return: The WorkingTree that contains 'path', and the rest of path
360
path = osutils.getcwd()
361
control, relpath = bzrdir.BzrDir.open_containing(path)
363
return control.open_workingtree(), relpath
366
def open_downlevel(path=None):
367
"""Open an unsupported working tree.
369
Only intended for advanced situations like upgrading part of a bzrdir.
371
return WorkingTree.open(path, _unsupported=True)
373
# should be deprecated - this is slow and in any case treating them as a
374
# container is (we now know) bad style -- mbp 20070302
375
## @deprecated_method(zero_fifteen)
377
"""Iterate through file_ids for this tree.
379
file_ids are in a WorkingTree if they are in the working inventory
380
and the working file exists.
382
inv = self._inventory
383
for path, ie in inv.iter_entries():
384
if osutils.lexists(self.abspath(path)):
388
return "<%s of %s>" % (self.__class__.__name__,
389
getattr(self, 'basedir', None))
391
def abspath(self, filename):
392
return pathjoin(self.basedir, filename)
394
def basis_tree(self):
395
"""Return RevisionTree for the current last revision.
397
If the left most parent is a ghost then the returned tree will be an
398
empty tree - one obtained by calling repository.revision_tree(None).
401
revision_id = self.get_parent_ids()[0]
403
# no parents, return an empty revision tree.
404
# in the future this should return the tree for
405
# 'empty:' - the implicit root empty tree.
406
return self.branch.repository.revision_tree(None)
408
return self.revision_tree(revision_id)
409
except errors.NoSuchRevision:
411
# No cached copy available, retrieve from the repository.
412
# FIXME? RBC 20060403 should we cache the inventory locally
415
return self.branch.repository.revision_tree(revision_id)
416
except errors.RevisionNotPresent:
417
# the basis tree *may* be a ghost or a low level error may have
418
# occured. If the revision is present, its a problem, if its not
420
if self.branch.repository.has_revision(revision_id):
422
# the basis tree is a ghost so return an empty tree.
423
return self.branch.repository.revision_tree(None)
426
@deprecated_method(zero_eight)
427
def create(branch, directory):
428
"""Create a workingtree for branch at directory.
430
If existing_directory already exists it must have a .bzr directory.
431
If it does not exist, it will be created.
433
This returns a new WorkingTree object for the new checkout.
435
TODO FIXME RBC 20060124 when we have checkout formats in place this
436
should accept an optional revisionid to checkout [and reject this if
437
checking out into the same dir as a pre-checkout-aware branch format.]
439
XXX: When BzrDir is present, these should be created through that
442
warnings.warn('delete WorkingTree.create', stacklevel=3)
443
transport = get_transport(directory)
444
if branch.bzrdir.root_transport.base == transport.base:
446
return branch.bzrdir.create_workingtree()
447
# different directory,
448
# create a branch reference
449
# and now a working tree.
450
raise NotImplementedError
453
@deprecated_method(zero_eight)
454
def create_standalone(directory):
455
"""Create a checkout and a branch and a repo at directory.
457
Directory must exist and be empty.
459
please use BzrDir.create_standalone_workingtree
461
return bzrdir.BzrDir.create_standalone_workingtree(directory)
463
def relpath(self, path):
464
"""Return the local path portion from a given path.
466
The path may be absolute or relative. If its a relative path it is
467
interpreted relative to the python current working directory.
469
return osutils.relpath(self.basedir, path)
471
def has_filename(self, filename):
472
return osutils.lexists(self.abspath(filename))
474
def get_file(self, file_id):
475
file_id = osutils.safe_file_id(file_id)
476
return self.get_file_byname(self.id2path(file_id))
478
def get_file_text(self, file_id):
479
file_id = osutils.safe_file_id(file_id)
480
return self.get_file(file_id).read()
482
def get_file_byname(self, filename):
483
return file(self.abspath(filename), 'rb')
486
def annotate_iter(self, file_id):
487
"""See Tree.annotate_iter
489
This implementation will use the basis tree implementation if possible.
490
Lines not in the basis are attributed to CURRENT_REVISION
492
If there are pending merges, lines added by those merges will be
493
incorrectly attributed to CURRENT_REVISION (but after committing, the
494
attribution will be correct).
496
file_id = osutils.safe_file_id(file_id)
497
basis = self.basis_tree()
500
changes = self._iter_changes(basis, True, [self.id2path(file_id)],
501
require_versioned=True).next()
502
changed_content, kind = changes[2], changes[6]
503
if not changed_content:
504
return basis.annotate_iter(file_id)
508
if kind[0] != 'file':
511
old_lines = list(basis.annotate_iter(file_id))
513
for tree in self.branch.repository.revision_trees(
514
self.get_parent_ids()[1:]):
515
if file_id not in tree:
517
old.append(list(tree.annotate_iter(file_id)))
518
return annotate.reannotate(old, self.get_file(file_id).readlines(),
523
def get_parent_ids(self):
524
"""See Tree.get_parent_ids.
526
This implementation reads the pending merges list and last_revision
527
value and uses that to decide what the parents list should be.
529
last_rev = self._last_revision()
535
merges_file = self._control_files.get('pending-merges')
536
except errors.NoSuchFile:
539
for l in merges_file.readlines():
540
revision_id = osutils.safe_revision_id(l.rstrip('\n'))
541
parents.append(revision_id)
545
def get_root_id(self):
546
"""Return the id of this trees root"""
547
return self._inventory.root.file_id
549
def _get_store_filename(self, file_id):
550
## XXX: badly named; this is not in the store at all
551
file_id = osutils.safe_file_id(file_id)
552
return self.abspath(self.id2path(file_id))
555
def clone(self, to_bzrdir, revision_id=None, basis=None):
556
"""Duplicate this working tree into to_bzr, including all state.
558
Specifically modified files are kept as modified, but
559
ignored and unknown files are discarded.
561
If you want to make a new line of development, see bzrdir.sprout()
564
If not None, the cloned tree will have its last revision set to
565
revision, and and difference between the source trees last revision
566
and this one merged in.
569
If not None, a closer copy of a tree which may have some files in
570
common, and which file content should be preferentially copied from.
572
# assumes the target bzr dir format is compatible.
573
result = self._format.initialize(to_bzrdir)
574
self.copy_content_into(result, revision_id)
578
def copy_content_into(self, tree, revision_id=None):
579
"""Copy the current content and user files of this tree into tree."""
580
tree.set_root_id(self.get_root_id())
581
if revision_id is None:
582
merge.transform_tree(tree, self)
584
# TODO now merge from tree.last_revision to revision (to preserve
585
# user local changes)
586
merge.transform_tree(tree, self)
587
tree.set_parent_ids([revision_id])
589
def id2abspath(self, file_id):
590
file_id = osutils.safe_file_id(file_id)
591
return self.abspath(self.id2path(file_id))
593
def has_id(self, file_id):
594
# files that have been deleted are excluded
595
file_id = osutils.safe_file_id(file_id)
597
if not inv.has_id(file_id):
599
path = inv.id2path(file_id)
600
return osutils.lexists(self.abspath(path))
602
def has_or_had_id(self, file_id):
603
file_id = osutils.safe_file_id(file_id)
604
if file_id == self.inventory.root.file_id:
606
return self.inventory.has_id(file_id)
608
__contains__ = has_id
610
def get_file_size(self, file_id):
611
file_id = osutils.safe_file_id(file_id)
612
return os.path.getsize(self.id2abspath(file_id))
615
def get_file_sha1(self, file_id, path=None, stat_value=None):
616
file_id = osutils.safe_file_id(file_id)
618
path = self._inventory.id2path(file_id)
619
return self._hashcache.get_sha1(path, stat_value)
621
def get_file_mtime(self, file_id, path=None):
622
file_id = osutils.safe_file_id(file_id)
624
path = self.inventory.id2path(file_id)
625
return os.lstat(self.abspath(path)).st_mtime
627
if not supports_executable():
628
def is_executable(self, file_id, path=None):
629
file_id = osutils.safe_file_id(file_id)
630
return self._inventory[file_id].executable
632
def is_executable(self, file_id, path=None):
634
file_id = osutils.safe_file_id(file_id)
635
path = self.id2path(file_id)
636
mode = os.lstat(self.abspath(path)).st_mode
637
return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
639
@needs_tree_write_lock
640
def _add(self, files, ids, kinds):
641
"""See MutableTree._add."""
642
# TODO: Re-adding a file that is removed in the working copy
643
# should probably put it back with the previous ID.
644
# the read and write working inventory should not occur in this
645
# function - they should be part of lock_write and unlock.
646
inv = self.read_working_inventory()
647
for f, file_id, kind in zip(files, ids, kinds):
648
assert kind is not None
650
inv.add_path(f, kind=kind)
652
file_id = osutils.safe_file_id(file_id)
653
inv.add_path(f, kind=kind, file_id=file_id)
654
self._write_inventory(inv)
656
@needs_tree_write_lock
657
def _gather_kinds(self, files, kinds):
658
"""See MutableTree._gather_kinds."""
659
for pos, f in enumerate(files):
660
if kinds[pos] is None:
661
fullpath = normpath(self.abspath(f))
663
kinds[pos] = file_kind(fullpath)
665
if e.errno == errno.ENOENT:
666
raise errors.NoSuchFile(fullpath)
669
def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
670
"""Add revision_id as a parent.
672
This is equivalent to retrieving the current list of parent ids
673
and setting the list to its value plus revision_id.
675
:param revision_id: The revision id to add to the parent list. It may
676
be a ghost revision as long as its not the first parent to be added,
677
or the allow_leftmost_as_ghost parameter is set True.
678
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
680
parents = self.get_parent_ids() + [revision_id]
681
self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
682
or allow_leftmost_as_ghost)
684
@needs_tree_write_lock
685
def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
686
"""Add revision_id, tree tuple as a parent.
688
This is equivalent to retrieving the current list of parent trees
689
and setting the list to its value plus parent_tuple. See also
690
add_parent_tree_id - if you only have a parent id available it will be
691
simpler to use that api. If you have the parent already available, using
692
this api is preferred.
694
:param parent_tuple: The (revision id, tree) to add to the parent list.
695
If the revision_id is a ghost, pass None for the tree.
696
:param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
698
parent_ids = self.get_parent_ids() + [parent_tuple[0]]
699
if len(parent_ids) > 1:
700
# the leftmost may have already been a ghost, preserve that if it
702
allow_leftmost_as_ghost = True
703
self.set_parent_ids(parent_ids,
704
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
706
@needs_tree_write_lock
707
def add_pending_merge(self, *revision_ids):
708
# TODO: Perhaps should check at this point that the
709
# history of the revision is actually present?
710
parents = self.get_parent_ids()
712
for rev_id in revision_ids:
713
if rev_id in parents:
715
parents.append(rev_id)
718
self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
720
@deprecated_method(zero_eleven)
722
def pending_merges(self):
723
"""Return a list of pending merges.
725
These are revisions that have been merged into the working
726
directory but not yet committed.
728
As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
729
instead - which is available on all tree objects.
731
return self.get_parent_ids()[1:]
733
def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
734
"""Common ghost checking functionality from set_parent_*.
736
This checks that the left hand-parent exists if there are any
739
if len(revision_ids) > 0:
740
leftmost_id = revision_ids[0]
741
if (not allow_leftmost_as_ghost and not
742
self.branch.repository.has_revision(leftmost_id)):
743
raise errors.GhostRevisionUnusableHere(leftmost_id)
745
def _set_merges_from_parent_ids(self, parent_ids):
746
merges = parent_ids[1:]
747
self._control_files.put_bytes('pending-merges', '\n'.join(merges))
749
@needs_tree_write_lock
750
def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
751
"""Set the parent ids to revision_ids.
753
See also set_parent_trees. This api will try to retrieve the tree data
754
for each element of revision_ids from the trees repository. If you have
755
tree data already available, it is more efficient to use
756
set_parent_trees rather than set_parent_ids. set_parent_ids is however
757
an easier API to use.
759
:param revision_ids: The revision_ids to set as the parent ids of this
760
working tree. Any of these may be ghosts.
762
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
763
self._check_parents_for_ghosts(revision_ids,
764
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
766
if len(revision_ids) > 0:
767
self.set_last_revision(revision_ids[0])
769
self.set_last_revision(None)
771
self._set_merges_from_parent_ids(revision_ids)
773
@needs_tree_write_lock
774
def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
775
"""See MutableTree.set_parent_trees."""
776
parent_ids = [osutils.safe_revision_id(rev) for (rev, tree) in parents_list]
778
self._check_parents_for_ghosts(parent_ids,
779
allow_leftmost_as_ghost=allow_leftmost_as_ghost)
781
if len(parent_ids) == 0:
782
leftmost_parent_id = None
783
leftmost_parent_tree = None
785
leftmost_parent_id, leftmost_parent_tree = parents_list[0]
787
if self._change_last_revision(leftmost_parent_id):
788
if leftmost_parent_tree is None:
789
# If we don't have a tree, fall back to reading the
790
# parent tree from the repository.
791
self._cache_basis_inventory(leftmost_parent_id)
793
inv = leftmost_parent_tree.inventory
794
xml = self._create_basis_xml_from_inventory(
795
leftmost_parent_id, inv)
796
self._write_basis_inventory(xml)
797
self._set_merges_from_parent_ids(parent_ids)
799
@needs_tree_write_lock
800
def set_pending_merges(self, rev_list):
801
parents = self.get_parent_ids()
802
leftmost = parents[:1]
803
new_parents = leftmost + rev_list
804
self.set_parent_ids(new_parents)
806
@needs_tree_write_lock
807
def set_merge_modified(self, modified_hashes):
809
for file_id, hash in modified_hashes.iteritems():
810
yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
811
self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
813
def _put_rio(self, filename, stanzas, header):
814
self._must_be_locked()
815
my_file = rio_file(stanzas, header)
816
self._control_files.put(filename, my_file)
818
@needs_write_lock # because merge pulls data into the branch.
819
def merge_from_branch(self, branch, to_revision=None):
820
"""Merge from a branch into this working tree.
822
:param branch: The branch to merge from.
823
:param to_revision: If non-None, the merge will merge to to_revision,
824
but not beyond it. to_revision does not need to be in the history
825
of the branch when it is supplied. If None, to_revision defaults to
826
branch.last_revision().
828
from bzrlib.merge import Merger, Merge3Merger
829
pb = bzrlib.ui.ui_factory.nested_progress_bar()
831
merger = Merger(self.branch, this_tree=self, pb=pb)
832
merger.pp = ProgressPhase("Merge phase", 5, pb)
833
merger.pp.next_phase()
834
# check that there are no
836
merger.check_basis(check_clean=True, require_commits=False)
837
if to_revision is None:
838
to_revision = branch.last_revision()
840
to_revision = osutils.safe_revision_id(to_revision)
841
merger.other_rev_id = to_revision
842
if merger.other_rev_id is None:
843
raise error.NoCommits(branch)
844
self.branch.fetch(branch, last_revision=merger.other_rev_id)
845
merger.other_basis = merger.other_rev_id
846
merger.other_tree = self.branch.repository.revision_tree(
848
merger.other_branch = branch
849
merger.pp.next_phase()
851
if merger.base_rev_id == merger.other_rev_id:
852
raise errors.PointlessMerge
853
merger.backup_files = False
854
merger.merge_type = Merge3Merger
855
merger.set_interesting_files(None)
856
merger.show_base = False
857
merger.reprocess = False
858
conflicts = merger.do_merge()
865
def merge_modified(self):
866
"""Return a dictionary of files modified by a merge.
868
The list is initialized by WorkingTree.set_merge_modified, which is
869
typically called after we make some automatic updates to the tree
872
This returns a map of file_id->sha1, containing only files which are
873
still in the working inventory and have that text hash.
876
hashfile = self._control_files.get('merge-hashes')
877
except errors.NoSuchFile:
881
if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
882
raise errors.MergeModifiedFormatError()
883
except StopIteration:
884
raise errors.MergeModifiedFormatError()
885
for s in RioReader(hashfile):
886
# RioReader reads in Unicode, so convert file_ids back to utf8
887
file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
888
if file_id not in self.inventory:
890
text_hash = s.get("hash")
891
if text_hash == self.get_file_sha1(file_id):
892
merge_hashes[file_id] = text_hash
896
def mkdir(self, path, file_id=None):
897
"""See MutableTree.mkdir()."""
899
file_id = generate_ids.gen_file_id(os.path.basename(path))
900
os.mkdir(self.abspath(path))
901
self.add(path, file_id, 'directory')
904
def get_symlink_target(self, file_id):
905
file_id = osutils.safe_file_id(file_id)
906
return os.readlink(self.id2abspath(file_id))
909
def subsume(self, other_tree):
910
def add_children(inventory, entry):
911
for child_entry in entry.children.values():
912
inventory._byid[child_entry.file_id] = child_entry
913
if child_entry.kind == 'directory':
914
add_children(inventory, child_entry)
915
if other_tree.get_root_id() == self.get_root_id():
916
raise errors.BadSubsumeSource(self, other_tree,
917
'Trees have the same root')
919
other_tree_path = self.relpath(other_tree.basedir)
920
except errors.PathNotChild:
921
raise errors.BadSubsumeSource(self, other_tree,
922
'Tree is not contained by the other')
923
new_root_parent = self.path2id(osutils.dirname(other_tree_path))
924
if new_root_parent is None:
925
raise errors.BadSubsumeSource(self, other_tree,
926
'Parent directory is not versioned.')
927
# We need to ensure that the result of a fetch will have a
928
# versionedfile for the other_tree root, and only fetching into
929
# RepositoryKnit2 guarantees that.
930
if not self.branch.repository.supports_rich_root():
931
raise errors.SubsumeTargetNeedsUpgrade(other_tree)
932
other_tree.lock_tree_write()
934
new_parents = other_tree.get_parent_ids()
935
other_root = other_tree.inventory.root
936
other_root.parent_id = new_root_parent
937
other_root.name = osutils.basename(other_tree_path)
938
self.inventory.add(other_root)
939
add_children(self.inventory, other_root)
940
self._write_inventory(self.inventory)
941
# normally we don't want to fetch whole repositories, but i think
942
# here we really do want to consolidate the whole thing.
943
for parent_id in other_tree.get_parent_ids():
944
self.branch.fetch(other_tree.branch, parent_id)
945
self.add_parent_tree_id(parent_id)
948
other_tree.bzrdir.retire_bzrdir()
950
@needs_tree_write_lock
951
def extract(self, file_id, format=None):
952
"""Extract a subtree from this tree.
954
A new branch will be created, relative to the path for this tree.
958
segments = osutils.splitpath(path)
959
transport = self.branch.bzrdir.root_transport
960
for name in segments:
961
transport = transport.clone(name)
964
except errors.FileExists:
968
sub_path = self.id2path(file_id)
969
branch_transport = mkdirs(sub_path)
971
format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
973
branch_transport.mkdir('.')
974
except errors.FileExists:
976
branch_bzrdir = format.initialize_on_transport(branch_transport)
978
repo = branch_bzrdir.find_repository()
979
except errors.NoRepositoryPresent:
980
repo = branch_bzrdir.create_repository()
981
assert repo.supports_rich_root()
983
if not repo.supports_rich_root():
984
raise errors.RootNotRich()
985
new_branch = branch_bzrdir.create_branch()
986
new_branch.pull(self.branch)
987
for parent_id in self.get_parent_ids():
988
new_branch.fetch(self.branch, parent_id)
989
tree_transport = self.bzrdir.root_transport.clone(sub_path)
990
if tree_transport.base != branch_transport.base:
991
tree_bzrdir = format.initialize_on_transport(tree_transport)
992
branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
994
tree_bzrdir = branch_bzrdir
995
wt = tree_bzrdir.create_workingtree(NULL_REVISION)
996
wt.set_parent_ids(self.get_parent_ids())
997
my_inv = self.inventory
998
child_inv = Inventory(root_id=None)
999
new_root = my_inv[file_id]
1000
my_inv.remove_recursive_id(file_id)
1001
new_root.parent_id = None
1002
child_inv.add(new_root)
1003
self._write_inventory(my_inv)
1004
wt._write_inventory(child_inv)
1007
def _serialize(self, inventory, out_file):
1008
xml5.serializer_v5.write_inventory(self._inventory, out_file)
1010
def _deserialize(selt, in_file):
1011
return xml5.serializer_v5.read_inventory(in_file)
1014
"""Write the in memory inventory to disk."""
1015
# TODO: Maybe this should only write on dirty ?
1016
if self._control_files._lock_mode != 'w':
1017
raise errors.NotWriteLocked(self)
1019
self._serialize(self._inventory, sio)
1021
self._control_files.put('inventory', sio)
1022
self._inventory_is_modified = False
1024
def _kind(self, relpath):
1025
return osutils.file_kind(self.abspath(relpath))
1027
def list_files(self, include_root=False):
1028
"""Recursively list all files as (path, class, kind, id, entry).
1030
Lists, but does not descend into unversioned directories.
1032
This does not include files that have been deleted in this
1035
Skips the control directory.
1037
# list_files is an iterator, so @needs_read_lock doesn't work properly
1038
# with it. So callers should be careful to always read_lock the tree.
1039
if not self.is_locked():
1040
raise errors.ObjectNotLocked(self)
1042
inv = self.inventory
1043
if include_root is True:
1044
yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1045
# Convert these into local objects to save lookup times
1046
pathjoin = osutils.pathjoin
1047
file_kind = self._kind
1049
# transport.base ends in a slash, we want the piece
1050
# between the last two slashes
1051
transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
1053
fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1055
# directory file_id, relative path, absolute path, reverse sorted children
1056
children = os.listdir(self.basedir)
1058
# jam 20060527 The kernel sized tree seems equivalent whether we
1059
# use a deque and popleft to keep them sorted, or if we use a plain
1060
# list and just reverse() them.
1061
children = collections.deque(children)
1062
stack = [(inv.root.file_id, u'', self.basedir, children)]
1064
from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1067
f = children.popleft()
1068
## TODO: If we find a subdirectory with its own .bzr
1069
## directory, then that is a separate tree and we
1070
## should exclude it.
1072
# the bzrdir for this tree
1073
if transport_base_dir == f:
1076
# we know that from_dir_relpath and from_dir_abspath never end in a slash
1077
# and 'f' doesn't begin with one, we can do a string op, rather
1078
# than the checks of pathjoin(), all relative paths will have an extra slash
1080
fp = from_dir_relpath + '/' + f
1083
fap = from_dir_abspath + '/' + f
1085
f_ie = inv.get_child(from_dir_id, f)
1088
elif self.is_ignored(fp[1:]):
1091
# we may not have found this file, because of a unicode issue
1092
f_norm, can_access = osutils.normalized_filename(f)
1093
if f == f_norm or not can_access:
1094
# No change, so treat this file normally
1097
# this file can be accessed by a normalized path
1098
# check again if it is versioned
1099
# these lines are repeated here for performance
1101
fp = from_dir_relpath + '/' + f
1102
fap = from_dir_abspath + '/' + f
1103
f_ie = inv.get_child(from_dir_id, f)
1106
elif self.is_ignored(fp[1:]):
1113
# make a last minute entry
1115
yield fp[1:], c, fk, f_ie.file_id, f_ie
1118
yield fp[1:], c, fk, None, fk_entries[fk]()
1120
yield fp[1:], c, fk, None, TreeEntry()
1123
if fk != 'directory':
1126
# But do this child first
1127
new_children = os.listdir(fap)
1129
new_children = collections.deque(new_children)
1130
stack.append((f_ie.file_id, fp, fap, new_children))
1131
# Break out of inner loop,
1132
# so that we start outer loop with child
1135
# if we finished all children, pop it off the stack
1138
@needs_tree_write_lock
1139
def move(self, from_paths, to_dir=None, after=False, **kwargs):
1142
to_dir must exist in the inventory.
1144
If to_dir exists and is a directory, the files are moved into
1145
it, keeping their old names.
1147
Note that to_dir is only the last component of the new name;
1148
this doesn't change the directory.
1150
For each entry in from_paths the move mode will be determined
1153
The first mode moves the file in the filesystem and updates the
1154
inventory. The second mode only updates the inventory without
1155
touching the file on the filesystem. This is the new mode introduced
1158
move uses the second mode if 'after == True' and the target is not
1159
versioned but present in the working tree.
1161
move uses the second mode if 'after == False' and the source is
1162
versioned but no longer in the working tree, and the target is not
1163
versioned but present in the working tree.
1165
move uses the first mode if 'after == False' and the source is
1166
versioned and present in the working tree, and the target is not
1167
versioned and not present in the working tree.
1169
Everything else results in an error.
1171
This returns a list of (from_path, to_path) pairs for each
1172
entry that is moved.
1177
# check for deprecated use of signature
1179
to_dir = kwargs.get('to_name', None)
1181
raise TypeError('You must supply a target directory')
1183
symbol_versioning.warn('The parameter to_name was deprecated'
1184
' in version 0.13. Use to_dir instead',
1187
# check destination directory
1188
assert not isinstance(from_paths, basestring)
1189
inv = self.inventory
1190
to_abs = self.abspath(to_dir)
1191
if not isdir(to_abs):
1192
raise errors.BzrMoveFailedError('',to_dir,
1193
errors.NotADirectory(to_abs))
1194
if not self.has_filename(to_dir):
1195
raise errors.BzrMoveFailedError('',to_dir,
1196
errors.NotInWorkingDirectory(to_dir))
1197
to_dir_id = inv.path2id(to_dir)
1198
if to_dir_id is None:
1199
raise errors.BzrMoveFailedError('',to_dir,
1200
errors.NotVersionedError(path=str(to_dir)))
1202
to_dir_ie = inv[to_dir_id]
1203
if to_dir_ie.kind != 'directory':
1204
raise errors.BzrMoveFailedError('',to_dir,
1205
errors.NotADirectory(to_abs))
1207
# create rename entries and tuples
1208
for from_rel in from_paths:
1209
from_tail = splitpath(from_rel)[-1]
1210
from_id = inv.path2id(from_rel)
1212
raise errors.BzrMoveFailedError(from_rel,to_dir,
1213
errors.NotVersionedError(path=str(from_rel)))
1215
from_entry = inv[from_id]
1216
from_parent_id = from_entry.parent_id
1217
to_rel = pathjoin(to_dir, from_tail)
1218
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1220
from_tail=from_tail,
1221
from_parent_id=from_parent_id,
1222
to_rel=to_rel, to_tail=from_tail,
1223
to_parent_id=to_dir_id)
1224
rename_entries.append(rename_entry)
1225
rename_tuples.append((from_rel, to_rel))
1227
# determine which move mode to use. checks also for movability
1228
rename_entries = self._determine_mv_mode(rename_entries, after)
1230
original_modified = self._inventory_is_modified
1233
self._inventory_is_modified = True
1234
self._move(rename_entries)
1236
# restore the inventory on error
1237
self._inventory_is_modified = original_modified
1239
self._write_inventory(inv)
1240
return rename_tuples
1242
def _determine_mv_mode(self, rename_entries, after=False):
1243
"""Determines for each from-to pair if both inventory and working tree
1244
or only the inventory has to be changed.
1246
Also does basic plausability tests.
1248
inv = self.inventory
1250
for rename_entry in rename_entries:
1251
# store to local variables for easier reference
1252
from_rel = rename_entry.from_rel
1253
from_id = rename_entry.from_id
1254
to_rel = rename_entry.to_rel
1255
to_id = inv.path2id(to_rel)
1256
only_change_inv = False
1258
# check the inventory for source and destination
1260
raise errors.BzrMoveFailedError(from_rel,to_rel,
1261
errors.NotVersionedError(path=str(from_rel)))
1262
if to_id is not None:
1263
raise errors.BzrMoveFailedError(from_rel,to_rel,
1264
errors.AlreadyVersionedError(path=str(to_rel)))
1266
# try to determine the mode for rename (only change inv or change
1267
# inv and file system)
1269
if not self.has_filename(to_rel):
1270
raise errors.BzrMoveFailedError(from_id,to_rel,
1271
errors.NoSuchFile(path=str(to_rel),
1272
extra="New file has not been created yet"))
1273
only_change_inv = True
1274
elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1275
only_change_inv = True
1276
elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1277
only_change_inv = False
1279
# something is wrong, so lets determine what exactly
1280
if not self.has_filename(from_rel) and \
1281
not self.has_filename(to_rel):
1282
raise errors.BzrRenameFailedError(from_rel,to_rel,
1283
errors.PathsDoNotExist(paths=(str(from_rel),
1286
raise errors.RenameFailedFilesExist(from_rel, to_rel,
1287
extra="(Use --after to update the Bazaar id)")
1288
rename_entry.only_change_inv = only_change_inv
1289
return rename_entries
1291
def _move(self, rename_entries):
1292
"""Moves a list of files.
1294
Depending on the value of the flag 'only_change_inv', the
1295
file will be moved on the file system or not.
1297
inv = self.inventory
1300
for entry in rename_entries:
1302
self._move_entry(entry)
1304
self._rollback_move(moved)
1308
def _rollback_move(self, moved):
1309
"""Try to rollback a previous move in case of an filesystem error."""
1310
inv = self.inventory
1313
self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1314
entry.to_tail, entry.to_parent_id, entry.from_rel,
1315
entry.from_tail, entry.from_parent_id,
1316
entry.only_change_inv))
1317
except errors.BzrMoveFailedError, e:
1318
raise errors.BzrMoveFailedError( '', '', "Rollback failed."
1319
" The working tree is in an inconsistent state."
1320
" Please consider doing a 'bzr revert'."
1321
" Error message is: %s" % e)
1323
def _move_entry(self, entry):
1324
inv = self.inventory
1325
from_rel_abs = self.abspath(entry.from_rel)
1326
to_rel_abs = self.abspath(entry.to_rel)
1327
if from_rel_abs == to_rel_abs:
1328
raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
1329
"Source and target are identical.")
1331
if not entry.only_change_inv:
1333
osutils.rename(from_rel_abs, to_rel_abs)
1335
raise errors.BzrMoveFailedError(entry.from_rel,
1337
inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1339
@needs_tree_write_lock
1340
def rename_one(self, from_rel, to_rel, after=False):
1343
This can change the directory or the filename or both.
1345
rename_one has several 'modes' to work. First, it can rename a physical
1346
file and change the file_id. That is the normal mode. Second, it can
1347
only change the file_id without touching any physical file. This is
1348
the new mode introduced in version 0.15.
1350
rename_one uses the second mode if 'after == True' and 'to_rel' is not
1351
versioned but present in the working tree.
1353
rename_one uses the second mode if 'after == False' and 'from_rel' is
1354
versioned but no longer in the working tree, and 'to_rel' is not
1355
versioned but present in the working tree.
1357
rename_one uses the first mode if 'after == False' and 'from_rel' is
1358
versioned and present in the working tree, and 'to_rel' is not
1359
versioned and not present in the working tree.
1361
Everything else results in an error.
1363
inv = self.inventory
1366
# create rename entries and tuples
1367
from_tail = splitpath(from_rel)[-1]
1368
from_id = inv.path2id(from_rel)
1370
raise errors.BzrRenameFailedError(from_rel,to_rel,
1371
errors.NotVersionedError(path=str(from_rel)))
1372
from_entry = inv[from_id]
1373
from_parent_id = from_entry.parent_id
1374
to_dir, to_tail = os.path.split(to_rel)
1375
to_dir_id = inv.path2id(to_dir)
1376
rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
1378
from_tail=from_tail,
1379
from_parent_id=from_parent_id,
1380
to_rel=to_rel, to_tail=to_tail,
1381
to_parent_id=to_dir_id)
1382
rename_entries.append(rename_entry)
1384
# determine which move mode to use. checks also for movability
1385
rename_entries = self._determine_mv_mode(rename_entries, after)
1387
# check if the target changed directory and if the target directory is
1389
if to_dir_id is None:
1390
raise errors.BzrMoveFailedError(from_rel,to_rel,
1391
errors.NotVersionedError(path=str(to_dir)))
1393
# all checks done. now we can continue with our actual work
1394
mutter('rename_one:\n'
1399
' to_dir_id {%s}\n',
1400
from_id, from_rel, to_rel, to_dir, to_dir_id)
1402
self._move(rename_entries)
1403
self._write_inventory(inv)
1405
class _RenameEntry(object):
1406
def __init__(self, from_rel, from_id, from_tail, from_parent_id,
1407
to_rel, to_tail, to_parent_id, only_change_inv=False):
1408
self.from_rel = from_rel
1409
self.from_id = from_id
1410
self.from_tail = from_tail
1411
self.from_parent_id = from_parent_id
1412
self.to_rel = to_rel
1413
self.to_tail = to_tail
1414
self.to_parent_id = to_parent_id
1415
self.only_change_inv = only_change_inv
1419
"""Return all unknown files.
1421
These are files in the working directory that are not versioned or
1422
control files or ignored.
1424
# force the extras method to be fully executed before returning, to
1425
# prevent race conditions with the lock
1427
[subp for subp in self.extras() if not self.is_ignored(subp)])
1429
def _warn_deprecated_format(self):
1430
ui.ui_factory.recommend_upgrade(
1431
self._format.get_format_description(),
1434
@needs_tree_write_lock
1435
def unversion(self, file_ids):
1436
"""Remove the file ids in file_ids from the current versioned set.
1438
When a file_id is unversioned, all of its children are automatically
1441
:param file_ids: The file ids to stop versioning.
1442
:raises: NoSuchId if any fileid is not currently versioned.
1444
for file_id in file_ids:
1445
file_id = osutils.safe_file_id(file_id)
1446
if self._inventory.has_id(file_id):
1447
self._inventory.remove_recursive_id(file_id)
1449
raise errors.NoSuchId(self, file_id)
1451
# in the future this should just set a dirty bit to wait for the
1452
# final unlock. However, until all methods of workingtree start
1453
# with the current in -memory inventory rather than triggering
1454
# a read, it is more complex - we need to teach read_inventory
1455
# to know when to read, and when to not read first... and possibly
1456
# to save first when the in memory one may be corrupted.
1457
# so for now, we just only write it if it is indeed dirty.
1459
self._write_inventory(self._inventory)
1461
@deprecated_method(zero_eight)
1462
def iter_conflicts(self):
1463
"""List all files in the tree that have text or content conflicts.
1464
DEPRECATED. Use conflicts instead."""
1465
return self._iter_conflicts()
1467
def _iter_conflicts(self):
1469
for info in self.list_files():
1471
stem = get_conflicted_stem(path)
1474
if stem not in conflicted:
1475
conflicted.add(stem)
1479
def pull(self, source, overwrite=False, stop_revision=None,
1480
change_reporter=None):
1481
top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1484
pp = ProgressPhase("Pull phase", 2, top_pb)
1486
old_revision_info = self.branch.last_revision_info()
1487
basis_tree = self.basis_tree()
1488
count = self.branch.pull(source, overwrite, stop_revision)
1489
new_revision_info = self.branch.last_revision_info()
1490
if new_revision_info != old_revision_info:
1492
repository = self.branch.repository
1493
pb = bzrlib.ui.ui_factory.nested_progress_bar()
1494
basis_tree.lock_read()
1496
new_basis_tree = self.branch.basis_tree()
1503
change_reporter=change_reporter)
1504
if (basis_tree.inventory.root is None and
1505
new_basis_tree.inventory.root is not None):
1506
self.set_root_id(new_basis_tree.inventory.root.file_id)
1510
# TODO - dedup parents list with things merged by pull ?
1511
# reuse the revisiontree we merged against to set the new
1513
parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1514
# we have to pull the merge trees out again, because
1515
# merge_inner has set the ids. - this corner is not yet
1516
# layered well enough to prevent double handling.
1517
# XXX TODO: Fix the double handling: telling the tree about
1518
# the already known parent data is wasteful.
1519
merges = self.get_parent_ids()[1:]
1520
parent_trees.extend([
1521
(parent, repository.revision_tree(parent)) for
1523
self.set_parent_trees(parent_trees)
1530
def put_file_bytes_non_atomic(self, file_id, bytes):
1531
"""See MutableTree.put_file_bytes_non_atomic."""
1532
file_id = osutils.safe_file_id(file_id)
1533
stream = file(self.id2abspath(file_id), 'wb')
1538
# TODO: update the hashcache here ?
1541
"""Yield all unversioned files in this WorkingTree.
1543
If there are any unversioned directories then only the directory is
1544
returned, not all its children. But if there are unversioned files
1545
under a versioned subdirectory, they are returned.
1547
Currently returned depth-first, sorted by name within directories.
1548
This is the same order used by 'osutils.walkdirs'.
1550
## TODO: Work from given directory downwards
1551
for path, dir_entry in self.inventory.directories():
1552
# mutter("search for unknowns in %r", path)
1553
dirabs = self.abspath(path)
1554
if not isdir(dirabs):
1555
# e.g. directory deleted
1559
for subf in os.listdir(dirabs):
1562
if subf not in dir_entry.children:
1563
subf_norm, can_access = osutils.normalized_filename(subf)
1564
if subf_norm != subf and can_access:
1565
if subf_norm not in dir_entry.children:
1566
fl.append(subf_norm)
1572
subp = pathjoin(path, subf)
1575
def ignored_files(self):
1576
"""Yield list of PATH, IGNORE_PATTERN"""
1577
for subp in self.extras():
1578
pat = self.is_ignored(subp)
1582
def get_ignore_list(self):
1583
"""Return list of ignore patterns.
1585
Cached in the Tree object after the first call.
1587
ignoreset = getattr(self, '_ignoreset', None)
1588
if ignoreset is not None:
1591
ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1592
ignore_globs.update(ignores.get_runtime_ignores())
1593
ignore_globs.update(ignores.get_user_ignores())
1594
if self.has_filename(bzrlib.IGNORE_FILENAME):
1595
f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1597
ignore_globs.update(ignores.parse_ignore_file(f))
1600
self._ignoreset = ignore_globs
1603
def _flush_ignore_list_cache(self):
1604
"""Resets the cached ignore list to force a cache rebuild."""
1605
self._ignoreset = None
1606
self._ignoreglobster = None
1608
def is_ignored(self, filename):
1609
r"""Check whether the filename matches an ignore pattern.
1611
Patterns containing '/' or '\' need to match the whole path;
1612
others match against only the last component.
1614
If the file is ignored, returns the pattern which caused it to
1615
be ignored, otherwise None. So this can simply be used as a
1616
boolean if desired."""
1617
if getattr(self, '_ignoreglobster', None) is None:
1618
self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1619
return self._ignoreglobster.match(filename)
1621
def kind(self, file_id):
1622
return file_kind(self.id2abspath(file_id))
1624
def _comparison_data(self, entry, path):
1625
abspath = self.abspath(path)
1627
stat_value = os.lstat(abspath)
1629
if getattr(e, 'errno', None) == errno.ENOENT:
1636
mode = stat_value.st_mode
1637
kind = osutils.file_kind_from_stat_mode(mode)
1638
if not supports_executable():
1639
executable = entry.executable
1641
executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1642
return kind, executable, stat_value
1644
def _file_size(self, entry, stat_value):
1645
return stat_value.st_size
1647
def last_revision(self):
1648
"""Return the last revision of the branch for this tree.
1650
This format tree does not support a separate marker for last-revision
1651
compared to the branch.
1653
See MutableTree.last_revision
1655
return self._last_revision()
1658
def _last_revision(self):
1659
"""helper for get_parent_ids."""
1660
return self.branch.last_revision()
1662
def is_locked(self):
1663
return self._control_files.is_locked()
1665
def _must_be_locked(self):
1666
if not self.is_locked():
1667
raise errors.ObjectNotLocked(self)
1669
def lock_read(self):
1670
"""See Branch.lock_read, and WorkingTree.unlock."""
1671
if not self.is_locked():
1673
self.branch.lock_read()
1675
return self._control_files.lock_read()
1677
self.branch.unlock()
1680
def lock_tree_write(self):
1681
"""See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1682
if not self.is_locked():
1684
self.branch.lock_read()
1686
return self._control_files.lock_write()
1688
self.branch.unlock()
1691
def lock_write(self):
1692
"""See MutableTree.lock_write, and WorkingTree.unlock."""
1693
if not self.is_locked():
1695
self.branch.lock_write()
1697
return self._control_files.lock_write()
1699
self.branch.unlock()
1702
def get_physical_lock_status(self):
1703
return self._control_files.get_physical_lock_status()
1705
def _basis_inventory_name(self):
1706
return 'basis-inventory-cache'
1708
def _reset_data(self):
1709
"""Reset transient data that cannot be revalidated."""
1710
self._inventory_is_modified = False
1711
result = self._deserialize(self._control_files.get('inventory'))
1712
self._set_inventory(result, dirty=False)
1714
@needs_tree_write_lock
1715
def set_last_revision(self, new_revision):
1716
"""Change the last revision in the working tree."""
1717
new_revision = osutils.safe_revision_id(new_revision)
1718
if self._change_last_revision(new_revision):
1719
self._cache_basis_inventory(new_revision)
1721
def _change_last_revision(self, new_revision):
1722
"""Template method part of set_last_revision to perform the change.
1724
This is used to allow WorkingTree3 instances to not affect branch
1725
when their last revision is set.
1727
if new_revision is None:
1728
self.branch.set_revision_history([])
1731
self.branch.generate_revision_history(new_revision)
1732
except errors.NoSuchRevision:
1733
# not present in the repo - dont try to set it deeper than the tip
1734
self.branch.set_revision_history([new_revision])
1737
def _write_basis_inventory(self, xml):
1738
"""Write the basis inventory XML to the basis-inventory file"""
1739
assert isinstance(xml, str), 'serialised xml must be bytestring.'
1740
path = self._basis_inventory_name()
1742
self._control_files.put(path, sio)
1744
def _create_basis_xml_from_inventory(self, revision_id, inventory):
1745
"""Create the text that will be saved in basis-inventory"""
1746
# TODO: jam 20070209 This should be redundant, as the revision_id
1747
# as all callers should have already converted the revision_id to
1749
inventory.revision_id = osutils.safe_revision_id(revision_id)
1750
return xml7.serializer_v7.write_inventory_to_string(inventory)
1752
def _cache_basis_inventory(self, new_revision):
1753
"""Cache new_revision as the basis inventory."""
1754
# TODO: this should allow the ready-to-use inventory to be passed in,
1755
# as commit already has that ready-to-use [while the format is the
1758
# this double handles the inventory - unpack and repack -
1759
# but is easier to understand. We can/should put a conditional
1760
# in here based on whether the inventory is in the latest format
1761
# - perhaps we should repack all inventories on a repository
1763
# the fast path is to copy the raw xml from the repository. If the
1764
# xml contains 'revision_id="', then we assume the right
1765
# revision_id is set. We must check for this full string, because a
1766
# root node id can legitimately look like 'revision_id' but cannot
1768
xml = self.branch.repository.get_inventory_xml(new_revision)
1769
firstline = xml.split('\n', 1)[0]
1770
if (not 'revision_id="' in firstline or
1771
'format="7"' not in firstline):
1772
inv = self.branch.repository.deserialise_inventory(
1774
xml = self._create_basis_xml_from_inventory(new_revision, inv)
1775
self._write_basis_inventory(xml)
1776
except (errors.NoSuchRevision, errors.RevisionNotPresent):
1779
def read_basis_inventory(self):
1780
"""Read the cached basis inventory."""
1781
path = self._basis_inventory_name()
1782
return self._control_files.get(path).read()
1785
def read_working_inventory(self):
1786
"""Read the working inventory.
1788
:raises errors.InventoryModified: read_working_inventory will fail
1789
when the current in memory inventory has been modified.
1791
# conceptually this should be an implementation detail of the tree.
1792
# XXX: Deprecate this.
1793
# ElementTree does its own conversion from UTF-8, so open in
1795
if self._inventory_is_modified:
1796
raise errors.InventoryModified(self)
1797
result = self._deserialize(self._control_files.get('inventory'))
1798
self._set_inventory(result, dirty=False)
1801
@needs_tree_write_lock
1802
def remove(self, files, verbose=False, to_file=None):
1803
"""Remove nominated files from the working inventory..
1805
This does not remove their text. This does not run on XXX on what? RBC
1807
TODO: Refuse to remove modified files unless --force is given?
1809
TODO: Do something useful with directories.
1811
TODO: Should this remove the text or not? Tough call; not
1812
removing may be useful and the user can just use use rm, and
1813
is the opposite of add. Removing it is consistent with most
1814
other tools. Maybe an option.
1816
## TODO: Normalize names
1817
## TODO: Remove nested loops; better scalability
1818
if isinstance(files, basestring):
1821
inv = self.inventory
1823
# do this before any modifications
1825
fid = inv.path2id(f)
1827
note("%s is not versioned."%f)
1830
# having remove it, it must be either ignored or unknown
1831
if self.is_ignored(f):
1835
textui.show_status(new_status, inv[fid].kind, f,
1839
self._write_inventory(inv)
1841
@needs_tree_write_lock
1842
def revert(self, filenames, old_tree=None, backups=True,
1843
pb=DummyProgress(), report_changes=False):
1844
from bzrlib.conflicts import resolve
1845
if old_tree is None:
1846
old_tree = self.basis_tree()
1847
conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1849
if not len(filenames):
1850
self.set_parent_ids(self.get_parent_ids()[:1])
1853
resolve(self, filenames, ignore_misses=True)
1856
def revision_tree(self, revision_id):
1857
"""See Tree.revision_tree.
1859
WorkingTree can supply revision_trees for the basis revision only
1860
because there is only one cached inventory in the bzr directory.
1862
if revision_id == self.last_revision():
1864
xml = self.read_basis_inventory()
1865
except errors.NoSuchFile:
1869
inv = xml7.serializer_v7.read_inventory_from_string(xml)
1870
# dont use the repository revision_tree api because we want
1871
# to supply the inventory.
1872
if inv.revision_id == revision_id:
1873
return revisiontree.RevisionTree(self.branch.repository,
1875
except errors.BadInventoryFormat:
1877
# raise if there was no inventory, or if we read the wrong inventory.
1878
raise errors.NoSuchRevisionInTree(self, revision_id)
1880
# XXX: This method should be deprecated in favour of taking in a proper
1881
# new Inventory object.
1882
@needs_tree_write_lock
1883
def set_inventory(self, new_inventory_list):
1884
from bzrlib.inventory import (Inventory,
1889
inv = Inventory(self.get_root_id())
1890
for path, file_id, parent, kind in new_inventory_list:
1891
name = os.path.basename(path)
1894
# fixme, there should be a factory function inv,add_??
1895
if kind == 'directory':
1896
inv.add(InventoryDirectory(file_id, name, parent))
1897
elif kind == 'file':
1898
inv.add(InventoryFile(file_id, name, parent))
1899
elif kind == 'symlink':
1900
inv.add(InventoryLink(file_id, name, parent))
1902
raise errors.BzrError("unknown kind %r" % kind)
1903
self._write_inventory(inv)
1905
@needs_tree_write_lock
1906
def set_root_id(self, file_id):
1907
"""Set the root id for this tree."""
1910
symbol_versioning.warn(symbol_versioning.zero_twelve
1911
% 'WorkingTree.set_root_id with fileid=None',
1916
file_id = osutils.safe_file_id(file_id)
1917
self._set_root_id(file_id)
1919
def _set_root_id(self, file_id):
1920
"""Set the root id for this tree, in a format specific manner.
1922
:param file_id: The file id to assign to the root. It must not be
1923
present in the current inventory or an error will occur. It must
1924
not be None, but rather a valid file id.
1926
inv = self._inventory
1927
orig_root_id = inv.root.file_id
1928
# TODO: it might be nice to exit early if there was nothing
1929
# to do, saving us from trigger a sync on unlock.
1930
self._inventory_is_modified = True
1931
# we preserve the root inventory entry object, but
1932
# unlinkit from the byid index
1933
del inv._byid[inv.root.file_id]
1934
inv.root.file_id = file_id
1935
# and link it into the index with the new changed id.
1936
inv._byid[inv.root.file_id] = inv.root
1937
# and finally update all children to reference the new id.
1938
# XXX: this should be safe to just look at the root.children
1939
# list, not the WHOLE INVENTORY.
1942
if entry.parent_id == orig_root_id:
1943
entry.parent_id = inv.root.file_id
1946
"""See Branch.unlock.
1948
WorkingTree locking just uses the Branch locking facilities.
1949
This is current because all working trees have an embedded branch
1950
within them. IF in the future, we were to make branch data shareable
1951
between multiple working trees, i.e. via shared storage, then we
1952
would probably want to lock both the local tree, and the branch.
1954
raise NotImplementedError(self.unlock)
1957
"""Update a working tree along its branch.
1959
This will update the branch if its bound too, which means we have
1960
multiple trees involved:
1962
- The new basis tree of the master.
1963
- The old basis tree of the branch.
1964
- The old basis tree of the working tree.
1965
- The current working tree state.
1967
Pathologically, all three may be different, and non-ancestors of each
1968
other. Conceptually we want to:
1970
- Preserve the wt.basis->wt.state changes
1971
- Transform the wt.basis to the new master basis.
1972
- Apply a merge of the old branch basis to get any 'local' changes from
1974
- Restore the wt.basis->wt.state changes.
1976
There isn't a single operation at the moment to do that, so we:
1977
- Merge current state -> basis tree of the master w.r.t. the old tree
1979
- Do a 'normal' merge of the old branch basis if it is relevant.
1981
if self.branch.get_master_branch() is not None:
1983
update_branch = True
1985
self.lock_tree_write()
1986
update_branch = False
1989
old_tip = self.branch.update()
1992
return self._update_tree(old_tip)
1996
@needs_tree_write_lock
1997
def _update_tree(self, old_tip=None):
1998
"""Update a tree to the master branch.
2000
:param old_tip: if supplied, the previous tip revision the branch,
2001
before it was changed to the master branch's tip.
2003
# here if old_tip is not None, it is the old tip of the branch before
2004
# it was updated from the master branch. This should become a pending
2005
# merge in the working tree to preserve the user existing work. we
2006
# cant set that until we update the working trees last revision to be
2007
# one from the new branch, because it will just get absorbed by the
2008
# parent de-duplication logic.
2010
# We MUST save it even if an error occurs, because otherwise the users
2011
# local work is unreferenced and will appear to have been lost.
2015
last_rev = self.get_parent_ids()[0]
2018
if last_rev != self.branch.last_revision():
2019
# merge tree state up to new branch tip.
2020
basis = self.basis_tree()
2023
to_tree = self.branch.basis_tree()
2024
if basis.inventory.root is None:
2025
self.set_root_id(to_tree.inventory.root.file_id)
2027
result += merge.merge_inner(
2034
# TODO - dedup parents list with things merged by pull ?
2035
# reuse the tree we've updated to to set the basis:
2036
parent_trees = [(self.branch.last_revision(), to_tree)]
2037
merges = self.get_parent_ids()[1:]
2038
# Ideally we ask the tree for the trees here, that way the working
2039
# tree can decide whether to give us teh entire tree or give us a
2040
# lazy initialised tree. dirstate for instance will have the trees
2041
# in ram already, whereas a last-revision + basis-inventory tree
2042
# will not, but also does not need them when setting parents.
2043
for parent in merges:
2044
parent_trees.append(
2045
(parent, self.branch.repository.revision_tree(parent)))
2046
if old_tip is not None:
2047
parent_trees.append(
2048
(old_tip, self.branch.repository.revision_tree(old_tip)))
2049
self.set_parent_trees(parent_trees)
2050
last_rev = parent_trees[0][0]
2052
# the working tree had the same last-revision as the master
2053
# branch did. We may still have pivot local work from the local
2054
# branch into old_tip:
2055
if old_tip is not None:
2056
self.add_parent_tree_id(old_tip)
2057
if old_tip and old_tip != last_rev:
2058
# our last revision was not the prior branch last revision
2059
# and we have converted that last revision to a pending merge.
2060
# base is somewhere between the branch tip now
2061
# and the now pending merge
2063
# Since we just modified the working tree and inventory, flush out
2064
# the current state, before we modify it again.
2065
# TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
2066
# requires it only because TreeTransform directly munges the
2067
# inventory and calls tree._write_inventory(). Ultimately we
2068
# should be able to remove this extra flush.
2070
from bzrlib.revision import common_ancestor
2072
base_rev_id = common_ancestor(self.branch.last_revision(),
2074
self.branch.repository)
2075
except errors.NoCommonAncestor:
2077
base_tree = self.branch.repository.revision_tree(base_rev_id)
2078
other_tree = self.branch.repository.revision_tree(old_tip)
2079
result += merge.merge_inner(
2086
def _write_hashcache_if_dirty(self):
2087
"""Write out the hashcache if it is dirty."""
2088
if self._hashcache.needs_write:
2090
self._hashcache.write()
2092
if e.errno not in (errno.EPERM, errno.EACCES):
2094
# TODO: jam 20061219 Should this be a warning? A single line
2095
# warning might be sufficient to let the user know what
2097
mutter('Could not write hashcache for %s\nError: %s',
2098
self._hashcache.cache_file_name(), e)
2100
@needs_tree_write_lock
2101
def _write_inventory(self, inv):
2102
"""Write inventory as the current inventory."""
2103
self._set_inventory(inv, dirty=True)
2106
def set_conflicts(self, arg):
2107
raise errors.UnsupportedOperation(self.set_conflicts, self)
2109
def add_conflicts(self, arg):
2110
raise errors.UnsupportedOperation(self.add_conflicts, self)
2113
def conflicts(self):
2114
conflicts = _mod_conflicts.ConflictList()
2115
for conflicted in self._iter_conflicts():
2118
if file_kind(self.abspath(conflicted)) != "file":
2120
except errors.NoSuchFile:
2123
for suffix in ('.THIS', '.OTHER'):
2125
kind = file_kind(self.abspath(conflicted+suffix))
2128
except errors.NoSuchFile:
2132
ctype = {True: 'text conflict', False: 'contents conflict'}[text]
2133
conflicts.append(_mod_conflicts.Conflict.factory(ctype,
2135
file_id=self.path2id(conflicted)))
2138
def walkdirs(self, prefix=""):
2139
"""Walk the directories of this tree.
2141
This API returns a generator, which is only valid during the current
2142
tree transaction - within a single lock_read or lock_write duration.
2144
If the tree is not locked, it may cause an error to be raised, depending
2145
on the tree implementation.
2147
disk_top = self.abspath(prefix)
2148
if disk_top.endswith('/'):
2149
disk_top = disk_top[:-1]
2150
top_strip_len = len(disk_top) + 1
2151
inventory_iterator = self._walkdirs(prefix)
2152
disk_iterator = osutils.walkdirs(disk_top, prefix)
2154
current_disk = disk_iterator.next()
2155
disk_finished = False
2157
if e.errno != errno.ENOENT:
2160
disk_finished = True
2162
current_inv = inventory_iterator.next()
2163
inv_finished = False
2164
except StopIteration:
2167
while not inv_finished or not disk_finished:
2168
if not disk_finished:
2169
# strip out .bzr dirs
2170
if current_disk[0][1][top_strip_len:] == '':
2171
# osutils.walkdirs can be made nicer -
2172
# yield the path-from-prefix rather than the pathjoined
2174
bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
2175
if current_disk[1][bzrdir_loc][0] == '.bzr':
2176
# we dont yield the contents of, or, .bzr itself.
2177
del current_disk[1][bzrdir_loc]
2179
# everything is unknown
2182
# everything is missing
2185
direction = cmp(current_inv[0][0], current_disk[0][0])
2187
# disk is before inventory - unknown
2188
dirblock = [(relpath, basename, kind, stat, None, None) for
2189
relpath, basename, kind, stat, top_path in current_disk[1]]
2190
yield (current_disk[0][0], None), dirblock
2192
current_disk = disk_iterator.next()
2193
except StopIteration:
2194
disk_finished = True
2196
# inventory is before disk - missing.
2197
dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2198
for relpath, basename, dkind, stat, fileid, kind in
2200
yield (current_inv[0][0], current_inv[0][1]), dirblock
2202
current_inv = inventory_iterator.next()
2203
except StopIteration:
2206
# versioned present directory
2207
# merge the inventory and disk data together
2209
for relpath, subiterator in itertools.groupby(sorted(
2210
current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
2211
path_elements = list(subiterator)
2212
if len(path_elements) == 2:
2213
inv_row, disk_row = path_elements
2214
# versioned, present file
2215
dirblock.append((inv_row[0],
2216
inv_row[1], disk_row[2],
2217
disk_row[3], inv_row[4],
2219
elif len(path_elements[0]) == 5:
2221
dirblock.append((path_elements[0][0],
2222
path_elements[0][1], path_elements[0][2],
2223
path_elements[0][3], None, None))
2224
elif len(path_elements[0]) == 6:
2225
# versioned, absent file.
2226
dirblock.append((path_elements[0][0],
2227
path_elements[0][1], 'unknown', None,
2228
path_elements[0][4], path_elements[0][5]))
2230
raise NotImplementedError('unreachable code')
2231
yield current_inv[0], dirblock
2233
current_inv = inventory_iterator.next()
2234
except StopIteration:
2237
current_disk = disk_iterator.next()
2238
except StopIteration:
2239
disk_finished = True
2241
def _walkdirs(self, prefix=""):
2242
_directory = 'directory'
2243
# get the root in the inventory
2244
inv = self.inventory
2245
top_id = inv.path2id(prefix)
2249
pending = [(prefix, '', _directory, None, top_id, None)]
2252
currentdir = pending.pop()
2253
# 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2254
top_id = currentdir[4]
2256
relroot = currentdir[0] + '/'
2259
# FIXME: stash the node in pending
2261
for name, child in entry.sorted_children():
2262
dirblock.append((relroot + name, name, child.kind, None,
2263
child.file_id, child.kind
2265
yield (currentdir[0], entry.file_id), dirblock
2266
# push the user specified dirs from dirblock
2267
for dir in reversed(dirblock):
2268
if dir[2] == _directory:
2271
@needs_tree_write_lock
2272
def auto_resolve(self):
2273
"""Automatically resolve text conflicts according to contents.
2275
Only text conflicts are auto_resolvable. Files with no conflict markers
2276
are considered 'resolved', because bzr always puts conflict markers
2277
into files that have text conflicts. The corresponding .THIS .BASE and
2278
.OTHER files are deleted, as per 'resolve'.
2279
:return: a tuple of ConflictLists: (un_resolved, resolved).
2281
un_resolved = _mod_conflicts.ConflictList()
2282
resolved = _mod_conflicts.ConflictList()
2283
conflict_re = re.compile('^(<{7}|={7}|>{7})')
2284
for conflict in self.conflicts():
2285
if (conflict.typestring != 'text conflict' or
2286
self.kind(conflict.file_id) != 'file'):
2287
un_resolved.append(conflict)
2289
my_file = open(self.id2abspath(conflict.file_id), 'rb')
2291
for line in my_file:
2292
if conflict_re.search(line):
2293
un_resolved.append(conflict)
2296
resolved.append(conflict)
2299
resolved.remove_files(self)
2300
self.set_conflicts(un_resolved)
2301
return un_resolved, resolved
2304
class WorkingTree2(WorkingTree):
2305
"""This is the Format 2 working tree.
2307
This was the first weave based working tree.
2308
- uses os locks for locking.
2309
- uses the branch last-revision.
2312
def lock_tree_write(self):
2313
"""See WorkingTree.lock_tree_write().
2315
In Format2 WorkingTrees we have a single lock for the branch and tree
2316
so lock_tree_write() degrades to lock_write().
2318
self.branch.lock_write()
2320
return self._control_files.lock_write()
2322
self.branch.unlock()
2326
# we share control files:
2327
if self._control_files._lock_count == 3:
2328
# _inventory_is_modified is always False during a read lock.
2329
if self._inventory_is_modified:
2331
self._write_hashcache_if_dirty()
2333
# reverse order of locking.
2335
return self._control_files.unlock()
2337
self.branch.unlock()
2340
class WorkingTree3(WorkingTree):
2341
"""This is the Format 3 working tree.
2343
This differs from the base WorkingTree by:
2344
- having its own file lock
2345
- having its own last-revision property.
2347
This is new in bzr 0.8
2351
def _last_revision(self):
2352
"""See Mutable.last_revision."""
2354
return osutils.safe_revision_id(
2355
self._control_files.get('last-revision').read())
2356
except errors.NoSuchFile:
2359
def _change_last_revision(self, revision_id):
2360
"""See WorkingTree._change_last_revision."""
2361
if revision_id is None or revision_id == NULL_REVISION:
2363
self._control_files._transport.delete('last-revision')
2364
except errors.NoSuchFile:
2368
self._control_files.put_bytes('last-revision', revision_id)
2371
@needs_tree_write_lock
2372
def set_conflicts(self, conflicts):
2373
self._put_rio('conflicts', conflicts.to_stanzas(),
2376
@needs_tree_write_lock
2377
def add_conflicts(self, new_conflicts):
2378
conflict_set = set(self.conflicts())
2379
conflict_set.update(set(list(new_conflicts)))
2380
self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
2381
key=_mod_conflicts.Conflict.sort_key)))
2384
def conflicts(self):
2386
confile = self._control_files.get('conflicts')
2387
except errors.NoSuchFile:
2388
return _mod_conflicts.ConflictList()
2390
if confile.next() != CONFLICT_HEADER_1 + '\n':
2391
raise errors.ConflictFormatError()
2392
except StopIteration:
2393
raise errors.ConflictFormatError()
2394
return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2397
if self._control_files._lock_count == 1:
2398
# _inventory_is_modified is always False during a read lock.
2399
if self._inventory_is_modified:
2401
self._write_hashcache_if_dirty()
2402
# reverse order of locking.
2404
return self._control_files.unlock()
2406
self.branch.unlock()
2409
def get_conflicted_stem(path):
2410
for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
2411
if path.endswith(suffix):
2412
return path[:-len(suffix)]
2415
@deprecated_function(zero_eight)
2416
def is_control_file(filename):
2417
"""See WorkingTree.is_control_filename(filename)."""
2418
## FIXME: better check
2419
filename = normpath(filename)
2420
while filename != '':
2421
head, tail = os.path.split(filename)
2422
## mutter('check %r for control file' % ((head, tail),))
2425
if filename == head:
2431
class WorkingTreeFormat(object):
2432
"""An encapsulation of the initialization and open routines for a format.
2434
Formats provide three things:
2435
* An initialization routine,
2439
Formats are placed in an dict by their format string for reference
2440
during workingtree opening. Its not required that these be instances, they
2441
can be classes themselves with class methods - it simply depends on
2442
whether state is needed for a given format or not.
2444
Once a format is deprecated, just deprecate the initialize and open
2445
methods on the format class. Do not deprecate the object, as the
2446
object will be created every time regardless.
2449
_default_format = None
2450
"""The default format used for new trees."""
2453
"""The known formats."""
2455
requires_rich_root = False
2458
def find_format(klass, a_bzrdir):
2459
"""Return the format for the working tree object in a_bzrdir."""
2461
transport = a_bzrdir.get_workingtree_transport(None)
2462
format_string = transport.get("format").read()
2463
return klass._formats[format_string]
2464
except errors.NoSuchFile:
2465
raise errors.NoWorkingTree(base=transport.base)
2467
raise errors.UnknownFormatError(format=format_string)
2469
def __eq__(self, other):
2470
return self.__class__ is other.__class__
2472
def __ne__(self, other):
2473
return not (self == other)
2476
def get_default_format(klass):
2477
"""Return the current default format."""
2478
return klass._default_format
2480
def get_format_string(self):
2481
"""Return the ASCII format string that identifies this format."""
2482
raise NotImplementedError(self.get_format_string)
2484
def get_format_description(self):
2485
"""Return the short description for this format."""
2486
raise NotImplementedError(self.get_format_description)
2488
def is_supported(self):
2489
"""Is this format supported?
2491
Supported formats can be initialized and opened.
2492
Unsupported formats may not support initialization or committing or
2493
some other features depending on the reason for not being supported.
2498
def register_format(klass, format):
2499
klass._formats[format.get_format_string()] = format
2502
def set_default_format(klass, format):
2503
klass._default_format = format
2506
def unregister_format(klass, format):
2507
assert klass._formats[format.get_format_string()] is format
2508
del klass._formats[format.get_format_string()]
2512
class WorkingTreeFormat2(WorkingTreeFormat):
2513
"""The second working tree format.
2515
This format modified the hash cache from the format 1 hash cache.
2518
def get_format_description(self):
2519
"""See WorkingTreeFormat.get_format_description()."""
2520
return "Working tree format 2"
2522
def stub_initialize_remote(self, control_files):
2523
"""As a special workaround create critical control files for a remote working tree
2525
This ensures that it can later be updated and dealt with locally,
2526
since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
2527
no working tree. (See bug #43064).
2531
xml5.serializer_v5.write_inventory(inv, sio)
2533
control_files.put('inventory', sio)
2535
control_files.put_bytes('pending-merges', '')
2538
def initialize(self, a_bzrdir, revision_id=None):
2539
"""See WorkingTreeFormat.initialize()."""
2540
if not isinstance(a_bzrdir.transport, LocalTransport):
2541
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2542
branch = a_bzrdir.open_branch()
2543
if revision_id is not None:
2544
revision_id = osutils.safe_revision_id(revision_id)
2547
revision_history = branch.revision_history()
2549
position = revision_history.index(revision_id)
2551
raise errors.NoSuchRevision(branch, revision_id)
2552
branch.set_revision_history(revision_history[:position + 1])
2555
revision = branch.last_revision()
2557
wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2563
basis_tree = branch.repository.revision_tree(revision)
2564
if basis_tree.inventory.root is not None:
2565
wt.set_root_id(basis_tree.inventory.root.file_id)
2566
# set the parent list and cache the basis tree.
2567
wt.set_parent_trees([(revision, basis_tree)])
2568
transform.build_tree(basis_tree, wt)
2572
super(WorkingTreeFormat2, self).__init__()
2573
self._matchingbzrdir = bzrdir.BzrDirFormat6()
2575
def open(self, a_bzrdir, _found=False):
2576
"""Return the WorkingTree object for a_bzrdir
2578
_found is a private parameter, do not use it. It is used to indicate
2579
if format probing has already been done.
2582
# we are being called directly and must probe.
2583
raise NotImplementedError
2584
if not isinstance(a_bzrdir.transport, LocalTransport):
2585
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2586
return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2592
class WorkingTreeFormat3(WorkingTreeFormat):
2593
"""The second working tree format updated to record a format marker.
2596
- exists within a metadir controlling .bzr
2597
- includes an explicit version marker for the workingtree control
2598
files, separate from the BzrDir format
2599
- modifies the hash cache format
2601
- uses a LockDir to guard access for writes.
2604
def get_format_string(self):
2605
"""See WorkingTreeFormat.get_format_string()."""
2606
return "Bazaar-NG Working Tree format 3"
2608
def get_format_description(self):
2609
"""See WorkingTreeFormat.get_format_description()."""
2610
return "Working tree format 3"
2612
_lock_file_name = 'lock'
2613
_lock_class = LockDir
2615
_tree_class = WorkingTree3
2617
def __get_matchingbzrdir(self):
2618
return bzrdir.BzrDirMetaFormat1()
2620
_matchingbzrdir = property(__get_matchingbzrdir)
2622
def _open_control_files(self, a_bzrdir):
2623
transport = a_bzrdir.get_workingtree_transport(None)
2624
return LockableFiles(transport, self._lock_file_name,
2627
def initialize(self, a_bzrdir, revision_id=None):
2628
"""See WorkingTreeFormat.initialize().
2630
revision_id allows creating a working tree at a different
2631
revision than the branch is at.
2633
if not isinstance(a_bzrdir.transport, LocalTransport):
2634
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2635
transport = a_bzrdir.get_workingtree_transport(self)
2636
control_files = self._open_control_files(a_bzrdir)
2637
control_files.create_lock()
2638
control_files.lock_write()
2639
control_files.put_utf8('format', self.get_format_string())
2640
branch = a_bzrdir.open_branch()
2641
if revision_id is None:
2642
revision_id = branch.last_revision()
2644
revision_id = osutils.safe_revision_id(revision_id)
2645
# WorkingTree3 can handle an inventory which has a unique root id.
2646
# as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
2647
# those trees. And because there isn't a format bump inbetween, we
2648
# are maintaining compatibility with older clients.
2649
# inv = Inventory(root_id=gen_root_id())
2650
inv = self._initial_inventory()
2651
wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2657
_control_files=control_files)
2658
wt.lock_tree_write()
2660
basis_tree = branch.repository.revision_tree(revision_id)
2661
# only set an explicit root id if there is one to set.
2662
if basis_tree.inventory.root is not None:
2663
wt.set_root_id(basis_tree.inventory.root.file_id)
2664
if revision_id == NULL_REVISION:
2665
wt.set_parent_trees([])
2667
wt.set_parent_trees([(revision_id, basis_tree)])
2668
transform.build_tree(basis_tree, wt)
2670
# Unlock in this order so that the unlock-triggers-flush in
2671
# WorkingTree is given a chance to fire.
2672
control_files.unlock()
2676
def _initial_inventory(self):
2680
super(WorkingTreeFormat3, self).__init__()
2682
def open(self, a_bzrdir, _found=False):
2683
"""Return the WorkingTree object for a_bzrdir
2685
_found is a private parameter, do not use it. It is used to indicate
2686
if format probing has already been done.
2689
# we are being called directly and must probe.
2690
raise NotImplementedError
2691
if not isinstance(a_bzrdir.transport, LocalTransport):
2692
raise errors.NotLocalUrl(a_bzrdir.transport.base)
2693
return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
2695
def _open(self, a_bzrdir, control_files):
2696
"""Open the tree itself.
2698
:param a_bzrdir: the dir for the tree.
2699
:param control_files: the control files for the tree.
2701
return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2705
_control_files=control_files)
2708
return self.get_format_string()
2711
__default_format = WorkingTreeFormat4()
2712
WorkingTreeFormat.register_format(__default_format)
2713
WorkingTreeFormat.register_format(WorkingTreeFormat3())
2714
WorkingTreeFormat.set_default_format(__default_format)
2715
# formats which have no format string are not discoverable
2716
# and not independently creatable, so are not registered.
2717
_legacy_formats = [WorkingTreeFormat2(),
2721
class WorkingTreeTestProviderAdapter(object):
2722
"""A tool to generate a suite testing multiple workingtree formats at once.
2724
This is done by copying the test once for each transport and injecting
2725
the transport_server, transport_readonly_server, and workingtree_format
2726
classes into each copy. Each copy is also given a new id() to make it
2730
def __init__(self, transport_server, transport_readonly_server, formats):
2731
self._transport_server = transport_server
2732
self._transport_readonly_server = transport_readonly_server
2733
self._formats = formats
2735
def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2736
"""Clone test for adaption."""
2737
new_test = deepcopy(test)
2738
new_test.transport_server = self._transport_server
2739
new_test.transport_readonly_server = self._transport_readonly_server
2740
new_test.bzrdir_format = bzrdir_format
2741
new_test.workingtree_format = workingtree_format
2742
def make_new_test_id():
2743
new_id = "%s(%s)" % (test.id(), variation)
2744
return lambda: new_id
2745
new_test.id = make_new_test_id()
2748
def adapt(self, test):
2749
from bzrlib.tests import TestSuite
2750
result = TestSuite()
2751
for workingtree_format, bzrdir_format in self._formats:
2752
new_test = self._clone_test(
2755
workingtree_format, workingtree_format.__class__.__name__)
2756
result.addTest(new_test)